PageRenderTime 53ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/controller/user.php

https://github.com/alugo/Goteo
PHP | 783 lines | 526 code | 90 blank | 167 comment | 130 complexity | 57be566eb863c1dd5b983e1b5cb40f69 MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /*
  3. * Copyright (C) 2012 Platoniq y Fundación Fuentes Abiertas (see README for details)
  4. * This file is part of Goteo.
  5. *
  6. * Goteo is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Goteo is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with Goteo. If not, see <http://www.gnu.org/licenses/agpl.txt>.
  18. *
  19. */
  20. namespace Goteo\Controller {
  21. use Goteo\Core\Redirection,
  22. Goteo\Core\Error,
  23. Goteo\Core\View,
  24. Goteo\Model,
  25. Goteo\Library\Feed,
  26. Goteo\Library\Text,
  27. Goteo\Library\Message,
  28. Goteo\Library\Listing;
  29. class User extends \Goteo\Core\Controller {
  30. /**
  31. * Atajo al perfil de usuario.
  32. * @param string $id Nombre de usuario
  33. */
  34. public function index($id, $show = '') {
  35. throw new Redirection('/user/profile/' . $id . '/' . $show, Redirection::PERMANENT);
  36. }
  37. public function raw($id) {
  38. $user = Model\User::get($id, LANG);
  39. \trace($user);
  40. die;
  41. }
  42. /**
  43. * Inicio de sesión.
  44. * Si no se le pasan parámetros carga el tpl de identificación.
  45. *
  46. * @param string $username Nombre de usuario
  47. * @param string $password Contraseña
  48. */
  49. public function login($username = '') {
  50. // si venimos de la página de aportar
  51. if (isset($_POST['amount'])) {
  52. $_SESSION['invest-amount'] = $_POST['amount'];
  53. $msg = Text::get('user-login-required-login');
  54. $msg .= (!empty($_POST['amount'])) ? '. ' . Text::get('invest-alert-investing') . ' ' . $_POST['amount'] . '&euro;' : '';
  55. Message::Info($msg);
  56. }
  57. if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['login'])) {
  58. $username = \strtolower($_POST['username']);
  59. $password = $_POST['password'];
  60. if (false !== ($user = (\Goteo\Model\User::login($username, $password)))) {
  61. $_SESSION['user'] = $user;
  62. // creamos una cookie
  63. setcookie("goteo_user", $user->id, time() + 3600 * 24 * 365);
  64. if (!empty($user->lang)) {
  65. $_SESSION['lang'] = $user->lang;
  66. }
  67. unset($_SESSION['admin_menu']);
  68. if (isset($user->roles['admin'])) {
  69. // (Nodesys)
  70. } else {
  71. unset($_SESSION['admin_node']);
  72. }
  73. if (!empty($_REQUEST['return'])) {
  74. throw new Redirection($_REQUEST['return']);
  75. } elseif (!empty($_SESSION['jumpto'])) {
  76. $jumpto = $_SESSION['jumpto'];
  77. unset($_SESSION['jumpto']);
  78. throw new Redirection($jumpto);
  79. } elseif (isset($user->roles['admin']) || isset($user->roles['superadmin'])) {
  80. throw new Redirection('/admin');
  81. } else {
  82. throw new Redirection('/dashboard');
  83. }
  84. } else {
  85. Message::Error(Text::get('login-fail'));
  86. }
  87. } elseif (empty($_SESSION['user']) && !empty($_COOKIE['goteo_user'])) {
  88. // si tenemos cookie de usuario
  89. return new View('view/user/login.html.php', array('username'=>$_COOKIE['goteo_user']));
  90. }
  91. return new View('view/user/login.html.php');
  92. }
  93. /**
  94. * Cerrar sesión.
  95. */
  96. public function logout() {
  97. $lang = '?lang=' . $_SESSION['lang'];
  98. session_start();
  99. session_unset();
  100. session_destroy();
  101. session_write_close();
  102. session_regenerate_id(true);
  103. throw new Redirection('/' . $lang);
  104. die;
  105. }
  106. /**
  107. * Registro de usuario.
  108. */
  109. public function register() {
  110. if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  111. foreach ($_POST as $key => $value) {
  112. $_POST[$key] = trim($value);
  113. }
  114. $errors = array();
  115. if (strcmp($_POST['email'], $_POST['remail']) !== 0) {
  116. $errors['remail'] = Text::get('error-register-email-confirm');
  117. }
  118. if (strcmp($_POST['password'], $_POST['rpassword']) !== 0) {
  119. $errors['rpassword'] = Text::get('error-register-password-confirm');
  120. }
  121. $user = new Model\User();
  122. $user->userid = $_POST['userid'];
  123. $user->name = $_POST['username'];
  124. $user->email = $_POST['email'];
  125. $user->password = $_POST['password'];
  126. $user->active = true;
  127. $user->node = \NODE_ID;
  128. $user->save($errors);
  129. if (empty($errors)) {
  130. Message::Info(Text::get('user-register-success'));
  131. $_SESSION['user'] = Model\User::get($user->id);
  132. // creamos una cookie
  133. setcookie("goteo_user", $user->id, time() + 3600 * 24 * 365);
  134. if (!empty($_SESSION['jumpto'])) {
  135. $jumpto = $_SESSION['jumpto'];
  136. unset($_SESSION['jumpto']);
  137. throw new Redirection($jumpto);
  138. } else {
  139. throw new Redirection('/dashboard');
  140. }
  141. } else {
  142. foreach ($errors as $field => $text) {
  143. Message::Error($text);
  144. }
  145. }
  146. }
  147. return new View(
  148. 'view/user/login.html.php',
  149. array(
  150. 'errors' => $errors
  151. )
  152. );
  153. }
  154. /**
  155. * Registro de usuario desde oauth
  156. */
  157. public function oauth_register() {
  158. //comprovar si venimos de un registro via oauth
  159. if ($_POST['provider']) {
  160. require_once OAUTH_LIBS;
  161. $provider = $_POST['provider'];
  162. $oauth = new \SocialAuth($provider);
  163. //importar els tokens obtinguts anteriorment via POST
  164. if ($_POST['tokens'][$oauth->provider]['token'])
  165. $oauth->tokens[$oauth->provider]['token'] = $_POST['tokens'][$oauth->provider]['token'];
  166. if ($_POST['tokens'][$oauth->provider]['secret'])
  167. $oauth->tokens[$oauth->provider]['secret'] = $_POST['tokens'][$oauth->provider]['secret'];
  168. //print_r($_POST['tokens']);print_R($oauth->tokens[$oauth->provider]);die;
  169. $user = new Model\User();
  170. $user->userid = $_POST['userid'];
  171. $user->email = $_POST['email'];
  172. $user->active = true;
  173. //resta de dades
  174. foreach ($oauth->user_data as $k => $v) {
  175. if ($_POST[$k]) {
  176. $oauth->user_data[$k] = $_POST[$k];
  177. if (in_array($k, $oauth->import_user_data))
  178. $user->$k = $_POST[$k];
  179. }
  180. }
  181. //si no existe nombre, nos lo inventamos a partir del userid
  182. if (trim($user->name) == '')
  183. $user->name = ucfirst($user->userid);
  184. //print_R($user);print_r($oauth);die;
  185. //no hará falta comprovar la contraseña ni el estado del usuario
  186. $skip_validations = array('password', 'active');
  187. //si el email proviene del proveedor de oauth, podemos confiar en el y lo activamos por defecto
  188. if ($_POST['provider_email'] == $user->email) {
  189. $user->confirmed = 1;
  190. }
  191. //comprovamos si ya existe el usuario
  192. //en caso de que si, se comprovará que el password sea correcto
  193. $query = Model\User::query('SELECT id,password,active FROM user WHERE email = ?', array($user->email));
  194. if ($u = $query->fetchObject()) {
  195. if ($u->password == sha1($_POST['password'])) {
  196. //ok, login en goteo e importar datos
  197. //y fuerza que pueda logear en caso de que no esté activo
  198. if (!$oauth->goteoLogin(true)) {
  199. //si no: registrar errores
  200. Message::Error(Text::get($oauth->last_error));
  201. }
  202. } else {
  203. Message::Error(Text::get('login-fail'));
  204. return new View(
  205. 'view/user/confirm_account.html.php',
  206. array(
  207. 'oauth' => $oauth,
  208. 'user' => Model\User::get($u->id)
  209. )
  210. );
  211. }
  212. } elseif ($user->save($errors, $skip_validations)) {
  213. //si el usuario se ha creado correctamente, login en goteo e importacion de datos
  214. //y fuerza que pueda logear en caso de que no esté activo
  215. if (!$oauth->goteoLogin(true)) {
  216. //si no: registrar errores
  217. Message::Error(Text::get($oauth->last_error));
  218. }
  219. } elseif ($errors) {
  220. foreach ($errors as $err => $val) {
  221. if ($err != 'email' && $err != 'userid')
  222. Message::Error($val);
  223. }
  224. }
  225. }
  226. return new View(
  227. 'view/user/confirm.html.php',
  228. array(
  229. 'errors' => $errors,
  230. 'oauth' => $oauth
  231. )
  232. );
  233. }
  234. /**
  235. * Registro de usuario a traves de Oauth (libreria HybridOauth, openid, facebook, twitter, etc).
  236. */
  237. public function oauth() {
  238. require_once OAUTH_LIBS;
  239. $errors = array();
  240. if (isset($_GET["provider"]) && $_GET["provider"]) {
  241. $oauth = new \SocialAuth($_GET["provider"]);
  242. if (!$oauth->authenticate()) {
  243. //si falla: error, si no siempre se redirige al proveedor
  244. Message::Error(Text::get($oauth->last_error));
  245. }
  246. }
  247. //return from provider authentication
  248. if (isset($_GET["return"]) && $_GET["return"]) {
  249. //check twitter activation
  250. $oauth = new \SocialAuth($_GET["return"]);
  251. if ($oauth->login()) {
  252. //si ok: redireccion de login!
  253. //Message::Info("USER INFO:\n".print_r($oauth->user_data,1));
  254. //si es posible, login en goteo (redirecciona a user/dashboard o a user/confirm)
  255. //y fuerza que pueda logear en caso de que no esté activo
  256. if (!$oauth->goteoLogin()) {
  257. //si falla: error o formulario de confirmación
  258. if ($oauth->last_error == 'oauth-goteo-user-not-exists') {
  259. return new View(
  260. 'view/user/confirm.html.php',
  261. array(
  262. 'oauth' => $oauth
  263. )
  264. );
  265. } elseif ($oauth->last_error == 'oauth-goteo-user-password-exists') {
  266. Message::Error(Text::get($oauth->last_error));
  267. return new View(
  268. 'view/user/confirm_account.html.php',
  269. array(
  270. 'oauth' => $oauth,
  271. 'user' => Model\User::get($oauth->user_data['username'])
  272. )
  273. );
  274. }
  275. else
  276. Message::Error(Text::get($oauth->last_error));
  277. }
  278. }
  279. else {
  280. //si falla: error
  281. Message::Error(Text::get($oauth->last_error));
  282. }
  283. }
  284. return new View(
  285. 'view/user/login.html.php',
  286. array(
  287. 'errors' => $errors
  288. )
  289. );
  290. }
  291. /**
  292. * Modificación perfil de usuario.
  293. * Metodo Obsoleto porque esto lo hacen en el dashboard
  294. */
  295. public function edit() {
  296. $user = $_SESSION['user'];
  297. if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  298. $errors = array();
  299. // E-mail
  300. if ($_POST['change_email']) {
  301. if (empty($_POST['user_nemail'])) {
  302. $errors['email'] = Text::get('error-user-email-empty');
  303. } elseif (!\Goteo\Library\Check::mail($_POST['user_nemail'])) {
  304. $errors['email'] = Text::get('error-user-email-invalid');
  305. } elseif (empty($_POST['user_remail'])) {
  306. $errors['email']['retry'] = Text::get('error-user-email-empty');
  307. } elseif (strcmp($_POST['user_nemail'], $_POST['user_remail']) !== 0) {
  308. $errors['email']['retry'] = Text::get('error-user-email-confirm');
  309. } else {
  310. $user->email = $_POST['user_nemail'];
  311. }
  312. }
  313. // Contraseña
  314. if ($_POST['change_password']) {
  315. /*
  316. * Quitamos esta verificacion porque los usuarios que acceden mediante servicio no tienen contraseña
  317. *
  318. if(empty($_POST['user_password'])) {
  319. $errors['password'] = Text::get('error-user-password-empty');
  320. }
  321. else
  322. */
  323. if (!Model\User::login($user->id, $_POST['user_password'])) {
  324. $errors['password'] = Text::get('error-user-wrong-password');
  325. } elseif (empty($_POST['user_npassword'])) {
  326. $errors['password']['new'] = Text::get('error-user-password-empty');
  327. } elseif (!\Goteo\Library\Check::password($_POST['user_npassword'])) {
  328. $errors['password']['new'] = Text::get('error-user-password-invalid');
  329. } elseif (empty($_POST['user_rpassword'])) {
  330. $errors['password']['retry'] = Text::get('error-user-password-empty');
  331. } elseif (strcmp($_POST['user_npassword'], $_POST['user_rpassword']) !== 0) {
  332. $errors['password']['retry'] = Text::get('error-user-password-confirm');
  333. } else {
  334. $user->password = $_POST['user_npassword'];
  335. }
  336. }
  337. // Avatar
  338. if (!empty($_FILES['user_avatar']['name'])) {
  339. $user->avatar = $_FILES['user_avatar'];
  340. }
  341. // tratar si quitan la imagen
  342. if (!empty($_POST['avatar-' . $user->avatar->id . '-remove'])) {
  343. $user->avatar->remove('user');
  344. $user->avatar = '';
  345. }
  346. // Perfil público
  347. $user->name = $_POST['user_name'];
  348. $user->about = $_POST['user_about'];
  349. $user->keywords = $_POST['user_keywords'];
  350. $user->contribution = $_POST['user_contribution'];
  351. $user->twitter = $_POST['user_twitter'];
  352. $user->facebook = $_POST['user_facebook'];
  353. $user->linkedin = $_POST['user_linkedin'];
  354. // Intereses
  355. $user->interests = $_POST['user_interests'];
  356. // Páginas Web
  357. if (!empty($_POST['user_webs']['remove'])) {
  358. $user->webs = array('remove' => $_POST['user_webs']['remove']);
  359. } elseif (!empty($_POST['user_webs']['add']) && !empty($_POST['user_webs']['add'][0])) {
  360. $user->webs = array('add' => $_POST['user_webs']['add']);
  361. } else {
  362. $user->webs = array('edit', $_POST['user_webs']['edit']);
  363. }
  364. if ($user->save($errors)) {
  365. // Refresca la sesión.
  366. $user = Model\User::flush();
  367. if (isset($_POST['save'])) {
  368. throw new Redirection('/dashboard');
  369. } else {
  370. throw new Redirection('/user/edit');
  371. }
  372. }
  373. }
  374. return new View(
  375. 'view/user/edit.html.php',
  376. array(
  377. 'user' => $user,
  378. 'errors' => $errors
  379. )
  380. );
  381. }
  382. /**
  383. * Perfil público de usuario.
  384. *
  385. * @param string $id Nombre de usuario
  386. */
  387. public function profile($id, $show = 'profile', $category = null) {
  388. if (!in_array($show, array('profile', 'investors', 'sharemates', 'message'))) {
  389. $show = 'profile';
  390. }
  391. $user = Model\User::get($id, LANG);
  392. if (!$user instanceof Model\User || $user->hide) {
  393. throw new Error('404', Text::html('fatal-error-user'));
  394. }
  395. //--- para usuarios públicos---
  396. if (empty($_SESSION['user'])) {
  397. // la subpágina de mensaje también está restringida
  398. if ($show == 'message') {
  399. $_SESSION['jumpto'] = '/user/profile/' . $id . '/message';
  400. Message::Info(Text::get('user-login-required-to_message'));
  401. throw new Redirection(SEC_URL."/user/login");
  402. }
  403. // a menos que este perfil sea de un vip, no pueden verlo
  404. if (!isset($user->roles['vip'])) {
  405. $_SESSION['jumpto'] = '/user/profile/' . $id . '/' . $show;
  406. Message::Info(Text::get('user-login-required-to_see'));
  407. throw new Redirection(SEC_URL."/user/login");
  408. }
  409. /*
  410. // subpágina de cofinanciadores
  411. if ($show == 'investors') {
  412. Message::Info(Text::get('user-login-required-to_see-supporters'));
  413. throw new Redirection('/user/profile/' . $id);
  414. }
  415. */
  416. }
  417. //--- el resto pueden seguir ---
  418. // impulsor y usuario solamente pueden comunicarse si:
  419. if ($show == 'message') {
  420. $is_author = false; // si es autor de un proyecto publicado
  421. $is_investor = false; // si es cofinanciador
  422. $is_messeger = false; // si es participante
  423. // si el usuario logueado es impulsor (autro de proyecto publicado
  424. $user_created = Model\Project::ofmine($_SESSION['user']->id, true);
  425. if (!empty($user_created)) {
  426. $is_author = true;
  427. }
  428. // si el usuario del perfil es cofin. o partic.
  429. // proyectos que es cofinanciador este usuario (el del perfil)
  430. $user_invested = Model\User::invested($id, true);
  431. foreach ($user_invested as $a_project) {
  432. if ($a_project->owner == $_SESSION['user']->id) {
  433. $is_investor = true;
  434. break;
  435. }
  436. }
  437. // proyectos que es participante este usuario (el del perfil) (que ha enviado algún mensaje)
  438. $user_messeged = Model\Message::getMesseged($id, true);
  439. foreach ($user_messeged as $a_project) {
  440. if ($a_project->owner == $_SESSION['user']->id) {
  441. $is_messeger = true;
  442. break;
  443. }
  444. }
  445. // si el usuario logueado es el usuario cofin./partic.
  446. // si el usuario del perfil es impulsor de un proyecto cofinanciado o en el que ha participado
  447. // proyectos que es cofinanciador el usuario logueado
  448. $user_invested = Model\User::invested($_SESSION['user']->id, true);
  449. foreach ($user_invested as $a_project) {
  450. if ($a_project->owner == $id) {
  451. $is_investor = true;
  452. break;
  453. }
  454. }
  455. // proyectos que es participante el usuario logueado (que ha enviado algún mensaje)
  456. $user_messeged = Model\Message::getMesseged($_SESSION['user']->id, true);
  457. foreach ($user_messeged as $a_project) {
  458. if ($a_project->owner == $id) {
  459. $is_messeger = true;
  460. break;
  461. }
  462. }
  463. if (!$is_investor && !$is_messeger && !$is_author) {
  464. Message::Info(Text::get('user-message-restricted'));
  465. throw new Redirection('/user/profile/' . $id);
  466. } else {
  467. $_SESSION['message_autorized'] = true;
  468. }
  469. }
  470. // vip profile
  471. $viewData = array();
  472. $viewData['user'] = $user;
  473. $projects = Model\Project::ofmine($id, true);
  474. $viewData['projects'] = $projects;
  475. //mis cofinanciadores
  476. // array de usuarios con:
  477. // foto, nombre, nivel, cantidad a mis proyectos, fecha ultimo aporte, nº proyectos que cofinancia
  478. $investors = array();
  479. foreach ($projects as $kay => $project) {
  480. // quitamos los caducados
  481. if ($project->status == 0) {
  482. unset($projects[$kay]);
  483. continue;
  484. }
  485. foreach (Model\Invest::investors($project->id) as $key => $investor) {
  486. // convocadores no, gracias
  487. if (!empty($investor->campaign))
  488. continue;
  489. if (\array_key_exists($investor->user, $investors)) {
  490. // ya está en el array, quiere decir que cofinancia este otro proyecto
  491. // , añadir uno, sumar su aporte, actualizar la fecha
  492. ++$investors[$investor->user]->projects;
  493. $investors[$investor->user]->amount += $investor->amount;
  494. $investors[$investor->user]->date = $investor->date;
  495. } else {
  496. $investors[$investor->user] = (object) array(
  497. 'user' => $investor->user,
  498. 'name' => $investor->name,
  499. 'projects' => 1,
  500. 'avatar' => $investor->avatar,
  501. 'worth' => $investor->worth,
  502. 'amount' => $investor->amount,
  503. 'date' => $investor->date
  504. );
  505. }
  506. }
  507. }
  508. $viewData['investors'] = $investors;
  509. // comparten intereses
  510. $viewData['shares'] = Model\User\Interest::share($id, $category);
  511. if ($show == 'sharemates' && empty($viewData['shares'])) {
  512. $show = 'profile';
  513. }
  514. if (!empty($category)) {
  515. $viewData['category'] = $category;
  516. }
  517. // proyectos que cofinancio
  518. $invested = Model\User::invested($id, true);
  519. // agrupacion de proyectos que cofinancia y proyectos suyos
  520. $viewData['lists'] = array();
  521. if (!empty($invested)) {
  522. $viewData['lists']['invest_on'] = Listing::get($invested, 2);
  523. }
  524. if (!empty($projects)) {
  525. $viewData['lists']['my_projects'] = Listing::get($projects, 2);
  526. }
  527. return new View ('view/user/'.$show.'.html.php', $viewData);
  528. }
  529. /**
  530. * Activación usuario.
  531. *
  532. * @param type string $token
  533. */
  534. public function activate($token) {
  535. $query = Model\User::query('SELECT id FROM user WHERE token = ?', array($token));
  536. if ($id = $query->fetchColumn()) {
  537. $user = Model\User::get($id);
  538. if (!$user->confirmed) {
  539. $user->confirmed = true;
  540. $user->active = true;
  541. if ($user->save($errors)) {
  542. Message::Info(Text::get('user-activate-success'));
  543. $_SESSION['user'] = $user;
  544. // Evento Feed
  545. $log = new Feed();
  546. $log->setTarget($user->id, 'user');
  547. $log->populate('nuevo usuario registrado (confirmado)', '/admin/users', Text::html('feed-new_user', Feed::item('user', $user->name, $user->id)));
  548. $log->doAdmin('user');
  549. // evento público
  550. $log->title = $user->name;
  551. $log->url = null;
  552. $log->doPublic('community');
  553. unset($log);
  554. } else {
  555. Message::Error($errors);
  556. }
  557. } else {
  558. Message::Info(Text::get('user-activate-already-active'));
  559. }
  560. } else {
  561. Message::Error(Text::get('user-activate-fail'));
  562. }
  563. throw new Redirection('/dashboard');
  564. }
  565. /**
  566. * Cambiar dirección de correo.
  567. *
  568. * @param type string $token
  569. */
  570. public function changeemail($token) {
  571. $token = base64_decode($token);
  572. if (count(explode('¬', $token)) > 1) {
  573. $query = Model\User::query('SELECT id FROM user WHERE token = ?', array($token));
  574. if ($id = $query->fetchColumn()) {
  575. $user = Model\User::get($id);
  576. $user->email = $token;
  577. $errors = array();
  578. if ($user->save($errors)) {
  579. Message::Info(Text::get('user-changeemail-success'));
  580. // Refresca la sesión.
  581. Model\User::flush();
  582. } else {
  583. Message::Error($errors);
  584. }
  585. } else {
  586. Message::Error(Text::get('user-changeemail-fail'));
  587. }
  588. } else {
  589. Message::Error(Text::get('user-changeemail-fail'));
  590. }
  591. throw new Redirection('/dashboard');
  592. }
  593. /**
  594. * Recuperacion de contraseña
  595. * - Si no llega nada, mostrar formulario para que pongan su username y el email correspondiente
  596. * - Si llega post es una peticion, comprobar que el username y el email que han puesto son válidos
  597. * si no lo son, dejarlos en el formulario y mensaje de error
  598. * si son válidos, enviar email con la url y mensaje de ok
  599. *
  600. * - Si llega un hash, verificar y darle acceso hasta su dashboard /profile/access para que la cambien
  601. *
  602. * @param string $token Codigo
  603. */
  604. public function recover($token = null) {
  605. // si el token mola, logueo este usuario y lo llevo a su dashboard
  606. if (!empty($token)) {
  607. $token = base64_decode($token);
  608. $parts = explode('¬', $token);
  609. if (count($parts) > 1) {
  610. $query = Model\User::query('SELECT id FROM user WHERE email = ? AND token = ?', array($parts[1], $token));
  611. if ($id = $query->fetchColumn()) {
  612. if (!empty($id)) {
  613. // el token coincide con el email y he obtenido una id
  614. Model\User::query('UPDATE user SET active = 1 WHERE id = ?', array($id));
  615. $user = Model\User::get($id);
  616. $_SESSION['user'] = $user;
  617. $_SESSION['recovering'] = $user->id;
  618. throw new Redirection(SEC_URL.'/dashboard/profile/access/recover#password');
  619. }
  620. }
  621. }
  622. $error = Text::get('recover-token-incorrect');
  623. }
  624. // password recovery only by email
  625. if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['recover'])) {
  626. $email = $_POST['email'];
  627. if (!empty($email) && Model\User::recover($email)) {
  628. $message = Text::get('recover-email-sended');
  629. unset($_POST['email']);
  630. } else {
  631. $error = Text::get('recover-request-fail');
  632. }
  633. }
  634. return new View(
  635. 'view/user/recover.html.php',
  636. array(
  637. 'error' => $error,
  638. 'message' => $message
  639. )
  640. );
  641. }
  642. /**
  643. * Darse de baja
  644. * - Si no llega nada, mostrar formulario para que pongan el email de su cuenta
  645. * - Si llega post es una peticion, comprobar que el email que han puesto es válido
  646. * si no es, dejarlos en el formulario y mensaje de error
  647. * si es válido, enviar email con la url y mensaje de ok
  648. *
  649. * - Si llega un hash, verificar y dar de baja la cuenta (desactivar y ocultar)
  650. *
  651. * @param string $token Codigo
  652. */
  653. public function leave($token = null) {
  654. // si el token mola, lo doy de baja
  655. if (!empty($token)) {
  656. $token = base64_decode($token);
  657. $parts = explode('¬', $token);
  658. if (count($parts) > 1) {
  659. $query = Model\User::query('SELECT id FROM user WHERE email = ? AND token = ?', array($parts[1], $token));
  660. if ($id = $query->fetchColumn()) {
  661. if (!empty($id)) {
  662. // el token coincide con el email y he obtenido una id
  663. if (Model\User::cancel($id)) {
  664. Message::Info(Text::get('leave-process-completed'));
  665. throw new Redirection(SEC_URL.'/user/login');
  666. } else {
  667. Message::Error(Text::get('leave-process-fail'));
  668. throw new Redirection(SEC_URL.'/user/login');
  669. }
  670. }
  671. }
  672. }
  673. $error = Text::get('leave-token-incorrect');
  674. }
  675. if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['leaving'])) {
  676. if (Model\User::leaving($_POST['email'], $_POST['reason'])) {
  677. $message = Text::get('leave-email-sended');
  678. unset($_POST['email']);
  679. unset($_POST['reason']);
  680. } else {
  681. $error = Text::get('leave-request-fail');
  682. }
  683. }
  684. return new View(
  685. 'view/user/leave.html.php',
  686. array(
  687. 'error' => $error,
  688. 'message' => $message
  689. )
  690. );
  691. }
  692. }
  693. }