예제 #1
0
파일: tags.php 프로젝트: kenjs/Goteo
 public static function process($action = 'list', $id = null)
 {
     $model = 'Goteo\\Model\\Blog\\Post\\Tag';
     $url = '/admin/tags';
     $errors = array();
     switch ($action) {
         case 'add':
             return new View('view/admin/index.html.php', array('folder' => 'base', 'file' => 'edit', 'data' => (object) array(), 'form' => array('action' => "{$url}/edit/", 'submit' => array('name' => 'update', 'label' => Text::_('Añadir')), 'fields' => array('id' => array('label' => '', 'name' => 'id', 'type' => 'hidden'), 'name' => array('label' => Text::_('Tag'), 'name' => 'name', 'type' => 'text')))));
             break;
         case 'edit':
             // gestionar post
             if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update'])) {
                 $errors = array();
                 // instancia
                 $item = new $model(array('id' => $_POST['id'], 'name' => $_POST['name']));
                 if ($item->save($errors)) {
                     Message::Info(Text::get('admin-tags-info-udate'));
                     throw new Redirection($url);
                 } else {
                     Message::Error(Text::get('admin-tags-error-save-fail') . implode('<br />', $errors));
                 }
             } else {
                 $item = $model::get($id);
             }
             return new View('view/admin/index.html.php', array('folder' => 'base', 'file' => 'edit', 'data' => $item, 'form' => array('action' => "{$url}/edit/{$id}", 'submit' => array('name' => 'update', 'label' => Text::get('regular-save')), 'fields' => array('id' => array('label' => '', 'name' => 'id', 'type' => 'hidden'), 'name' => array('label' => Text::_('Tag'), 'name' => 'name', 'type' => 'text')))));
             break;
         case 'remove':
             if ($model::delete($id)) {
                 throw new Redirection($url);
             }
             break;
     }
     return new View('view/admin/index.html.php', array('folder' => 'base', 'file' => 'list', 'model' => 'tag', 'addbutton' => Text::_('Nuevo tag'), 'data' => $model::getList(1), 'columns' => array('edit' => '', 'name' => Text::_('Tag'), 'used' => Text::_('Entradas'), 'translate' => '', 'remove' => ''), 'url' => "{$url}"));
 }
예제 #2
0
파일: icons.php 프로젝트: anvnguyen/Goteo
 public static function process($action = 'list', $id = null, $filters = array())
 {
     $groups = Model\Icon::groups();
     $errors = array();
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         // instancia
         $icon = new Model\Icon(array('id' => $_POST['id'], 'name' => $_POST['name'], 'description' => $_POST['description'], 'order' => $_POST['order'], 'group' => empty($_POST['group']) ? null : $_POST['group']));
         if ($icon->save($errors)) {
             switch ($_POST['action']) {
                 case 'add':
                     Message::Info('Nuevo tipo añadido correctamente');
                     break;
                 case 'edit':
                     Message::Info('Tipo editado correctamente');
                     // Evento Feed
                     $log = new Feed();
                     $log->populate('modificacion de tipo de retorno/recompensa (admin)', '/admin/icons', \vsprintf("El admin %s ha %s el tipo de retorno/recompensa %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Modificado'), Feed::item('project', $icon->name))));
                     $log->doAdmin('admin');
                     unset($log);
                     break;
             }
         } else {
             Message::Error(implode('<br />', $errors));
             return new View('view/admin/index.html.php', array('folder' => 'icons', 'file' => 'edit', 'action' => $_POST['action'], 'icon' => $icon, 'groups' => $groups));
         }
     }
     switch ($action) {
         case 'edit':
             $icon = Model\Icon::get($id);
             return new View('view/admin/index.html.php', array('folder' => 'icons', 'file' => 'edit', 'action' => 'edit', 'icon' => $icon, 'groups' => $groups));
             break;
     }
     $icons = Model\Icon::getAll($filters['group']);
     return new View('view/admin/index.html.php', array('folder' => 'icons', 'file' => 'list', 'icons' => $icons, 'groups' => $groups, 'filters' => $filters));
 }
예제 #3
0
파일: templates.php 프로젝트: kenjs/Goteo
 public static function process($action = 'list', $id = null, $filters = array())
 {
     $errors = array();
     // valores de filtro
     $groups = Template::groups();
     switch ($action) {
         case 'edit':
             // si estamos editando una plantilla
             $template = Template::get($id);
             // si llega post, vamos a guardar los cambios
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 $template->title = $_POST['title'];
                 $template->text = $_POST['text'];
                 if ($template->save($errors)) {
                     //Message::Info(Text::_('La plantilla se ha actualizado correctamente'));
                     throw new Redirection("/admin/templates");
                 } else {
                     Message::Error(Text::get('admin-templates-error-record-fail') . implode('<br />', $errors));
                 }
             }
             // sino, mostramos para editar
             return new View('view/admin/index.html.php', array('folder' => 'templates', 'file' => 'edit', 'template' => $template));
             break;
         case 'list':
             // si estamos en la lista de páginas
             $templates = Template::getAll($filters);
             return new View('view/admin/index.html.php', array('folder' => 'templates', 'file' => 'list', 'templates' => $templates, 'groups' => $groups, 'filters' => $filters));
             break;
     }
 }
예제 #4
0
 /**
  * Suplantando al usuario
  * @param string $id   user->id
  */
 public function index()
 {
     $admin = $_SESSION['user'];
     if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['id']) && !empty($_POST['impersonate'])) {
         $impersonator = $_SESSION['user']->id;
         session_unset();
         $_SESSION['user'] = User::get($_POST['id']);
         $_SESSION['impersonating'] = true;
         $_SESSION['impersonator'] = $impersonator;
         unset($_SESSION['admin_menu']);
         /*
          * Evento Feed
          */
         // Evento Feed
         $log = new Feed();
         $log->setTarget($_SESSION['user']->id, 'user');
         $log->populate('Suplantación usuario (admin)', '/admin/users', \vsprintf('El admin %s ha %s al usuario %s', array(Feed::item('user', $admin->name, $admin->id), Feed::item('relevant', 'Suplantado'), Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id))));
         $log->doAdmin('user');
         unset($log);
         throw new Redirection('/dashboard');
     } else {
         Message::Error('Ha ocurrido un error');
         throw new Redirection('/dashboard');
     }
 }
예제 #5
0
파일: worth.php 프로젝트: anvnguyen/Goteo
 public static function process($action = 'list', $id = null)
 {
     $errors = array();
     if ($_SERVER['REQUEST_METHOD'] == 'POST' && $action == 'edit') {
         // instancia
         $data = array('id' => $_POST['id'], 'name' => $_POST['name'], 'amount' => $_POST['amount']);
         if (WorthLib::save($data, $errors)) {
             $action = 'list';
             Message::Info(Text::_('Nivel de meritocracia modificado'));
             // Evento Feed
             $log = new Feed();
             $log->populate(Text::_('Nivel de meritocracia modificado'), '/admin/worth', \vsprintf("El admin %s ha %s el nivel de meritocrácia %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Modificado'), Feed::item('project', $icon->name))));
             $log->doAdmin('admin');
             unset($log);
         } else {
             Message::Error(Text::_('No se ha guardado correctamente. ') . implode('<br />', $errors));
             return new View('view/admin/index.html.php', array('folder' => 'worth', 'file' => 'edit', 'action' => 'edit', 'worth' => (object) $data));
         }
     }
     switch ($action) {
         case 'edit':
             $worth = WorthLib::getAdmin($id);
             return new View('view/admin/index.html.php', array('folder' => 'worth', 'file' => 'edit', 'action' => 'edit', 'worth' => $worth));
             break;
     }
     $worthcracy = WorthLib::getAll();
     return new View('view/admin/index.html.php', array('folder' => 'worth', 'file' => 'list', 'worthcracy' => $worthcracy));
 }
예제 #6
0
파일: home.php 프로젝트: isbkch/Goteo
 public static function process($action = 'list', $id = null, $filters = array(), $type = 'main')
 {
     //@NODESYS
     $node = \GOTEO_NODE;
     $type = 'main';
     $errors = array();
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         // instancia
         $item = new Model\Home(array('item' => $_POST['item'], 'type' => $_POST['type'], 'node' => $node, 'order' => $_POST['order'], 'move' => 'down'));
         if ($item->save($errors)) {
         } else {
             Message::Error(implode('<br />', $errors));
         }
     }
     switch ($action) {
         case 'remove':
             Model\Home::delete($id, $node, $type);
             throw new Redirection('/admin/home');
             break;
         case 'up':
             Model\Home::up($id, $node, $type);
             throw new Redirection('/admin/home');
             break;
         case 'down':
             Model\Home::down($id, $node, $type);
             throw new Redirection('/admin/home');
             break;
         case 'add':
             $next = Model\Home::next($node, 'main');
             $availables = Model\Home::available($node);
             if (empty($availables)) {
                 Message::Info(Text::_('Todos los elementos disponibles ya estan en portada'));
                 throw new Redirection('/admin/home');
                 break;
             }
             return new View('view/admin/index.html.php', array('folder' => 'home', 'file' => 'add', 'action' => 'add', 'home' => (object) array('node' => $node, 'order' => $next, 'type' => 'main'), 'availables' => $availables));
             break;
         case 'addside':
             $next = Model\Home::next($node, 'side');
             $availables = Model\Home::availableSide($node);
             if (empty($availables)) {
                 Message::Info(Text::_('Todos los elementos laterales disponibles ya estan en portada'));
                 throw new Redirection('/admin/home');
                 break;
             }
             return new View('view/admin/index.html.php', array('folder' => 'home', 'file' => 'add', 'action' => 'add', 'home' => (object) array('node' => $node, 'order' => $next, 'type' => 'side'), 'availables' => $availables));
             break;
     }
     $viewData = array('folder' => 'home', 'file' => 'list');
     $viewData['items'] = Model\Home::getAll($node);
     /* Para añadir nuevos desde la lista */
     $viewData['availables'] = Model\Home::available($node);
     $viewData['new'] = (object) array('node' => $node, 'order' => Model\Home::next($node, 'main'), 'type' => 'main');
     // laterales
     $viewData['side_items'] = Model\Home::getAllSide($node);
     $viewData['side_availables'] = Model\Home::availableSide($node);
     $viewData['side_new'] = (object) array('node' => $node, 'order' => Model\Home::next($node, 'side'), 'type' => 'side');
     return new View('view/admin/index.html.php', $viewData);
 }
예제 #7
0
 public static function process($action = 'list', $id = null)
 {
     $node = isset($_SESSION['admin_node']) ? $_SESSION['admin_node'] : \GOTEO_NODE;
     $model = 'Goteo\\Model\\Sponsor';
     $url = '/admin/sponsors';
     $errors = array();
     switch ($action) {
         case 'add':
             return new View('view/admin/index.html.php', array('folder' => 'base', 'file' => 'edit', 'data' => (object) array('order' => $model::next($node), 'node' => $node), 'form' => array('action' => "{$url}/edit/", 'submit' => array('name' => 'update', 'label' => Text::_('Añadir')), 'fields' => array('id' => array('label' => '', 'name' => 'id', 'type' => 'hidden'), 'node' => array('label' => '', 'name' => 'node', 'type' => 'hidden'), 'name' => array('label' => Text::_('Patrocinador'), 'name' => 'name', 'type' => 'text'), 'url' => array('label' => Text::_('Enlace'), 'name' => 'url', 'type' => 'text', 'properties' => 'size=100'), 'image' => array('label' => Text::_('Logo'), 'name' => 'image', 'type' => 'image'), 'order' => array('label' => Text::_('Posición'), 'name' => 'order', 'type' => 'text')))));
             break;
         case 'edit':
             // gestionar post
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 // instancia
                 $item = new $model(array('id' => $_POST['id'], 'name' => $_POST['name'], 'node' => $_POST['node'], 'image' => $_POST['image'], 'url' => $_POST['url'], 'order' => $_POST['order']));
                 // tratar si quitan la imagen
                 $current = $_POST['image'];
                 // la actual
                 if (isset($_POST['image-' . $current . '-remove'])) {
                     $image = Model\Image::get($current);
                     $image->remove('sponsor');
                     $item->image = '';
                     $removed = true;
                 }
                 // tratar la imagen y ponerla en la propiedad image
                 if (!empty($_FILES['image']['name'])) {
                     $item->image = $_FILES['image'];
                 }
                 if ($item->save($errors)) {
                     Message::Info(Text::_('Datos grabados correctamente'));
                     throw new Redirection($url);
                 } else {
                     Message::Error(Text::_('No se ha grabado correctamente. ') . implode(', ', $errors));
                 }
             } else {
                 $item = $model::get($id);
             }
             return new View('view/admin/index.html.php', array('folder' => 'base', 'file' => 'edit', 'data' => $item, 'form' => array('action' => "{$url}/edit/{$id}", 'submit' => array('name' => 'update', 'label' => Text::get('regular-save')), 'fields' => array('id' => array('label' => '', 'name' => 'id', 'type' => 'hidden'), 'node' => array('label' => '', 'name' => 'node', 'type' => 'hidden'), 'name' => array('label' => Text::_('Patrocinador'), 'name' => 'name', 'type' => 'text'), 'url' => array('label' => Text::_('Enlace'), 'name' => 'url', 'type' => 'text', 'properties' => 'size=100'), 'image' => array('label' => Text::_('Logo'), 'name' => 'image', 'type' => 'image'), 'order' => array('label' => Text::_('Posición'), 'name' => 'order', 'type' => 'text')))));
             break;
         case 'up':
             $model::up($id, $node);
             throw new Redirection($url);
             break;
         case 'down':
             $model::down($id, $node);
             throw new Redirection($url);
             break;
         case 'remove':
             if ($model::delete($id)) {
                 Message::Info(Text::_('Se ha eliminado el registro'));
                 throw new Redirection($url);
             } else {
                 Message::Info(Text::_('No se ha podido eliminar el registro'));
             }
             break;
     }
     return new View('view/admin/index.html.php', array('folder' => 'base', 'file' => 'list', 'addbutton' => Text::_('Nuevo patrocinador'), 'data' => $model::getAll($node), 'columns' => array('edit' => '', 'name' => Text::_('Patrocinador'), 'url' => Text::_('Enlace'), 'image' => Text::_('Imagen'), 'order' => Text::_('Posición'), 'up' => '', 'down' => '', 'remove' => ''), 'url' => "{$url}"));
 }
예제 #8
0
파일: pages.php 프로젝트: isbkch/Goteo
 public static function process($action = 'list', $id = null)
 {
     $node = isset($_SESSION['admin_node']) ? $_SESSION['admin_node'] : \GOTEO_NODE;
     $errors = array();
     switch ($action) {
         case 'add':
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 $page = new Page();
                 $page->id = $_POST['id'];
                 $page->name = $_POST['name'];
                 if ($page->add($errors)) {
                     Message::Info('La página <strong>' . $page->name . '</strong> se ha creado correctamente, se puede editar ahora.');
                     throw new Redirection("/admin/pages/edit/{$page->id}");
                 } else {
                     Message::Error('No se ha creado bien ' . implode('<br />', $errors));
                     throw new Redirection("/admin/pages/add");
                 }
             }
             return new View('view/admin/index.html.php', array('folder' => 'pages', 'file' => 'add'));
             break;
         case 'edit':
             if ($node != \GOTEO_NODE && !in_array($id, static::_node_pages())) {
                 Message::Info('No puedes gestionar la página <strong>' . $id . '</strong>');
                 throw new Redirection("/admin/pages");
             }
             // si estamos editando una página
             $page = Page::get($id, $node, \GOTEO_DEFAULT_LANG);
             // si llega post, vamos a guardar los cambios
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 $page->name = $_POST['name'];
                 $page->description = $_POST['description'];
                 $page->content = $_POST['content'];
                 if ($page->save($errors)) {
                     // Evento Feed
                     $log = new Feed();
                     if ($node != \GOTEO_NODE && in_array($id, static::_node_pages())) {
                         $log->setTarget($node, 'node');
                     }
                     $log->populate(Text::_('modificacion de página institucional (admin)'), '/admin/pages', \vsprintf("El admin %s ha %s la página institucional %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Modificado'), Feed::item('relevant', $page->name, $page->url))));
                     $log->doAdmin('admin');
                     unset($log);
                     Message::Info('La página ' . $page->name . ' se ha actualizado correctamente');
                     throw new Redirection("/admin/pages");
                 } else {
                     Message::Error(implode('<br />', $errors));
                 }
             }
             // sino, mostramos para editar
             return new View('view/admin/index.html.php', array('folder' => 'pages', 'file' => 'edit', 'page' => $page));
             break;
         case 'list':
             // si estamos en la lista de páginas
             $pages = Page::getList($node);
             return new View('view/admin/index.html.php', array('folder' => 'pages', 'file' => 'list', 'pages' => $pages, 'node' => $node));
             break;
     }
 }
예제 #9
0
파일: licenses.php 프로젝트: kenjs/Goteo
 public static function process($action = 'list', $id = null, $filters = array())
 {
     // agrupaciones de mas a menos abertas
     $groups = Model\License::groups();
     // tipos de retorno para asociar
     $icons = Model\Icon::getAll('social');
     $errors = array();
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         // objeto
         $license = new Model\License(array('id' => $_POST['id'], 'name' => $_POST['name'], 'description' => $_POST['description'], 'url' => $_POST['url'], 'group' => $_POST['group'], 'order' => $_POST['order'], 'icons' => $_POST['icons']));
         if ($license->save($errors)) {
             switch ($_POST['action']) {
                 case 'add':
                     Message::Info(Text::get('admin-licenses-info-add'));
                     break;
                 case 'edit':
                     Message::Info(Text::get('admin-licenses-info-edit'));
                     // Evento Feed
                     $log = new Feed();
                     $log->populate('modificacion de licencia (admin)', '/admin/licenses', \vsprintf("El admin %s ha %s la licencia %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Modificado'), Feed::item('project', $license->name))));
                     $log->doAdmin('admin');
                     unset($log);
                     break;
             }
         } else {
             Message::Error(implode('<br />', $errors));
             return new View('view/admin/index.html.php', array('folder' => 'licenses', 'file' => 'edit', 'action' => $_POST['action'], 'license' => $license, 'icons' => $icons, 'groups' => $groups));
         }
     }
     switch ($action) {
         case 'up':
             Model\License::up($id);
             break;
         case 'down':
             Model\License::down($id);
             break;
         case 'add':
             $next = Model\License::next();
             return new View('view/admin/index.html.php', array('folder' => 'licenses', 'file' => 'edit', 'action' => 'add', 'license' => (object) array('order' => $next, 'icons' => array()), 'icons' => $icons, 'groups' => $groups));
             break;
         case 'edit':
             $license = Model\License::get($id);
             return new View('view/admin/index.html.php', array('folder' => 'licenses', 'file' => 'edit', 'action' => 'edit', 'license' => $license, 'icons' => $icons, 'groups' => $groups));
             break;
         case 'remove':
             //                Model\License::delete($id);
             break;
     }
     $licenses = Model\License::getAll($filters['icon'], $filters['group']);
     return new View('view/admin/index.html.php', array('folder' => 'licenses', 'file' => 'list', 'licenses' => $licenses, 'filters' => $filters, 'groups' => $groups, 'icons' => $icons));
 }
예제 #10
0
파일: faq.php 프로젝트: anvnguyen/Goteo
 public static function process($action = 'list', $id = null, $filters = array())
 {
     $sections = Model\Faq::sections();
     if (!isset($sections[$filters['section']])) {
         unset($filters['section']);
     }
     $errors = array();
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         // instancia
         $faq = new Model\Faq(array('id' => $_POST['id'], 'node' => \GOTEO_NODE, 'section' => $_POST['section'], 'title' => $_POST['title'], 'description' => $_POST['description'], 'order' => $_POST['order'], 'move' => $_POST['move']));
         if ($faq->save($errors)) {
             switch ($_POST['action']) {
                 case 'add':
                     Message::Info('Pregunta añadida correctamente');
                     break;
                 case 'edit':
                     Message::Info('Pregunta editado correctamente');
                     break;
             }
         } else {
             Message::Error(implode('<br />', $errors));
             return new View('view/admin/index.html.php', array('folder' => 'faq', 'file' => 'edit', 'action' => $_POST['action'], 'faq' => $faq, 'filter' => $filter, 'sections' => $sections));
         }
     }
     switch ($action) {
         case 'up':
             Model\Faq::up($id);
             throw new Redirection('/admin/faq');
             break;
         case 'down':
             Model\Faq::down($id);
             throw new Redirection('/admin/faq');
             break;
         case 'add':
             $next = Model\Faq::next($filters['section']);
             return new View('view/admin/index.html.php', array('folder' => 'faq', 'file' => 'edit', 'action' => 'add', 'faq' => (object) array('section' => $filters['section'], 'order' => $next, 'cuantos' => $next), 'sections' => $sections));
             break;
         case 'edit':
             $faq = Model\Faq::get($id);
             $cuantos = Model\Faq::next($faq->section);
             $faq->cuantos = $cuantos - 1;
             return new View('view/admin/index.html.php', array('folder' => 'faq', 'file' => 'edit', 'action' => 'edit', 'faq' => $faq, 'sections' => $sections));
             break;
         case 'remove':
             Model\Faq::delete($id);
             break;
     }
     $faqs = Model\Faq::getAll($filters['section']);
     return new View('view/admin/index.html.php', array('folder' => 'faq', 'file' => 'list', 'faqs' => $faqs, 'sections' => $sections, 'filters' => $filters));
 }
예제 #11
0
파일: criteria.php 프로젝트: kenjs/Goteo
 public static function process($action = 'list', $id = null, $filters = array())
 {
     $sections = Model\Criteria::sections();
     if (!isset($sections[$filters['section']])) {
         unset($filters['section']);
     }
     $errors = array();
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         // instancia
         $criteria = new Model\Criteria(array('id' => $_POST['id'], 'section' => $_POST['section'], 'title' => $_POST['title'], 'description' => $_POST['description'], 'order' => $_POST['order'], 'move' => $_POST['move']));
         if ($criteria->save($errors)) {
             switch ($_POST['action']) {
                 case 'add':
                     Message::Info(Text::get('criteria-info-add-correctly'));
                     break;
                 case 'edit':
                     Message::Info(Text::get('criteria-info-edit-correctly'));
                     break;
             }
         } else {
             Message::Error(implode('<br />', $errors));
             return new View('view/admin/index.html.php', array('folder' => 'criteria', 'file' => 'edit', 'action' => $_POST['action'], 'criteria' => $criteria, 'sections' => $sections));
         }
     }
     switch ($action) {
         case 'up':
             Model\Criteria::up($id);
             break;
         case 'down':
             Model\Criteria::down($id);
             break;
         case 'add':
             $next = Model\Criteria::next($filters['section']);
             return new View('view/admin/index.html.php', array('folder' => 'criteria', 'file' => 'edit', 'action' => 'add', 'criteria' => (object) array('section' => $filters['section'], 'order' => $next, 'cuantos' => $next), 'sections' => $sections));
             break;
         case 'edit':
             $criteria = Model\Criteria::get($id);
             $cuantos = Model\Criteria::next($criteria->section);
             $criteria->cuantos = $cuantos - 1;
             return new View('view/admin/index.html.php', array('folder' => 'criteria', 'file' => 'edit', 'action' => 'edit', 'criteria' => $criteria, 'sections' => $sections));
             break;
         case 'remove':
             Model\Criteria::delete($id);
             break;
     }
     $criterias = Model\Criteria::getAll($filters['section']);
     return new View('view/admin/index.html.php', array('folder' => 'criteria', 'file' => 'list', 'criterias' => $criterias, 'sections' => $sections, 'filters' => $filters));
 }
예제 #12
0
파일: texts.php 프로젝트: isbkch/Goteo
 public static function process($action = 'list', $id = null, $filters = array())
 {
     // valores de filtro
     $groups = Text::groups();
     // metemos el todos
     \array_unshift($groups, Text::_('Todas las agrupaciones'));
     //@fixme temporal hasta pasar las agrupaciones a tabal o arreglar en el list.html.php
     // I dont know if this must serve in default lang or in current navigation lang
     $data = Text::getAll($filters, 'original');
     foreach ($data as $key => $item) {
         $data[$key]->group = $groups[$item->group];
     }
     switch ($action) {
         case 'list':
             return new View('view/admin/index.html.php', array('folder' => 'texts', 'file' => 'list', 'data' => $data, 'columns' => array('edit' => '', 'text' => Text::_('Texto'), 'group' => Text::_('Agrupación')), 'url' => '/admin/texts', 'filters' => array('filtered' => $filters['filtered'], 'group' => array('label' => Text::_('Filtrar por agrupación:'), 'type' => 'select', 'options' => $groups, 'value' => $filters['group']), 'text' => array('label' => Text::_('Buscar texto:'), 'type' => 'input', 'options' => null, 'value' => $filters['text']))));
             break;
         case 'edit':
             // gestionar post
             if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update'])) {
                 $errors = array();
                 $id = $_POST['id'];
                 $text = $_POST['text'];
                 $data = array('id' => $id, 'text' => $_POST['text']);
                 if (Text::update($data, $errors)) {
                     Message::Info(Text::_('El texto ha sido actualizado'));
                     throw new Redirection("/admin/texts");
                 } else {
                     Message::Error(implode('<br />', $errors));
                 }
             } else {
                 //@TODO: this must get the text in the GOTEO_DEFAULT_LANG or it will be overwrited
                 $text = Text::getPurpose($id);
                 // Julian Canaves  23 nov 2013
                 // right now getPurpose gets the spanish text.
                 // In future this spanish text will be moved to the `Text` table
                 //  and the `Purpose` table will distribute to database text or to gettext
                 //  and there will be no hardcoded strings
                 //  and will be all happy, fun and joy
             }
             return new View('view/admin/index.html.php', array('folder' => 'texts', 'file' => 'edit', 'data' => (object) array('id' => $id, 'text' => $text), 'form' => array('action' => '/admin/texts/edit/' . $id, 'submit' => array('name' => 'update', 'label' => Text::_('Aplicar')), 'fields' => array('idtext' => array('label' => '', 'name' => 'id', 'type' => 'hidden', 'properties' => ''), 'newtext' => array('label' => Text::_('Texto'), 'name' => 'text', 'type' => 'textarea', 'properties' => 'cols="100" rows="6"')))));
             break;
         default:
             throw new Redirection("/admin");
     }
 }
예제 #13
0
파일: blog.php 프로젝트: anvnguyen/Goteo
 public function index($post = null)
 {
     if (!empty($post)) {
         $show = 'post';
         // -- Mensaje azul molesto para usuarios no registrados
         if (empty($_SESSION['user'])) {
             $_SESSION['jumpto'] = '/blog/' . $post;
             Message::Info(Text::html('user-login-required'));
         }
     } else {
         $show = 'list';
     }
     // sacamos su blog
     $blog = Model\Blog::get(\GOTEO_NODE, 'node');
     $filters = array();
     if (isset($_GET['tag'])) {
         $tag = Model\Blog\Post\Tag::get($_GET['tag']);
         if (!empty($tag->id)) {
             $filters['tag'] = $tag->id;
         }
     } else {
         $tag = null;
     }
     if (isset($_GET['author'])) {
         $author = Model\User::getMini($_GET['author']);
         if (!empty($author->id)) {
             $filters['author'] = $author->id;
         }
     } else {
         $author = null;
     }
     if (!empty($filters)) {
         $blog->posts = Model\Blog\Post::getList($filters);
     }
     if (isset($post) && !isset($blog->posts[$post]) && $_GET['preview'] != $_SESSION['user']->id) {
         throw new \Goteo\Core\Redirection('/blog');
     }
     // segun eso montamos la vista
     return new View('view/blog/index.html.php', array('blog' => $blog, 'show' => $show, 'filters' => $filters, 'post' => $post, 'owner' => \GOTEO_NODE));
 }
예제 #14
0
파일: rewards.php 프로젝트: kenjs/Goteo
 public static function process($action = 'list', $id = null, $filters = array())
 {
     switch ($action) {
         case 'fulfill':
             $sql = "UPDATE invest_reward SET fulfilled = 1 WHERE invest = ?";
             if (Model\Invest::query($sql, array($id))) {
                 Message::Info(Text::get('admin-rewards-info-status-completed'));
             } else {
                 Message::Error(Text::get('admin-rewards-error-statuschage-fail'));
             }
             throw new Redirection('/admin/rewards');
             break;
         case 'unfill':
             $sql = "UPDATE invest_reward SET fulfilled = 0 WHERE invest = ?";
             if (Model\Invest::query($sql, array($id))) {
                 Message::Info(Text::get('admin-rewards-info-status-completed-pending'));
             } else {
                 message::Error('Ha fallado al desmarcar');
             }
             throw new Redirection('/admin/rewards');
             break;
     }
     // edicion
     if ($action == 'edit' && !empty($id)) {
         $invest = Model\Invest::get($id);
         $projectData = Model\Project::get($invest->project);
         $userData = Model\User::getMini($invest->user);
         $status = Model\Project::status();
         // si tratando post
         if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update'])) {
             $errors = array();
             // la recompensa:
             $chosen = $_POST['selected_reward'];
             if (empty($chosen)) {
                 // renuncia a las recompensas, bien por el/ella!
                 $invest->rewards = array();
             } else {
                 $invest->rewards = array($chosen);
             }
             $invest->anonymous = $_POST['anonymous'];
             // dirección de envio para la recompensa
             // y datos fiscales por si fuera donativo
             $invest->address = (object) array('name' => $_POST['name'], 'nif' => $_POST['nif'], 'address' => $_POST['address'], 'zipcode' => $_POST['zipcode'], 'location' => $_POST['location'], 'country' => $_POST['country']);
             if ($invest->update($errors)) {
                 Message::Info(Text::get('admin-rewards-info-update'));
                 throw new Redirection('/admin/rewards');
             } else {
                 Message::Error('No se han actualizado correctamente los datos del aporte. ERROR: ' . implode(', ', $errors));
             }
         }
         return new View('view/admin/index.html.php', array('folder' => 'rewards', 'file' => 'edit', 'invest' => $invest, 'project' => $projectData, 'user' => $userData, 'status' => $status));
     }
     // listado de proyectos
     $projects = Model\Invest::projects();
     $status = array('nok' => Text::_("Pendiente"), 'ok' => Text::_("Cumplida"));
     // listado de aportes
     if ($filters['filtered'] == 'yes') {
         $list = Model\Project\Reward::getChossen($filters);
     } else {
         $list = array();
     }
     return new View('view/admin/index.html.php', array('folder' => 'rewards', 'file' => 'list', 'list' => $list, 'filters' => $filters, 'projects' => $projects, 'status' => $status));
 }
예제 #15
0
파일: profile.php 프로젝트: anvnguyen/Goteo
 /**
  * Tratamiendo del formulario de preferencias de notificación
  * 
  * @param string(59) $id del usuario logueado
  * @param array $errors  (por referencia)
  * @param string $log_action  (por referencia)
  * @return boolean si se guarda bien
  */
 public static function process_preferences($id, &$errors, &$log_action)
 {
     $fields = array('updates', 'threads', 'rounds', 'mailing', 'email', 'tips');
     $preferences = array();
     foreach ($fields as $field) {
         $preferences[$field] = $_POST[$field];
     }
     // actualizamos estos datos en las preferencias del usuario
     if (Model\User::setPreferences($id, $preferences, $errors)) {
         Message::Info(Text::get('user-prefer-saved'));
         $log_action = 'Modificado las preferencias de notificación';
         //feed admin
         return true;
     } else {
         Message::Error(Text::get('user-save-fail'));
         $log_action = '¡ERROR! al modificar las preferencias de notificación';
         //feed admin
         return false;
     }
 }
예제 #16
0
파일: invest.php 프로젝트: isbkch/Goteo
 public function confirmed($project = null, $id = null, $reward = null)
 {
     if (empty($id)) {
         Message::Error(Text::get('invest-data-error'));
         throw new Redirection('/', Redirection::TEMPORARY);
     }
     // el aporte
     $invest = Model\Invest::get($id);
     $projectData = Model\Project::getMedium($invest->project);
     // para evitar las duplicaciones de feed y email
     if (isset($_SESSION['invest_' . $invest->id . '_completed'])) {
         Message::Info(Text::get('invest-process-completed'));
         throw new Redirection($retUrl);
     }
     // segun método
     if ($invest->method == 'tpv') {
         // si el aporte no está en estado "cobrado por goteo" (1)
         if ($invest->status != '1') {
             @mail('*****@*****.**', 'Aporte tpv no pagado ' . $invest->id, 'Ha llegado a invest/confirm el aporte ' . $invest->id . ' mediante tpv sin estado cobrado (llega con estado ' . $invest->status . ')');
             // mandarlo a la pagina de aportar para que lo intente de nuevo
             // si es de Bazar, a la del producto del catálogo
             if ($project == 'bazargoteo') {
                 throw new Redirection("/bazaar/{$reward}/fail");
             } else {
                 throw new Redirection("/project/{$invest->project}/invest/?confirm=fail");
             }
         }
     }
     // Paypal solo disponible si activado
     if ($invest->method == 'paypal') {
         // hay que cambiarle el status a 0
         $invest->setStatus('0');
         // Evento Feed
         $log = new Feed();
         $log->setTarget($projectData->id);
         $log->populate('Aporte PayPal', '/admin/invests', \vsprintf("%s ha aportado %s al proyecto %s mediante PayPal", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('money', $invest->amount . ' &euro;'), Feed::item('project', $projectData->name, $projectData->id))));
         $log->doAdmin('money');
         // evento público
         $log_html = Text::html('feed-invest', Feed::item('money', $invest->amount . ' &euro;'), Feed::item('project', $projectData->name, $projectData->id));
         if ($invest->anonymous) {
             $log->populate(Text::get('regular-anonymous'), '/user/profile/anonymous', $log_html, 1);
         } else {
             $log->populate($_SESSION['user']->name, '/user/profile/' . $_SESSION['user']->id, $log_html, $_SESSION['user']->avatar->id);
         }
         $log->doPublic('community');
         unset($log);
     }
     // fin segun metodo
     // Feed del aporte de la campaña
     if (!empty($invest->droped) && $drop instanceof Model\Invest && is_object($callData)) {
         // Evento Feed
         $log = new Feed();
         $log->setTarget($projectData->id);
         $log->populate('Aporte riego ' . $drop->method, '/admin/invests', \vsprintf("%s ha aportado %s de %s al proyecto %s a través de la campaña %s", array(Feed::item('user', $callData->user->name, $callData->user->id), Feed::item('money', $drop->amount . ' &euro;'), Feed::item('drop', 'Capital Riego', '/service/resources'), Feed::item('project', $projectData->name, $projectData->id), Feed::item('call', $callData->name, $callData->id))));
         $log->doAdmin('money');
         // evento público
         $log->populate($callData->user->name, '/user/profile/' . $callData->user->id, Text::html('feed-invest', Feed::item('money', $drop->amount . ' &euro;') . ' de ' . Feed::item('drop', 'Capital Riego', '/service/resources'), Feed::item('project', $projectData->name, $projectData->id) . ' a través de la campaña ' . Feed::item('call', $callData->name, $callData->id)), $callData->user->avatar->id);
         $log->doPublic('community');
         unset($log);
     }
     // texto recompensa
     // @TODO quitar esta lacra de N recompensas porque ya es solo una recompensa siempre
     $rewards = $invest->rewards;
     array_walk($rewards, function (&$reward) {
         $reward = $reward->reward;
     });
     $txt_rewards = implode(', ', $rewards);
     // recaudado y porcentaje
     $amount = $projectData->invested;
     $percent = floor($projectData->invested / $projectData->mincost * 100);
     // email de agradecimiento al cofinanciador
     // primero monto el texto de recompensas
     //@TODO el concepto principal sería 'renuncia' (porque todos los aportes son donativos)
     if ($invest->resign) {
         // Plantilla de donativo segun la ronda
         if ($projectData->round == 2) {
             $template = Template::get(36);
             // en segunda ronda
         } else {
             $template = Template::get(28);
             // en primera ronda
         }
     } else {
         // plantilla de agradecimiento segun la ronda
         if ($projectData->round == 2) {
             $template = Template::get(34);
             // en segunda ronda
         } else {
             $template = Template::get(10);
             // en primera ronda
         }
     }
     // Dirección en el mail (y version para regalo)
     $txt_address = Text::get('invest-address-address-field') . ' ' . $invest->address->address;
     $txt_address .= '<br> ' . Text::get('invest-address-zipcode-field') . ' ' . $invest->address->zipcode;
     $txt_address .= '<br> ' . Text::get('invest-address-location-field') . ' ' . $invest->address->location;
     $txt_address .= '<br> ' . Text::get('invest-address-country-field') . ' ' . $invest->address->country;
     $txt_destaddr = $txt_address;
     $txt_address = Text::get('invest-mail_info-address') . '<br>' . $txt_address;
     // Agradecimiento al cofinanciador
     // Sustituimos los datos
     $subject = str_replace('%PROJECTNAME%', $projectData->name, $template->title);
     // En el contenido:
     $search = array('%USERNAME%', '%PROJECTNAME%', '%PROJECTURL%', '%AMOUNT%', '%REWARDS%');
     $replace = array($_SESSION['user']->name, $projectData->name, SITE_URL . '/project/' . $projectData->id, $confirm->amount, $txt_rewards);
     $content = \str_replace($search, $replace, $template->text);
     $mailHandler = new Mail();
     $mailHandler->reply = GOTEO_CONTACT_MAIL;
     $mailHandler->replyName = GOTEO_MAIL_NAME;
     $mailHandler->to = $_SESSION['user']->email;
     $mailHandler->toName = $_SESSION['user']->name;
     $mailHandler->subject = $subject;
     $mailHandler->content = $content;
     $mailHandler->html = true;
     $mailHandler->template = $template->id;
     if ($mailHandler->send($errors)) {
         Message::Info(Text::get('project-invest-thanks_mail-success'));
     } else {
         Message::Error(Text::get('project-invest-thanks_mail-fail'));
         Message::Error(implode('<br />', $errors));
     }
     unset($mailHandler);
     // Notificación al autor
     $template = Template::get(29);
     // Sustituimos los datos
     $subject = str_replace('%PROJECTNAME%', $projectData->name, $template->title);
     // En el contenido:
     $search = array('%OWNERNAME%', '%USERNAME%', '%PROJECTNAME%', '%SITEURL%', '%AMOUNT%', '%MESSAGEURL%');
     $replace = array($projectData->user->name, $_SESSION['user']->name, $projectData->name, SITE_URL, $invest->amount, SITE_URL . '/user/profile/' . $_SESSION['user']->id . '/message');
     $content = \str_replace($search, $replace, $template->text);
     $mailHandler = new Mail();
     $mailHandler->to = $projectData->user->email;
     $mailHandler->toName = $projectData->user->name;
     $mailHandler->subject = $subject;
     $mailHandler->content = $content;
     $mailHandler->html = true;
     $mailHandler->template = $template->id;
     $mailHandler->send();
     unset($mailHandler);
     // marcar que ya se ha completado el proceso de aportar
     $_SESSION['invest_' . $invest->id . '_completed'] = true;
     // log
     Model\Invest::setDetail($invest->id, 'confirmed', 'El usuario regresó a /invest/confirmed');
     if ($confirm->method == 'paypal') {
         // hay que cambiarle el status a 0
         $confirm->setStatus('0');
         /*
          * Evento Feed
          */
         $log = new Feed();
         $log->title = 'Aporte PayPal';
         $log->url = '/admin/invests';
         $log->type = 'money';
         $log_text = "%s ha aportado %s al proyecto %s mediante PayPal";
         $items = array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('money', $confirm->amount . ' &euro;'), Feed::item('project', $projectData->name, $projectData->id));
         $log->html = \vsprintf($log_text, $items);
         $log->add($errors);
         // evento público
         if ($confirm->anonymous) {
             $log->title = Text::get('regular-anonymous');
             $log->url = '/user/profile/anonymous';
             $log->image = 1;
         } else {
             $log->title = $_SESSION['user']->name;
             $log->url = '/user/profile/' . $_SESSION['user']->id;
             $log->image = $_SESSION['user']->avatar->id;
         }
         $log->scope = 'public';
         $log->type = 'community';
         $log->html = Text::html('feed-invest', Feed::item('money', $confirm->amount . ' &euro;'), Feed::item('project', $projectData->name, $projectData->id));
         $log->add($errors);
         unset($log);
     }
     // mandarlo a la pagina de gracias
     throw new Redirection("/project/{$project}/invest/?confirm=ok", Redirection::TEMPORARY);
 }
예제 #17
0
파일: message.php 프로젝트: kenjs/Goteo
 public function personal($user = null)
 {
     if (empty($user)) {
         throw new Redirection('/community', Redirection::PERMANENT);
     }
     if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['message'])) {
         // sacamos el mail del responsable del proyecto
         $user = Model\User::get($user);
         if (!$user instanceof Model\User) {
             throw new Redirection('/', Redirection::TEMPORARY);
         }
         $msg_content = \nl2br(\strip_tags($_POST['message']));
         // Obtenemos la plantilla para asunto y contenido
         $template = Template::get(4);
         // Sustituimos los datos
         if (isset($_POST['subject']) && !empty($_POST['subject'])) {
             $subject = $_POST['subject'];
         } else {
             // En el asunto por defecto: %USERNAME% por $_SESSION['user']->name
             $subject = str_replace('%USERNAME%', $_SESSION['user']->name, $template->title);
         }
         $remite = $_SESSION['user']->name . ' ' . Text::get('regular-from') . ' ';
         $remite .= GOTEO_MAIL_NAME;
         $response_url = SITE_URL . '/user/profile/' . $_SESSION['user']->id . '/message';
         $profile_url = SITE_URL . "/user/profile/{$user->id}/sharemates";
         // En el contenido:  nombre del destinatario -> %TONAME% por $user->name
         // el mensaje que ha escrito el usuario -> %MESSAGE% por $msg_content
         // nombre del usuario -> %USERNAME% por $_SESSION['user']->name
         // url del perfil -> %PROFILEURL% por ".SITE_URL."/user/profile/{$user->id}/sharemates"
         $search = array('%MESSAGE%', '%TONAME%', '%USERNAME%', '%PROFILEURL%', '%RESPONSEURL%');
         $replace = array($msg_content, $user->name, $_SESSION['user']->name, $profile_url, $response_url);
         $content = \str_replace($search, $replace, $template->text);
         $mailHandler = new Mail();
         $mailHandler->fromName = $remite;
         $mailHandler->to = $user->email;
         $mailHandler->toName = $user->name;
         // blind copy a goteo desactivado durante las verificaciones
         //                $mailHandler->bcc = '*****@*****.**';
         $mailHandler->subject = $subject;
         $mailHandler->content = $content;
         $mailHandler->html = true;
         $mailHandler->template = $template->id;
         if ($mailHandler->send($errors)) {
             // ok
             \Goteo\Library\Message::Info(Text::get('regular-message_success'));
         } else {
             \Goteo\Library\Message::Info(Text::get('regular-message_fail') . '<br />' . implode(', ', $errors));
         }
         unset($mailHandler);
     }
     throw new Redirection("/user/profile/{$user->id}", Redirection::TEMPORARY);
 }
예제 #18
0
파일: accounts.php 프로젝트: isbkch/Goteo
 public static function process($action = 'list', $id = null, $filters = array())
 {
     $errors = array();
     // reubicando aporte,
     if ($action == 'move') {
         // el aporte original
         $original = Model\Invest::get($id);
         $userData = Model\User::getMini($original->user);
         $projectData = Model\Project::getMini($original->project);
         //el original tiene que ser de tpv o cash y estar como 'cargo ejecutado'
         if ($original->method == 'paypal' || $original->status != 1) {
             Message::Error('No se puede reubicar este aporte!');
             throw new Redirection('/admin/accounts');
         }
         // generar aporte manual y caducar el original
         if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['move'])) {
             // si falta proyecto, error
             $projectNew = $_POST['project'];
             // @TODO a saber si le toca dinero de alguna convocatoria
             $campaign = null;
             $invest = new Model\Invest(array('amount' => $original->amount, 'user' => $original->user, 'project' => $projectNew, 'account' => $userData->email, 'method' => 'cash', 'status' => '1', 'invested' => date('Y-m-d'), 'charged' => $original->charged, 'anonymous' => $original->anonymous, 'resign' => $original->resign, 'admin' => $_SESSION['user']->id, 'campaign' => $campaign));
             //@TODO si el proyecto seleccionado
             if ($invest->save($errors)) {
                 //recompensas que le tocan (si no era resign)
                 if (!$original->resign) {
                     // sacar recompensas
                     $rewards = Model\Project\Reward::getAll($projectNew, 'individual');
                     foreach ($rewards as $rewId => $rewData) {
                         $invest->setReward($rewId);
                         //asignar
                     }
                 }
                 // cambio estado del aporte original a 'Reubicado' (no aparece en cofinanciadores)
                 // si tuviera que aparecer lo marcaríamos como caducado
                 if ($original->setStatus('5')) {
                     // Evento Feed
                     $log = new Feed();
                     $log->setTarget($projectData->id);
                     $log->populate('Aporte reubicado', '/admin/accounts', \vsprintf("%s ha aportado %s al proyecto %s en nombre de %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('money', $_POST['amount'] . ' &euro;'), Feed::item('project', $projectData->name, $projectData->id), Feed::item('user', $userData->name, $userData->id))));
                     $log->doAdmin('money');
                     unset($log);
                     Message::Info('Aporte reubicado correctamente');
                     throw new Redirection('/admin/accounts');
                 } else {
                     $errors[] = 'A fallado al cambiar el estado del aporte original (' . $original->id . ')';
                 }
             } else {
                 $errors[] = 'Ha fallado algo al reubicar el aporte';
             }
         }
         $viewData = array('folder' => 'accounts', 'file' => 'move', 'original' => $original, 'user' => $userData, 'project' => $projectData);
         return new View('view/admin/index.html.php', $viewData);
         // fin de la historia dereubicar
     }
     // cambiando estado del aporte aporte,
     if ($action == 'update') {
         // el aporte original
         $invest = Model\Invest::get($id);
         if (!$invest instanceof Model\Invest) {
             Message::Error('No tenemos registro del aporte ' . $id);
             throw new Redirection('/admin/accounts');
         }
         $status = Model\Invest::status();
         $new = isset($_POST['status']) ? $_POST['status'] : null;
         if ($invest->issue && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update']) && $_POST['resolve'] == 1) {
             Model\Invest::unsetIssue($id);
             Model\Invest::setDetail($id, 'issue-solved', 'La incidencia se ha dado por resuelta por el usuario ' . $_SESSION['user']->name);
             Message::Info('La incidencia se ha dado por resuelta');
         }
         if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update']) && isset($new) && isset($status[$new])) {
             if ($new != $invest->status) {
                 if (Model\Invest::query("UPDATE invest SET status=:status WHERE id=:id", array(':id' => $id, ':status' => $new))) {
                     Model\Invest::setDetail($id, 'status-change' . rand(0, 9999), 'El admin ' . $_SESSION['user']->name . ' ha cambiado el estado del apote a ' . $status[$new]);
                     Message::Info('Se ha actualizado el estado del aporte');
                 } else {
                     Message::Error('Ha fallado al actualizar el estado del aporte');
                 }
             } else {
                 Message::Error('No se ha cambiado el estado');
             }
             throw new Redirection('/admin/accounts/details/' . $id);
         }
         return new View('view/admin/index.html.php', array('folder' => 'accounts', 'file' => 'update', 'invest' => $invest, 'status' => $status));
         // fin de la historia actualizar estado
     }
     // resolviendo incidencias
     if ($action == 'solve') {
         // el aporte original
         $invest = Model\Invest::get($id);
         if (!$invest instanceof Model\Invest) {
             Message::Error('No tenemos registro del aporte ' . $id);
             throw new Redirection('/admin/accounts');
         }
         $projectData = Model\Project::getMini($invest->project);
         $errors = array();
         // primero cancelar
         switch ($invest->method) {
             case 'paypal':
                 $err = array();
                 if (Paypal::cancelPreapproval($invest, $err)) {
                     $errors[] = 'Preaproval paypal cancelado.';
                     $log_text = "El admin %s ha cancelado aporte y preapproval de %s de %s mediante PayPal (id: %s) al proyecto %s del dia %s";
                 } else {
                     $txt_errors = implode('; ', $err);
                     $errors[] = 'Fallo al cancelar el preapproval en paypal: ' . $txt_errors;
                     $log_text = "El admin %s ha fallado al cancelar el aporte de %s de %s mediante PayPal (id: %s) al proyecto %s del dia %s. <br />Se han dado los siguientes errores: {$txt_errors}";
                     if ($invest->cancel()) {
                         $errors[] = 'Aporte cancelado';
                     } else {
                         $errors[] = 'Fallo al cancelar el aporte';
                     }
                 }
                 break;
             case 'tpv':
                 $err = array();
                 if (Tpv::cancelPreapproval($invest, $err)) {
                     $txt_errors = implode('; ', $err);
                     $errors[] = 'Aporte cancelado correctamente. ' . $txt_errors;
                     $log_text = "El admin %s ha anulado el cargo tpv de %s de %s mediante TPV (id: %s) al proyecto %s del dia %s";
                 } else {
                     $txt_errors = implode('; ', $err);
                     $errors[] = 'Fallo en la operación. ' . $txt_errors;
                     $log_text = "El admin %s ha fallado al solicitar la cancelación del cargo tpv de %s de %s mediante TPV (id: %s) al proyecto %s del dia %s. <br />Se han dado los siguientes errores: {$txt_errors}";
                 }
                 break;
             case 'cash':
                 if ($invest->cancel()) {
                     $log_text = "El admin %s ha cancelado aporte manual de %s de %s (id: %s) al proyecto %s del dia %s";
                     $errors[] = 'Aporte cancelado';
                 } else {
                     $log_text = "El admin %s ha fallado al cancelar el aporte manual de %s de %s (id: %s) al proyecto %s del dia %s. ";
                     $errors[] = 'Fallo al cancelar el aporte';
                 }
                 break;
         }
         // Evento Feed
         $log = new Feed();
         $log->setTarget($projectData->id);
         $log->populate('Cargo cancelado manualmente (admin)', '/admin/accounts', \vsprintf($log_text, array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('user', $userData->name, $userData->id), Feed::item('money', $invest->amount . ' &euro;'), Feed::item('system', $invest->id), Feed::item('project', $projectData->name, $projectData->id), Feed::item('system', date('d/m/Y', strtotime($invest->invested))))));
         $log->doAdmin();
         unset($log);
         // luego resolver
         if ($invest->solve($errors)) {
             // Evento Feed
             $log = new Feed();
             $log->setTarget($projectData->id);
             $log->populate('Incidencia resuelta (admin)', '/admin/accounts', \vsprintf("El admin %s ha dado por resuelta la incidencia con el botón \"Nos han hecho la transferencia\" para el aporte %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('system', $id, 'accounts/details/' . $id))));
             $log->doAdmin('admin');
             unset($log);
             Message::Info('La incidencia se ha dado por resuelta, el aporte se ha pasado a manual y cobrado');
             throw new Redirection('/admin/accounts');
         } else {
             // Evento Feed
             $log = new Feed();
             $log->setTarget($projectData->id);
             $log->populate('Fallo al resolver incidencia (admin)', '/admin/accounts', \vsprintf("Al admin %s le ha fallado el botón \"Nos han hecho la transferencia\" para el aporte %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('system', $id, 'accounts/details/' . $id))));
             $log->doAdmin('admin');
             unset($log);
             Message::Error('Ha fallado al resolver la incidencia: ' . implode(',', $errors));
             throw new Redirection('/admin/accounts/details/' . $id);
         }
     }
     // aportes manuales, cargamos la lista completa de usuarios, proyectos y campañas
     if ($action == 'add') {
         // listado de proyectos en campaña
         $projects = Model\Project::active(false, true);
         // usuarios
         $users = Model\User::getAllMini();
         // campañas
         //@CALLSYS
         $calls = array();
         // generar aporte manual
         if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add'])) {
             $userData = Model\User::getMini($_POST['user']);
             $projectData = Model\Project::getMini($_POST['project']);
             $invest = new Model\Invest(array('amount' => $_POST['amount'], 'user' => $userData->id, 'project' => $projectData->id, 'account' => $userData->email, 'method' => 'cash', 'status' => '1', 'invested' => date('Y-m-d'), 'charged' => date('Y-m-d'), 'anonymous' => $_POST['anonymous'], 'resign' => 1, 'admin' => $_SESSION['user']->id));
             //@CALLSYS
             if ($invest->save($errors)) {
                 // Evento Feed
                 $log = new Feed();
                 $log->setTarget($projectData->id);
                 $log->populate('Aporte manual (admin)', '/admin/accounts', \vsprintf("%s ha aportado %s al proyecto %s en nombre de %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('money', $_POST['amount'] . ' &euro;'), Feed::item('project', $projectData->name, $projectData->id), Feed::item('user', $userData->name, $userData->id))));
                 $log->doAdmin('money');
                 unset($log);
                 Model\Invest::setDetail($invest->id, 'admin-created', 'Este aporte ha sido creado manualmente por el admin ' . $_SESSION['user']->name);
                 Message::Info('Aporte manual creado correctamente, seleccionar recompensa y dirección de entrega.');
                 throw new Redirection('/admin/rewards/edit/' . $invest->id);
             } else {
                 $errors[] = 'Ha fallado algo al crear el aporte manual';
             }
         }
         $viewData = array('folder' => 'accounts', 'file' => 'add', 'autocomplete' => true, 'users' => $users, 'projects' => $projects, 'calls' => $calls);
         return new View('view/admin/index.html.php', $viewData);
         // fin de la historia
     }
     // Informe de la financiación de un proyecto
     if ($action == 'report') {
         // estados de aporte
         $project = Model\Project::get($id);
         if (!$project instanceof Model\Project) {
             Message::Error('Instancia de proyecto no valida');
             throw new Redirection('/admin/accounts');
         }
         $invests = Model\Invest::getAll($id);
         $project->investors = Model\Invest::investors($id, false, true);
         $users = $project->agregateInvestors();
         $investStatus = Model\Invest::status();
         // Datos para el informe de transacciones correctas
         $Data = Model\Invest::getReportData($project->id, $project->status, $project->round, $project->passed);
         return new View('view/admin/index.html.php', array('folder' => 'accounts', 'file' => 'report', 'invests' => $invests, 'project' => $project, 'status' => $status, 'users' => $users, 'investStatus' => $investStatus, 'Data' => $Data));
     }
     // cancelar aporte antes de ejecución, solo aportes no cargados
     if ($action == 'cancel') {
         $invest = Model\Invest::get($id);
         if (!$invest instanceof Model\Invest) {
             Message::Error('No tenemos objeto para el aporte ' . $id);
             throw new Redirection('/admin/accounts');
         }
         $project = Model\Project::get($invest->project);
         $userData = Model\User::get($invest->user);
         if ($project->status > 3 && $project->status < 6) {
             $errors[] = 'No debería poderse cancelar un aporte cuando el proyecto ya está financiado. Si es imprescindible, hacerlo desde el panel de paypal o tpv';
             break;
         }
         switch ($invest->method) {
             case 'paypal':
                 $err = array();
                 if (Paypal::cancelPreapproval($invest, $err)) {
                     $errors[] = 'Preaproval paypal cancelado.';
                     $log_text = "El admin %s ha cancelado aporte y preapproval de %s de %s mediante PayPal (id: %s) al proyecto %s del dia %s";
                 } else {
                     $txt_errors = implode('; ', $err);
                     $errors[] = 'Fallo al cancelar el preapproval en paypal: ' . $txt_errors;
                     $log_text = "El admin %s ha fallado al cancelar el aporte de %s de %s mediante PayPal (id: %s) al proyecto %s del dia %s. <br />Se han dado los siguientes errores: {$txt_errors}";
                     if ($invest->cancel()) {
                         $errors[] = 'Aporte cancelado';
                     } else {
                         $errors[] = 'Fallo al cancelar el aporte';
                     }
                 }
                 break;
             case 'tpv':
                 $err = array();
                 if (Tpv::cancelPreapproval($invest, $err)) {
                     $txt_errors = implode('; ', $err);
                     $errors[] = 'Aporte cancelado correctamente. ' . $txt_errors;
                     $log_text = "El admin %s ha anulado el cargo tpv de %s de %s mediante TPV (id: %s) al proyecto %s del dia %s";
                 } else {
                     $txt_errors = implode('; ', $err);
                     $errors[] = 'Fallo en la operación. ' . $txt_errors;
                     $log_text = "El admin %s ha fallado al solicitar la cancelación del cargo tpv de %s de %s mediante TPV (id: %s) al proyecto %s del dia %s. <br />Se han dado los siguientes errores: {$txt_errors}";
                 }
                 break;
             case 'cash':
                 if ($invest->cancel()) {
                     $log_text = "El admin %s ha cancelado aporte manual de %s de %s (id: %s) al proyecto %s del dia %s";
                     $errors[] = 'Aporte cancelado';
                 } else {
                     $log_text = "El admin %s ha fallado al cancelar el aporte manual de %s de %s (id: %s) al proyecto %s del dia %s. ";
                     $errors[] = 'Fallo al cancelar el aporte';
                 }
                 break;
         }
         // Evento Feed
         $log = new Feed();
         $log->setTarget($project->id);
         $log->populate('Cargo cancelado manualmente (admin)', '/admin/accounts', \vsprintf($log_text, array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('user', $userData->name, $userData->id), Feed::item('money', $invest->amount . ' &euro;'), Feed::item('system', $invest->id), Feed::item('project', $project->name, $project->id), Feed::item('system', date('d/m/Y', strtotime($invest->invested))))));
         $log->doAdmin();
         Model\Invest::setDetail($invest->id, 'manually-canceled', $log->html);
         unset($log);
     }
     // ejecutar cargo ahora!!, solo aportes no ejecutados
     // si esta pendiente, ejecutar el cargo ahora (como si fuera final de ronda), deja pendiente el pago secundario
     if ($action == 'execute' && $invest->status == 0) {
         $invest = Model\Invest::get($id);
         if (!$invest instanceof Model\Invest) {
             Message::Error('No tenemos objeto para el aporte ' . $id);
             throw new Redirection('/admin/accounts');
         }
         $project = Model\Project::get($invest->project);
         $userData = Model\User::get($invest->user);
         switch ($invest->method) {
             case 'paypal':
                 // a ver si tiene cuenta paypal
                 $projectAccount = Model\Project\Account::get($invest->project);
                 if (empty($projectAccount->paypal)) {
                     // Erroraco!
                     $errors[] = 'El proyecto no tiene cuenta paypal!!, ponersela en la seccion Contrato del dashboard del autor';
                     $log_text = null;
                     // Evento Feed
                     $log = new Feed();
                     $log->setTarget($project->id);
                     $log->populate('proyecto sin cuenta paypal (admin)', '/admin/projects', \vsprintf('El proyecto %s aun no ha puesto su %s !!!', array(Feed::item('project', $project->name, $project->id), Feed::item('relevant', 'cuenta PayPal'))));
                     $log->doAdmin('project');
                     unset($log);
                     break;
                 }
                 $invest->account = $projectAccount->paypal;
                 if (Paypal::pay($invest, $errors)) {
                     $errors[] = 'Cargo paypal correcto';
                     $log_text = "El admin %s ha ejecutado el cargo a %s por su aporte de %s mediante PayPal (id: %s) al proyecto %s del dia %s";
                     $invest->status = 1;
                     // si era incidencia la desmarcamos
                     if ($invest->issue) {
                         Model\Invest::unsetIssue($invest->id);
                         Model\Invest::setDetail($invest->id, 'issue-solved', 'La incidencia se ha dado por resuelta al ejecutar el aporte manualmente por el admin ' . $_SESSION['user']->name);
                     }
                 } else {
                     $txt_errors = implode('; ', $errors);
                     $errors[] = 'Fallo al ejecutar cargo paypal: ' . $txt_errors . '<strong>POSIBLE INCIDENCIA NO COMUNICADA Y APORTE NO CANCELADO, HAY QUE TRATARLA MANUALMENTE</strong>';
                     $log_text = "El admin %s ha fallado al ejecutar el cargo a %s por su aporte de %s mediante PayPal (id: %s) al proyecto %s del dia %s. <br />Se han dado los siguientes errores: {$txt_errors}";
                 }
                 break;
             case 'tpv':
                 if (Tpv::pay($invest, $errors)) {
                     $errors[] = 'Cargo sermepa correcto';
                     $log_text = "El admin %s ha ejecutado el cargo a %s por su aporte de %s mediante TPV (id: %s) al proyecto %s del dia %s";
                     $invest->status = 1;
                 } else {
                     $txt_errors = implode('; ', $errors);
                     $errors[] = 'Fallo al ejecutar cargo sermepa: ' . $txt_errors;
                     $log_text = "El admin %s ha fallado al ejecutar el cargo a %s por su aporte de %s mediante TPV (id: %s) al proyecto %s del dia %s <br />Se han dado los siguientes errores: {$txt_errors}";
                 }
                 break;
             case 'cash':
                 $invest->setStatus('1');
                 $errors[] = 'Aporte al contado, nada que ejecutar.';
                 $log_text = "El admin %s ha dado por ejecutado el aporte manual a nombre de %s por la cantidad de %s (id: %s) al proyecto %s del dia %s";
                 $invest->status = 1;
                 break;
         }
         if (!empty($log_text)) {
             // Evento Feed
             $log = new Feed();
             $log->setTarget($project->id);
             $log->populate('Cargo ejecutado manualmente (admin)', '/admin/accounts', \vsprintf($log_text, array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('user', $userData->name, $userData->id), Feed::item('money', $invest->amount . ' &euro;'), Feed::item('system', $invest->id), Feed::item('project', $project->name, $project->id), Feed::item('system', date('d/m/Y', strtotime($invest->invested))))));
             $log->doAdmin();
             Model\Invest::setDetail($invest->id, 'manually-executed', $log->html);
             unset($log);
         }
     }
     // visor de logs
     if ($action == 'viewer') {
         return new View('view/admin/index.html.php', array('folder' => 'accounts', 'file' => 'viewer'));
     }
     if ($action == 'resign' && !empty($id) && $_GET['token'] == md5('resign')) {
         if ($invest->setResign(true)) {
             Model\Invest::setDetail($invest->id, 'manually-resigned', 'Se ha marcado como donativo independientemente de las recompensas');
             throw new Redirection('/admin/accounts/detail/' . $invest->id);
         } else {
             $errors[] = 'Ha fallado al marcar donativo';
         }
     }
     if (!empty($errors)) {
         Message::Error(implode('<br />', $errors));
     }
     // tipos de aporte
     $methods = Model\Invest::methods();
     // estados del proyecto
     $status = Model\Project::status();
     $procStatus = Model\Project::procStatus();
     // estados de aporte
     $investStatus = Model\Invest::status();
     // listado de proyectos
     $projects = Model\Invest::projects();
     // usuarios cofinanciadores
     $users = Model\Invest::users(true);
     // campañas que tienen aportes
     $calls = Model\Invest::calls();
     // extras
     $types = array('donative' => 'Solo los donativos', 'anonymous' => 'Solo los anónimos', 'manual' => 'Solo los manuales', 'campaign' => 'Solo con riego');
     // filtros de revisión de proyecto
     $review = array('collect' => 'Recaudado', 'paypal' => 'Rev. PayPal', 'tpv' => 'Rev. TPV', 'online' => 'Pagos Online');
     $issue = array('show' => 'Solamente las incidencias', 'hide' => 'Ocultar las incidencias');
     /// detalles de una transaccion
     if ($action == 'details') {
         $invest = Model\Invest::get($id);
         $project = Model\Project::get($invest->project);
         $userData = Model\User::get($invest->user);
         return new View('view/admin/index.html.php', array('folder' => 'accounts', 'file' => 'details', 'invest' => $invest, 'project' => $project, 'user' => $userData, 'details' => $details, 'status' => $status, 'investStatus' => $investStatus));
     }
     // listado de aportes
     if ($filters['filtered'] == 'yes') {
         $list = Model\Invest::getList($filters, null, 999);
     } else {
         $list = array();
     }
     $viewData = array('folder' => 'accounts', 'file' => 'list', 'list' => $list, 'filters' => $filters, 'users' => $users, 'projects' => $projects, 'calls' => $calls, 'review' => $review, 'methods' => $methods, 'types' => $types, 'status' => $status, 'procStatus' => $procStatus, 'issue' => $issue, 'investStatus' => $investStatus);
     return new View('view/admin/index.html.php', $viewData);
 }
예제 #19
0
 public static function process($action = 'list', $id = null, $filters = array())
 {
     $log_text = null;
     $errors = array();
     // multiples usos
     $nodes = array();
     if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id'])) {
         $projData = Model\Project::get($_POST['id']);
         if (empty($projData->id)) {
             Message::Error('El proyecto ' . $_POST['id'] . ' no existe');
             throw new Redirection('/admin/projects/images/' . $id);
         }
         if (isset($_POST['save-dates'])) {
             $fields = array('created', 'updated', 'published', 'success', 'closed', 'passed');
             $set = '';
             $values = array(':id' => $projData->id);
             foreach ($fields as $field) {
                 if ($set != '') {
                     $set .= ", ";
                 }
                 $set .= "`{$field}` = :{$field} ";
                 if (empty($_POST[$field]) || $_POST[$field] == '0000-00-00') {
                     $_POST[$field] = null;
                 }
                 $values[":{$field}"] = $_POST[$field];
             }
             try {
                 $sql = "UPDATE project SET " . $set . " WHERE id = :id";
                 if (Model\Project::query($sql, $values)) {
                     $log_text = 'El admin %s ha <span class="red">tocado las fechas</span> del proyecto ' . $projData->name . ' %s';
                 } else {
                     $log_text = 'Al admin %s le ha <span class="red">fallado al tocar las fechas</span> del proyecto ' . $projData->name . ' %s';
                 }
             } catch (\PDOException $e) {
                 Message::Error(Text::_("No se ha guardado correctamente. ") . $e->getMessage());
             }
         } elseif (isset($_POST['save-accounts'])) {
             $accounts = Model\Project\Account::get($projData->id);
             $accounts->bank = $_POST['bank'];
             $accounts->bank_owner = $_POST['bank_owner'];
             $accounts->paypal = $_POST['paypal'];
             $accounts->paypal_owner = $_POST['paypal_owner'];
             if ($accounts->save($errors)) {
                 Message::Info(Text::_('Se han actualizado las cuentas del proyecto ') . $projData->name);
             } else {
                 Message::Error(implode('<br />', $errors));
             }
         } elseif ($action == 'images') {
             $todook = true;
             if (!empty($_POST['move'])) {
                 $direction = $_POST['action'];
                 Model\Project\Image::$direction($id, $_POST['move'], $_POST['section']);
             }
             foreach ($_POST as $key => $value) {
                 $parts = explode('_', $key);
                 if ($parts[1] == 'image' && in_array($parts[0], array('section', 'url'))) {
                     if (Model\Project\Image::update($id, $parts[2], $parts[0], $value)) {
                         // OK
                     } else {
                         $todook = false;
                         Message::Error(Text::_('No se ha podido actualizar campo') . " {$parts[0]} -> {$value}");
                     }
                 }
             }
             if ($todook) {
                 Message::Info(Text::_('Se han actualizado los datos'));
             }
             throw new Redirection('/admin/projects/images/' . $id);
         } elseif ($action == 'rebase') {
             $todook = true;
             if ($_POST['proceed'] == 'rebase' && !empty($_POST['newid'])) {
                 $newid = $_POST['newid'];
                 // pimero miramos que no hay otro proyecto con esa id
                 $test = Model\Project::getMini($newid);
                 if ($test->id == $newid) {
                     Message::Error(Text::_('Ya hay un proyecto con ese Id.'));
                     throw new Redirection('/admin/projects/rebase/' . $id);
                 }
                 if ($projData->status >= 3 && $_POST['force'] != 1) {
                     Message::Error(Text::_('El proyecto no está ni en Edición ni en Revisión, no se modifica nada.'));
                     throw new Redirection('/admin/projects/rebase/' . $id);
                 }
                 if ($projData->rebase($newid)) {
                     Message::Info(Text::_('Verificar el proyecto') . ' -> <a href="' . SITE_URL . '/project/' . $newid . '" target="_blank">' . $projData->name . '</a>');
                     throw new Redirection('/admin/projects');
                 } else {
                     Message::Info(Text::_('Ha fallado algo en el rebase, verificar el proyecto') . ' -> <a href="' . SITE_URL . '/project/' . $projData->id . '" target="_blank">' . $projData->name . ' (' . $id . ')</a>');
                     throw new Redirection('/admin/projects/rebase/' . $id);
                 }
             }
         }
     }
     /*
      * switch action,
      * proceso que sea,
      * redirect
      *
      */
     if (isset($id)) {
         $project = Model\Project::get($id);
     }
     switch ($action) {
         case 'review':
             // pasar un proyecto a revision
             if ($project->ready($errors)) {
                 $redir = '/admin/reviews/add/' . $project->id;
                 $log_text = 'El admin %s ha pasado el proyecto %s al estado <span class="red">Revision</span>';
             } else {
                 $log_text = 'Al admin %s le ha fallado al pasar el proyecto %s al estado <span class="red">Revision</span>';
             }
             break;
         case 'publish':
             // poner un proyecto en campa�a
             if ($project->publish($errors)) {
                 $log_text = 'El admin %s ha pasado el proyecto %s al estado <span class="red">en Campa�a</span>';
             } else {
                 $log_text = 'Al admin %s le ha fallado al pasar el proyecto %s al estado <span class="red">en Campa�a</span>';
             }
             break;
         case 'cancel':
             // descartar un proyecto por malo
             if ($project->cancel($errors)) {
                 $log_text = 'El admin %s ha pasado el proyecto %s al estado <span class="red">Descartado</span>';
             } else {
                 $log_text = 'Al admin %s le ha fallado al pasar el proyecto %s al estado <span class="red">Descartado</span>';
             }
             break;
         case 'enable':
             // si no esta en edicion, recuperarlo
             if ($project->enable($errors)) {
                 $log_text = 'El admin %s ha pasado el proyecto %s al estado <span class="red">Edicion</span>';
             } else {
                 $log_text = 'Al admin %s le ha fallado al pasar el proyecto %s al estado <span class="red">Edicion</span>';
             }
             break;
         case 'fulfill':
             // marcar que el proyecto ha cumplido con los retornos colectivos
             if ($project->satisfied($errors)) {
                 $log_text = 'El admin %s ha pasado el proyecto %s al estado <span class="red">Retorno cumplido</span>';
             } else {
                 $log_text = 'Al admin %s le ha fallado al pasar el proyecto %s al estado <span class="red">Retorno cumplido</span>';
             }
             break;
         case 'unfulfill':
             // dar un proyecto por financiado manualmente
             if ($project->rollback($errors)) {
                 $log_text = 'El admin %s ha pasado el proyecto %s al estado <span class="red">Financiado</span>';
             } else {
                 $log_text = 'Al admin %s le ha fallado al pasar el proyecto %s al estado <span class="red">Financiado</span>';
             }
             break;
     }
     if (isset($log_text)) {
         // Evento Feed
         $log = new Feed();
         $log->setTarget($project->id);
         $log->populate(Text::_('Cambio estado/fechas/cuentas/nodo de un proyecto desde el admin'), '/admin/projects', \vsprintf($log_text, array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('project', $project->name, $project->id))));
         $log->doAdmin('admin');
         Message::Info($log->html);
         if (!empty($errors)) {
             Message::Error(implode('<br />', $errors));
         }
         if ($action == 'publish') {
             // si es publicado, hay un evento publico
             $log->populate($project->name, '/project/' . $project->id, Text::html('feed-new_project'), $project->gallery[0]->id);
             $log->doPublic('projects');
         }
         unset($log);
         if (empty($redir)) {
             throw new Redirection('/admin/projects/list');
         } else {
             throw new Redirection($redir);
         }
     }
     if ($action == 'report') {
         // informe financiero
         // Datos para el informe de transacciones correctas
         $Data = Model\Invest::getReportData($project->id, $project->status, $project->round, $project->passed);
         return new View('view/admin/index.html.php', array('folder' => 'projects', 'file' => 'report', 'project' => $project, 'Data' => $Data));
     }
     if ($action == 'dates') {
         // cambiar fechas
         return new View('view/admin/index.html.php', array('folder' => 'projects', 'file' => 'dates', 'project' => $project));
     }
     if ($action == 'accounts') {
         $accounts = Model\Project\Account::get($project->id);
         // cambiar fechas
         return new View('view/admin/index.html.php', array('folder' => 'projects', 'file' => 'accounts', 'project' => $project, 'accounts' => $accounts));
     }
     if ($action == 'images') {
         // imagenes
         $images = array();
         // secciones
         $sections = Model\Project\Image::sections();
         foreach ($sections as $sec => $secName) {
             $secImages = Model\Project\Image::get($project->id, $sec);
             foreach ($secImages as $img) {
                 $images[$sec][] = $img;
             }
         }
         return new View('view/admin/index.html.php', array('folder' => 'projects', 'file' => 'images', 'project' => $project, 'images' => $images, 'sections' => $sections));
     }
     if ($action == 'move') {
         // cambiar el nodo
         return new View('view/admin/index.html.php', array('folder' => 'projects', 'file' => 'move', 'project' => $project, 'nodes' => $nodes));
     }
     if ($action == 'rebase') {
         // cambiar la id
         return new View('view/admin/index.html.php', array('folder' => 'projects', 'file' => 'rebase', 'project' => $project));
     }
     // Rechazo express
     if ($action == 'reject') {
         if (empty($project)) {
             Message::Error(Text::_('No hay proyecto sobre el que operar'));
         } else {
             // Obtenemos la plantilla para asunto y contenido
             $template = Template::get(40);
             // Sustituimos los datos
             $subject = str_replace('%PROJECTNAME%', $project->name, $template->title);
             $search = array('%USERNAME%', '%PROJECTNAME%');
             $replace = array($project->user->name, $project->name);
             $content = \str_replace($search, $replace, $template->text);
             // iniciamos mail
             $mailHandler = new Mail();
             $mailHandler->to = $project->user->email;
             $mailHandler->toName = $project->user->name;
             $mailHandler->subject = $subject;
             $mailHandler->content = $content;
             $mailHandler->html = true;
             $mailHandler->template = $template->id;
             if ($mailHandler->send()) {
                 Message::Info('Se ha enviado un email a <strong>' . $project->user->name . '</strong> a la dirección <strong>' . $project->user->email . '</strong>');
             } else {
                 Message::Error('Ha fallado al enviar el mail a <strong>' . $project->user->name . '</strong> a la dirección <strong>' . $project->user->email . '</strong>');
             }
             unset($mailHandler);
         }
         throw new Redirection('/admin/projects/list');
     }
     if (!empty($filters['filtered'])) {
         $projects = Model\Project::getList($filters, $_SESSION['admin_node']);
     } else {
         $projects = array();
     }
     $status = Model\Project::status();
     $categories = Model\Project\Category::getAll();
     //@CONTRACTSYS
     $calls = array();
     // la lista de nodos la hemos cargado arriba
     $orders = array('name' => Text::_('Nombre'), 'updated' => Text::_('Enviado a revision'));
     return new View('view/admin/index.html.php', array('folder' => 'projects', 'file' => 'list', 'projects' => $projects, 'filters' => $filters, 'status' => $status, 'categories' => $categories, 'calls' => $calls, 'nodes' => $nodes, 'orders' => $orders));
 }
예제 #20
0
 public static function menu($BC = array())
 {
     $admin_label = Text::_('Admin');
     $options = static::_options();
     $supervisors = static::_supervisors();
     // El menu del panel admin dependerá del rol del usuario que accede
     // Superadmin = todo
     // Admin = contenidos de Nodo
     // Supervisor = menus especiales
     if (isset($supervisors[$_SESSION['user']->id])) {
         $menu = self::setMenu('supervisor', $_SESSION['user']->id);
     } elseif (isset($_SESSION['user']->roles['admin'])) {
         $menu = self::setMenu('admin', $_SESSION['user']->id);
     } else {
         $menu = self::setMenu('superadmin', $_SESSION['user']->id);
     }
     // si el breadcrumbs no es un array vacio,
     // devolveremos el contenido html para pintar el camino de migas de pan
     // con enlaces a lo anterior
     if (empty($BC)) {
         return $menu;
     } else {
         // a ver si puede estar aqui!
         if ($BC['option'] != 'index') {
             $puede = false;
             foreach ($menu as $sCode => $section) {
                 if (isset($section['options'][$BC['option']])) {
                     $puede = true;
                     break;
                 }
             }
             if (!$puede) {
                 Message::Error(Text::get('admin-no_permission', $options[$BC['option']]['label']));
                 throw new Redirection('/admin');
             }
         }
         // Los últimos serán los primeros
         $path = '';
         // si el BC tiene Id, accion sobre ese registro
         // si el BC tiene Action
         if (!empty($BC['action']) && $BC['action'] != 'list') {
             // si es una accion no catalogada, mostramos la lista
             if (!in_array($BC['action'], array_keys($options[$BC['option']]['actions']))) {
                 $BC['action'] = '';
                 $BC['id'] = null;
             }
             $action = $options[$BC['option']]['actions'][$BC['action']];
             // si es de item , añadir el id (si viene)
             if ($action['item'] && !empty($BC['id'])) {
                 $path = " &gt; <strong>{$action['label']}</strong> {$BC['id']}";
             } else {
                 $path = " &gt; <strong>{$action['label']}</strong>";
             }
         }
         // si el BC tiene Option, enlace a la portada de esa gestión (a menos que sea laaccion por defecto)
         if (!empty($BC['option']) && isset($options[$BC['option']])) {
             $option = $options[$BC['option']];
             if ($BC['action'] == 'list') {
                 $path = " &gt; <strong>{$option['label']}</strong>";
             } else {
                 $path = ' &gt; <a href="/admin/' . $BC['option'] . '">' . $option['label'] . '</a>' . $path;
             }
         }
         // si el BC tiene section, facil, enlace al admin
         if ($BC['option'] == 'index') {
             $path = "<strong>{$admin_label}</strong>";
         } else {
             $path = '<a href="/admin">' . $admin_label . '</a>' . $path;
         }
         return $path;
     }
 }
예제 #21
0
파일: promote.php 프로젝트: anvnguyen/Goteo
 public static function process($action = 'list', $id = null, $filters = array(), $flag = null)
 {
     $errors = array();
     $node = isset($_SESSION['admin_node']) ? $_SESSION['admin_node'] : \GOTEO_NODE;
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         // objeto
         $promo = new Model\Promote(array('id' => $id, 'node' => $node, 'project' => $_POST['project'], 'title' => $_POST['title'], 'description' => $_POST['description'], 'order' => $_POST['order'], 'active' => $_POST['active']));
         if ($promo->save($errors)) {
             switch ($_POST['action']) {
                 case 'add':
                     Message::Info('Proyecto destacado correctamente');
                     $projectData = Model\Project::getMini($_POST['project']);
                     if ($node == \GOTEO_NODE) {
                         // Evento Feed
                         $log = new Feed();
                         $log->setTarget($projectData->id);
                         $log->populate('nuevo proyecto destacado en portada (admin)', '/admin/promote', \vsprintf('El admin %s ha %s el proyecto %s', array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Destacado en portada', '/'), Feed::item('project', $projectData->name, $projectData->id))));
                         $log->doAdmin('admin');
                         unset($log);
                     }
                     break;
                 case 'edit':
                     Message::Info('Destacado actualizado correctamente');
                     break;
             }
             throw new Redirection('/admin/promote');
         } else {
             Message::Error(implode(', ', $errors));
             switch ($_POST['action']) {
                 case 'add':
                     return new View('view/admin/index.html.php', array('folder' => 'promote', 'file' => 'edit', 'action' => 'add', 'promo' => $promo));
                     break;
                 case 'edit':
                     return new View('view/admin/index.html.php', array('folder' => 'promote', 'file' => 'edit', 'action' => 'edit', 'promo' => $promo));
                     break;
             }
         }
     }
     switch ($action) {
         case 'active':
             $set = $flag == 'on' ? true : false;
             Model\Promote::setActive($id, $set);
             throw new Redirection('/admin/promote');
             break;
         case 'up':
             Model\Promote::up($id, $node);
             throw new Redirection('/admin/promote');
             break;
         case 'down':
             Model\Promote::down($id, $node);
             throw new Redirection('/admin/promote');
             break;
         case 'remove':
             if (Model\Promote::delete($id)) {
                 Message::Info('Destacado quitado correctamente');
             } else {
                 Message::Error('No se ha podido quitar el destacado');
             }
             throw new Redirection('/admin/promote');
             break;
         case 'add':
             // siguiente orden
             $next = Model\Promote::next($node);
             return new View('view/admin/index.html.php', array('folder' => 'promote', 'file' => 'edit', 'action' => 'add', 'promo' => (object) array('order' => $next, 'node' => $node)));
             break;
         case 'edit':
             $promo = Model\Promote::get($id);
             return new View('view/admin/index.html.php', array('folder' => 'promote', 'file' => 'edit', 'action' => 'edit', 'promo' => $promo));
             break;
     }
     $promoted = Model\Promote::getAll(false, $node);
     return new View('view/admin/index.html.php', array('folder' => 'promote', 'file' => 'list', 'promoted' => $promoted));
 }
예제 #22
0
 public function save(&$errors = array())
 {
     if (!$this->validate($errors)) {
         return false;
     }
     $fields = array('id', 'title', 'text', 'legend', 'media');
     $values = array();
     foreach ($fields as $field) {
         if ($set != '') {
             $set .= ", ";
         }
         $set .= "`{$field}` = :{$field} ";
         $values[":{$field}"] = $this->{$field};
     }
     try {
         $sql = "REPLACE INTO glossary SET " . $set;
         self::query($sql, $values);
         if (empty($this->id)) {
             $this->id = self::insertId();
         }
         // Luego la imagen
         if (!empty($this->id) && is_array($this->image) && !empty($this->image['name'])) {
             $image = new Image($this->image);
             if ($image->save($errors)) {
                 $this->gallery[] = $image;
                 /**
                  * Guarda la relación NM en la tabla 'glossary_image'.
                  */
                 if (!empty($image->id)) {
                     self::query("REPLACE glossary_image (glossary, image) VALUES (:glossary, :image)", array(':glossary' => $this->id, ':image' => $image->id));
                 }
             } else {
                 Message::Error(Text::get('image-upload-fail') . implode(', ', $errors));
             }
         }
         return true;
     } catch (\PDOException $e) {
         $errors[] = Text::_("No se ha guardado correctamente. ") . $e->getMessage();
         return false;
     }
 }
예제 #23
0
파일: newsletter.php 프로젝트: isbkch/Goteo
 public static function process($action = 'list', $id = null, $filters = array())
 {
     switch ($action) {
         case 'init':
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 // plantilla
                 $template = $_POST['template'];
                 // destinatarios
                 if ($_POST['test']) {
                     $users = Boletin::getTesters();
                 } elseif ($template == 33) {
                     // los destinatarios de newsletter
                     $users = Boletin::getReceivers();
                 } elseif ($template == 35) {
                     // los destinatarios para testear a subscriptores
                     $users = Boletin::getReceivers();
                 }
                 // sin idiomas
                 $nolang = $_POST['nolang'];
                 if ($nolang) {
                     $receivers[LANG] = $users;
                 } else {
                     // separamos destinatarios en idiomas
                     $receivers = array();
                     foreach ($users as $usr) {
                         if (empty($usr->lang) || $usr->lang == LANG) {
                             $receivers[LANG][] = $usr;
                         } else {
                             $receivers[$usr->lang][] = $usr;
                         }
                     }
                 }
                 // idiomas que vamos a enviar
                 $langs = array_keys($receivers);
                 // para cada idioma
                 foreach ($langs as $lang) {
                     // destinatarios
                     $recipients = $receivers[$lang];
                     // datos de la plantilla
                     $tpl = Template::get($template, $lang);
                     // contenido de newsletter
                     $content = $template == 33 ? Boletin::getContent($tpl->text, $lang) : ($content = $tpl->text);
                     // asunto
                     $subject = $tpl->title;
                     // creamos instancia
                     $sql = "INSERT INTO mail (id, email, html, template) VALUES ('', :email, :html, :template)";
                     $values = array(':email' => 'any', ':html' => $content, ':template' => $template);
                     $query = \Goteo\Core\Model::query($sql, $values);
                     $mailId = \Goteo\Core\Model::insertId();
                     // inicializamos el envío
                     if (Sender::initiateSending($mailId, $subject, $recipients, true)) {
                         // ok...
                     } else {
                         Message::Error('No se ha podido iniciar el mailing con asunto "' . $subject . '"');
                     }
                 }
             }
             throw new Redirection('/admin/newsletter');
             break;
         case 'activate':
             if (Sender::activateSending($id)) {
                 Message::Info('Se ha activado un nuevo envío automático');
             } else {
                 Message::Error('No se pudo activar el envío. Iniciar de nuevo');
             }
             throw new Redirection('/admin/newsletter');
             break;
         case 'detail':
             $mailing = Sender::getSending($id);
             $list = Sender::getDetail($id, $filters['show']);
             return new View('view/admin/index.html.php', array('folder' => 'newsletter', 'file' => 'detail', 'detail' => $filters['show'], 'mailing' => $mailing, 'list' => $list));
             break;
         default:
             $list = Sender::getMailings();
             return new View('view/admin/index.html.php', array('folder' => 'newsletter', 'file' => 'list', 'list' => $list));
     }
 }
예제 #24
0
파일: activity.php 프로젝트: kenjs/Goteo
 public static function donor($user)
 {
     // ver si es donante, cargando sus datos
     $donation = Model\User\Donor::get($user->id);
     $donation->dates = Model\User\Donor::getDates($donation->user, $donation->year);
     $donation->userData = Model\User::getMini($donation->user);
     if (!$donation || !$donation instanceof Model\User\Donor) {
         Message::Error(Text::get('dashboard-donor-no_donor'));
         throw new Redirection('/dashboard/activity');
     }
     if ($action == 'edit' && $donation->confirmed) {
         Message::Error(Text::get('dashboard-donor-confirmed'));
         throw new Redirection('/dashboard/activity/donor');
     }
     // si están guardando, actualizar los datos y guardar
     if ($action == 'save' && $_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['save'] == 'donation') {
         $donation->edited = 1;
         $donation->confirmed = 0;
         $donation->name = $_POST['name'];
         $donation->nif = $_POST['nif'];
         $donation->address = $_POST['address'];
         $donation->zipcode = $_POST['zipcode'];
         $donation->location = $_POST['location'];
         $donation->country = $_POST['country'];
         if ($donation->save()) {
             Message::Info(Text::get('dashboard-donor-saved'));
             throw new Redirection('/dashboard/activity/donor');
         } else {
             Message::Error(Text::get('dashboard-donor-save_fail'));
             throw new Redirection('/dashboard/activity/donor/edit');
         }
     }
     if ($action == 'confirm') {
         // marcamos que los datos estan confirmados
         Model\User\Donor::setConfirmed($user->id);
         Message::Info(Text::get('dashboard-donor-confirmed'));
         throw new Redirection('/dashboard/activity/donor');
     }
     if ($action == 'download') {
         // preparamos los datos para el pdf
         // generamos el pdf y lo mosteramos con la vista específica
         // estos pdf se guardan en /data/pdfs/donativos
         // el formato del archivo es: Ymd_nif_userid
         // se genera una vez, si ya está generado se abre directamente
         if (!empty($donation->pdf) && file_exists('data/pdfs/donativos/' . $donation->pdf)) {
             // forzar descarga
             header('Content-type: application/pdf');
             header("Content-disposition: attachment; filename={$donation->pdf}");
             header("Content-Transfer-Encoding: binary");
             echo file_get_contents('data/pdfs/donativos/' . $donation->pdf);
             die;
         } else {
             $objeto = new \Goteo\Library\Num2char($donation->amount, null);
             $donation->amount_char = $objeto->getLetra();
             $filename = "certificado_" . date('Ymd') . "_{$donation->nif}_{$donation->user}.pdf";
             $debug = false;
             if ($debug) {
                 header('Content-type: text/html');
             }
             require_once 'library/pdf.php';
             // Libreria pdf
             $pdf = donativeCert($donation);
             if ($debug) {
                 echo 'FIN';
                 echo '<hr><pre>' . print_r($pdf, 1) . '</pre>';
             } else {
                 $pdf->Output('data/pdfs/donativos/' . $filename, 'F');
                 $donation->setPdf($filename);
                 //                            throw new Redirection('/dashboard/activity/donor/download/'.$donation->pdf);
                 header('Content-type: application/pdf');
                 header("Content-disposition: attachment; filename={$donation->pdf}");
                 header("Content-Transfer-Encoding: binary");
                 echo $pdf->Output('', 'S');
                 die;
             }
         }
     }
     // fin action download
     return $donation;
 }
예제 #25
0
 private function view($id, $show, $post = null)
 {
     $project = Model\Project::get($id, LANG);
     // recompensas
     foreach ($project->individual_rewards as &$reward) {
         $reward->none = false;
         $reward->taken = $reward->getTaken();
         // cofinanciadores quehan optado por esta recompensas
         // si controla unidades de esta recompensa, mirar si quedan
         if ($reward->units > 0 && $reward->taken >= $reward->units) {
             $reward->none = true;
         }
     }
     // mensaje cuando, sin estar en campaña, tiene fecha de publicación, es que la campaña ha sido cancelada
     if ($project->status < 3 && !empty($project->published)) {
         Message::Info(Text::get('project-unpublished'));
     } elseif ($project->status < 3) {
         // mensaje de no publicado siempre que no esté en campaña
         Message::Info(Text::get('project-not_published'));
     }
     // solamente se puede ver publicamente si...
     $grant = false;
     if ($project->status > 2) {
         // está publicado
         $grant = true;
     } elseif ($project->owner == $_SESSION['user']->id) {
         // es el dueño
         $grant = true;
     } elseif (ACL::check('/project/edit/todos')) {
         // es un admin
         $grant = true;
     } elseif (ACL::check('/project/view/todos')) {
         // es un usuario con permiso
         $grant = true;
     } elseif (isset($_SESSION['user']->roles['checker']) && Model\User\Review::is_assigned($_SESSION['user']->id, $project->id)) {
         // es un revisor y lo tiene asignado
         $grant = true;
     }
     // (Callsys)
     // si lo puede ver
     if ($grant) {
         $viewData = array('project' => $project, 'show' => $show);
         // sus entradas de novedades
         $blog = Model\Blog::get($project->id);
         // si está en modo preview, ponemos  todas las entradas, incluso las no publicadas
         if (isset($_GET['preview']) && $_GET['preview'] == $_SESSION['user']->id) {
             $blog->posts = Model\Blog\Post::getAll($blog->id, null, false);
         }
         $viewData['blog'] = $blog;
         // tenemos que tocar esto un poquito para motrar las necesitades no economicas
         if ($show == 'needs-non') {
             $viewData['show'] = 'needs';
             $viewData['non-economic'] = true;
         }
         // -- Mensaje azul molesto para usuarios no registrados
         if (($show == 'messages' || $show == 'updates') && empty($_SESSION['user'])) {
             Message::Info(Text::html('user-login-required'));
         }
         //tenemos que tocar esto un poquito para gestionar los pasos al aportar
         if ($show == 'invest') {
             // si no está en campaña no pueden estar aqui ni de coña
             if ($project->status != 3) {
                 Message::Info(Text::get('project-invest-closed'));
                 throw new Redirection('/project/' . $id, Redirection::TEMPORARY);
             }
             $viewData['show'] = 'supporters';
             /* pasos de proceso aporte
              *
              * 1, 'start': ver y seleccionar recompensa (y cantidad)
              * 2, 'login': loguear con usuario/contraseña o con email (que crea el usuario automáticamente)
              * 3, 'confirm': confirmar los datos y saltar a la pasarela de pago
              * 4, 'ok'/'fail': al volver de la pasarela de pago, la confirmación nos dice si todo bien o algo mal
              * 5, 'continue': recuperar aporte incompleto (variante de confirm)
              */
             // usamos la variable de url $post para movernos entre los pasos
             $step = isset($post) && in_array($post, array('start', 'login', 'confirm', 'continue')) ? $post : 'start';
             // si llega confirm ya ha terminado el proceso de aporte
             if (isset($_GET['confirm']) && \in_array($_GET['confirm'], array('ok', 'fail'))) {
                 unset($_SESSION['invest-amount']);
                 // confirmación
                 $step = $_GET['confirm'];
             } else {
                 // si no, a ver en que paso estamos
                 if (isset($_GET['amount'])) {
                     $_SESSION['invest-amount'] = $_GET['amount'];
                 }
                 // si el usuario está validado, recuperamos posible amount y mostramos
                 if ($_SESSION['user'] instanceof Model\User) {
                     $step = 'confirm';
                 } elseif ($step != 'start' && empty($_SESSION['user'])) {
                     // si no está validado solo puede estar en start
                     Message::Info(Text::get('user-login-required-to_invest'));
                     $step = 'start';
                 } elseif ($step == 'start') {
                     // para cuando salte
                     $_SESSION['jumpto'] = SEC_URL . '/project/' . $id . '/invest/#continue';
                 } else {
                     $step = 'start';
                 }
             }
             $viewData['step'] = $step;
         }
         if ($show == 'updates') {
             $viewData['post'] = $post;
             $viewData['owner'] = $project->owner;
         }
         if ($show == 'messages' && $project->status < 3) {
             Message::Info(Text::get('project-messages-closed'));
         }
         return new View('view/project/view.html.php', $viewData);
     } else {
         // no lo puede ver
         throw new Redirection("/");
     }
 }
예제 #26
0
파일: translate.php 프로젝트: kenjs/Goteo
 public function index($table = '', $action = 'list', $id = null, $auxAction = 'list', $contentId = null)
 {
     $_SESSION['user']->translangs = Model\User\Translate::getLangs($_SESSION['user']->id);
     if (empty($_SESSION['user']->translangs)) {
         Message::Error(Text::_('No tienes ningún idioma, contacta con el administrador'));
         throw new Redirection('/dashboard');
     }
     if (empty($_SESSION['translate_lang']) || !isset($_SESSION['user']->translangs[$_SESSION['translate_lang']])) {
         if (count($_SESSION['user']->translangs) > 1 && isset($_SESSION['user']->translangs['en'])) {
             $_SESSION['translate_lang'] = 'en';
         } else {
             $_SESSION['translate_lang'] = current(array_keys($_SESSION['user']->translangs));
         }
     }
     if ($table == '') {
         return new View('view/translate/index.html.php', array('menu' => self::menu()));
     }
     // para el breadcrumbs segun el contenido
     $section = $table == 'news' || $table == 'promote' ? 'home' : 'contents';
     // muy especial para traducción de nodo
     if ($table == 'node') {
         $BC = self::menu(array('section' => 'node', 'node' => $action, 'option' => $id, 'action' => $auxAction, 'id' => $contentId));
     } else {
         $BC = self::menu(array('section' => $section, 'option' => $table, 'action' => $action, 'id' => $id));
     }
     define('ADMIN_BCPATH', $BC);
     $errors = array();
     // la operación según acción
     switch ($table) {
         case 'texts':
             // comprobamos los filtros
             $filters = array();
             $fields = array('group', 'text', 'pending');
             if (!isset($_GET['pending'])) {
                 $_GET['pending'] = 0;
             }
             foreach ($fields as $field) {
                 if (isset($_GET[$field])) {
                     $filters[$field] = $_GET[$field];
                     $_SESSION['translate_filters']['texts'][$field] = (string) $_GET[$field];
                 } elseif (!empty($_SESSION['translate_filters']['texts'][$field])) {
                     // si no lo tenemos en el get, cogemos de la sesion pero no lo pisamos
                     $filters[$field] = $_SESSION['translate_filters']['texts'][$field];
                 }
             }
             $filter = "?group={$filters['group']}&text={$filters['text']}&pending={$filters['pending']}";
             // si llega post, vamos a guardar los cambios
             if ($action == 'edit' && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save'])) {
                 if (Text::save(array('id' => $id, 'text' => $_POST['text'], 'lang' => $_POST['lang']), $errors)) {
                     // Evento Feed
                     /*
                     $log = new Feed();
                     $log->populate('texto traducido (traductor)', '/translate/texts',
                         \vsprintf('El traductor %s ha %s el texto %s al %s', array(
                             Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id),
                             Feed::item('relevant', 'Traducido'),
                             Feed::item('blog', $id),
                             Feed::item('relevant', Lang::get($_POST['lang'])->name)
                     )));
                     $log->doAdmin('admin');
                     unset($log);
                     */
                     Message::Info('Texto <strong>' . $id . '</strong> traducido correctamente al <strong>' . Lang::get($_POST['lang'])->name . '</strong>');
                     throw new Redirection("/translate/texts/{$filter}&page=" . $_GET['page']);
                 } else {
                     // Evento Feed
                     $log = new Feed();
                     $log->setTarget($_SESSION['user']->id, 'user');
                     $log->populate('texto traducido (traductor)', '/translate/texts', \vsprintf('Al traductor %s  le ha %s el texto %s al %s', array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Fallado al traducir'), Feed::item('blog', $id), Feed::item('relevant', Lang::get($_POST['lang'])->name))));
                     $log->doAdmin('admin');
                     unset($log);
                     Message::Error('Ha habido algun ERROR al traducir el Texto <strong>' . $id . '</strong> al <strong>' . Lang::get($_POST['lang'])->name . '</strong><br />' . implode('<br />', $errors));
                 }
             }
             // sino, mostramos la lista
             return new View('view/translate/index.html.php', array('section' => 'texts', 'action' => $action, 'id' => $id, 'filter' => $filter, 'filters' => $filters, 'errors' => $errors));
             break;
         case 'node':
             // parametros especiales
             $node = $action;
             $action = $auxAction;
             $contentTable = $id;
             // si llega post, vamos a guardar los cambios
             if ($action == 'edit' && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save'])) {
                 switch ($contentTable) {
                     case 'banner':
                         if (Content::save(array('id' => $contentId, 'table' => $contentTable, 'title' => $_POST['title'], 'description' => $_POST['description'], 'lang' => $_POST['lang']), $errors)) {
                             Message::Info('El Banner <strong>' . $contentId . '</strong> del nodo <strong>' . $node . '</strong> traducido correctamente al <strong>' . Lang::get($_POST['lang'])->name . '</strong>');
                             throw new Redirection("/translate/node/{$node}/{$contentTable}/list");
                         } else {
                             Message::Error('Ha habido algun ERROR al traducir el Banner <strong>' . $contentId . '</strong> del nodo <strong>' . $node . '</strong> al <strong>' . Lang::get($_POST['lang'])->name . '</strong><br />' . implode('<br />', $errors));
                         }
                         break;
                     case 'page':
                         $page = Page::get($contentId, $node);
                         if ($page->update($contentId, $_POST['lang'], $node, $_POST['name'], $_POST['description'], $_POST['content'], $errors)) {
                             Message::Info('La página <strong>' . $contentId . '</strong> del nodo <strong>' . $node . '</strong> traducido correctamente al <strong>' . Lang::get($_POST['lang'])->name . '</strong>');
                             throw new Redirection("/translate/node/{$node}/{$contentTable}/list");
                         } else {
                             Message::Error('Ha habido algun ERROR al traducir la página <strong>' . $contentId . '</strong> del nodo <strong>' . $node . '</strong> al <strong>' . Lang::get($_POST['lang'])->name . '</strong><br />' . implode('<br />', $errors));
                         }
                         break;
                     case 'post':
                         if (Content::save(array('id' => $contentId, 'table' => $contentTable, 'title' => $_POST['title'], 'text' => $_POST['text'], 'legend' => $_POST['legend'], 'lang' => $_POST['lang']), $errors)) {
                             Message::Info('La entrada <strong>' . $contentId . '</strong> del nodo <strong>' . $node . '</strong> traducido correctamente al <strong>' . Lang::get($_POST['lang'])->name . '</strong>');
                             throw new Redirection("/translate/node/{$node}/{$contentTable}/list");
                         } else {
                             Message::Error('Ha habido algun ERROR al traducir la Entrada <strong>' . $contentId . '</strong> del nodo <strong>' . $node . '</strong> al <strong>' . Lang::get($_POST['lang'])->name . '</strong><br />' . implode('<br />', $errors));
                         }
                         break;
                     default:
                         $node = Model\Node::get($node);
                         $node->lang_lang = $_SESSION['translate_lang'];
                         $node->subtitle_lang = $_POST['subtitle'];
                         $node->description_lang = $_POST['description'];
                         if ($node->updateLang($errors)) {
                             Message::Info('La Descripción del nodo <strong>' . $node->id . '</strong> traducido correctamente al <strong>' . Lang::get($_POST['lang'])->name . '</strong>');
                             throw new Redirection("/translate/node/{$node->id}");
                         } else {
                             Message::Error('Ha habido algun ERROR al traducir la Descripción del nodo <strong>' . $node->id . '</strong> al <strong>' . Lang::get($_POST['lang'])->name . '</strong><br />' . implode('<br />', $errors));
                         }
                 }
                 return new View('view/translate/index.html.php', array('section' => 'node', 'action' => 'edit_' . $contentTable, 'option' => $contentTable, 'id' => $contentId, 'node' => $node));
             } elseif ($action == 'edit') {
                 return new View('view/translate/index.html.php', array('section' => 'node', 'action' => 'edit_' . $contentTable, 'option' => $contentTable, 'id' => $contentId, 'node' => $node));
             } elseif ($contentTable == 'data') {
                 return new View('view/translate/index.html.php', array('section' => 'node', 'action' => 'edit_' . $contentTable, 'option' => $contentTable, 'id' => $node, 'node' => $node));
             } else {
                 // sino, mostramos la lista
                 return new View('view/translate/index.html.php', array('section' => 'node', 'action' => 'list_' . $contentTable, 'option' => $contentTable, 'node' => $node));
             }
             break;
         case 'pages':
             // si llega post, vamos a guardar los cambios
             if ($action == 'edit' && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save'])) {
                 if (Page::update($id, $_POST['lang'], $_POST['node'], $_POST['name'], $_POST['description'], $_POST['content'], $errors)) {
                     Message::Info('Contenido de la Pagina <strong>' . $id . '</strong> traducido correctamente al <strong>' . Lang::get($_POST['lang'])->name . '</strong>');
                     throw new Redirection("/translate/pages");
                 } else {
                     // Evento Feed
                     $log = new Feed();
                     $log->setTarget($_SESSION['user']->id, 'user');
                     $log->populate('pagina traducida (traductor)', '/translate/pages', \vsprintf('Al traductor %s le ha %s la página %s del nodo %s al %s', array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Fallado al traducir'), Feed::item('blog', $id), Feed::item('blog', $_POST['node']), Feed::item('relevant', Lang::get($_POST['lang'])->name))));
                     $log->doAdmin('admin');
                     unset($log);
                     Message::Error('Ha habido algun ERROR al traducir el contenido de la pagina <strong>' . $id . '</strong> al <strong>' . Lang::get($_POST['lang'])->name . '</strong><br />' . implode('<br />', $errors));
                 }
             }
             // sino, mostramos la lista
             return new View('view/translate/index.html.php', array('section' => 'pages', 'action' => $action, 'id' => $id, 'errors' => $errors));
             break;
         default:
             // comprobamos los filtros
             $filters = array();
             $fields = array('type', 'text', 'pending');
             if (!isset($_GET['pending'])) {
                 $_GET['pending'] = 0;
             }
             foreach ($fields as $field) {
                 if (isset($_GET[$field])) {
                     $filters[$field] = $_GET[$field];
                     $_SESSION['translate_filters']['contents'][$field] = (string) $_GET[$field];
                 } elseif (!empty($_SESSION['translate_filters']['contents'][$field])) {
                     // si no lo tenemos en el get, cogemos de la sesion pero no lo pisamos
                     $filters[$field] = $_SESSION['translate_filters']['contents'][$field];
                 }
             }
             $filter = "?type={$filters['type']}&text={$filters['text']}&pending={$filters['pending']}";
             // si llega post, vamos a guardar los cambios
             if ($action == 'edit' && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save'])) {
                 if (!in_array($table, \array_keys(Content::_tables()))) {
                     $errors[] = Text::_("Tabla ") . $table . Text::_(" desconocida");
                     break;
                 }
                 if (Content::save($_POST, $errors)) {
                     // Evento Feed
                     /*
                     $log = new Feed();
                     $log->populate('contenido traducido (traductor)', '/translate/'.$table,
                         \vsprintf('El traductor %s ha %s el contenido del registro %s de la tabla %s al %s', array(
                         Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id),
                         Feed::item('relevant', 'Traducido'),
                         Feed::item('blog', $id),
                         Feed::item('blog', $table),
                         Feed::item('relevant', Lang::get($_SESSION['translate_lang'])->name)
                     )));
                     $log->doAdmin('admin');
                     unset($log);
                     */
                     Message::Info('Contenido del registro <strong>' . $id . '</strong> de la tabla <strong>' . $table . '</strong> traducido correctamente al <strong>' . Lang::get($_POST['lang'])->name . '</strong>');
                     if (isset($_SESSION['translate_node'])) {
                         throw new Redirection('/dashboard/translates/' . $table . 's');
                     }
                     throw new Redirection("/translate/{$table}/{$filter}&page=" . $_GET['page']);
                 } else {
                     // Evento Feed
                     $log = new Feed();
                     $log->setTarget($_SESSION['user']->id, 'user');
                     $log->populate('contenido traducido (traductor)', '/translate/' . $table, \vsprintf('El traductor %s le ha %s el contenido del registro %s de la tabla %s al %s', array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Fallado al traducir'), Feed::item('blog', $id), Feed::item('blog', $table), Feed::item('relevant', Lang::get($_SESSION['translate_lang'])->name))));
                     $log->doAdmin('admin');
                     unset($log);
                     Message::Error('Ha habido algun ERROR al traducir el contenido del registro <strong>' . $id . '</strong> de la tabla <strong>' . $table . '</strong> al <strong>' . Lang::get($_POST['lang'])->name . '</strong><br />' . implode('<br />', $errors));
                 }
             }
             // sino, mostramos la lista
             return new View('view/translate/index.html.php', array('section' => 'contents', 'action' => $action, 'table' => $table, 'id' => $id, 'filter' => $filter, 'filters' => $filters, 'errors' => $errors));
     }
     // si no pasa nada de esto, a la portada
     return new View('view/translate/index.html.php', array('menu' => self::menu()));
 }
예제 #27
0
파일: glossary.php 프로젝트: isbkch/Goteo
 public static function process($action = 'list', $id = null)
 {
     $errors = array();
     $url = '/admin/glossary';
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         $editing = false;
         if (!empty($_POST['id'])) {
             $post = Model\Glossary::get($_POST['id']);
         } else {
             $post = new Model\Glossary();
         }
         // campos que actualizamos
         $fields = array('id', 'title', 'text', 'media', 'legend');
         foreach ($fields as $field) {
             $post->{$field} = $_POST[$field];
         }
         // tratar la imagen y ponerla en la propiedad image
         if (!empty($_FILES['image_upload']['name'])) {
             $post->image = $_FILES['image_upload'];
             $editing = true;
         }
         // tratar las imagenes que quitan
         foreach ($post->gallery as $key => $image) {
             if (!empty($_POST["gallery-{$image->id}-remove"])) {
                 $image->remove('glossary');
                 unset($post->gallery[$key]);
                 if ($post->image == $image->id) {
                     $post->image = '';
                 }
                 $editing = true;
             }
         }
         if (!empty($post->media)) {
             $post->media = new Model\Project\Media($post->media);
         }
         /// este es el único save que se lanza desde un metodo process_
         if ($post->save($errors)) {
             if ($action == 'edit') {
                 Message::Info('El término se ha actualizado correctamente');
             } else {
                 Message::Info('Se ha añadido un nuevo término');
                 $id = $post->id;
             }
             $action = $editing ? 'edit' : 'list';
         } else {
             Message::Error(implode('<br />', $errors));
             Message::Error('Ha habido algun problema al guardar los datos');
         }
     }
     switch ($action) {
         case 'remove':
             // eliminar un término
             if (Model\Glossary::delete($id)) {
                 Message::Info('Término eliminado');
             } else {
                 Message::Error('No se ha podido eliminar el término');
             }
             break;
         case 'add':
             // nueva entrada con wisiwig
             // obtenemos datos basicos
             $post = new Model\Glossary();
             $message = 'Añadiendo un nuevo término';
             return new View('view/admin/index.html.php', array('folder' => 'glossary', 'file' => 'edit', 'action' => 'add', 'post' => $post, 'message' => $message));
             break;
         case 'edit':
             if (empty($id)) {
                 throw new Redirection('/admin/glossary');
                 break;
             } else {
                 $post = Model\Glossary::get($id);
                 if (!$post instanceof Model\Glossary) {
                     Message::Error('La entrada esta corrupta, contacte con nosotros.');
                     $action = 'list';
                     break;
                 }
             }
             $message = 'Editando un término existente';
             return new View('view/admin/index.html.php', array('folder' => 'glossary', 'file' => 'edit', 'action' => 'edit', 'post' => $post, 'message' => $message));
             break;
     }
     // lista de términos
     $posts = Model\Glossary::getAll();
     return new View('view/admin/index.html.php', array('folder' => 'glossary', 'file' => 'list', 'posts' => $posts));
 }
예제 #28
0
파일: user.php 프로젝트: isbkch/Goteo
 /**
  * Validación de usuario.
  *
  * @param string $username Nombre de usuario
  * @param string $password Contraseña
  * @return obj|false Objeto del usuario, en caso contrario devolverá 'false'.
  */
 public static function login($username, $password)
 {
     $ok = false;
     $query = self::query("\r\n                    SELECT\r\n                        password\r\n                    FROM user\r\n                    WHERE BINARY id = :username", array(':username' => trim($username)));
     if ($row = $query->fetch(\PDO::FETCH_OBJ)) {
         if (version_compare(phpversion(), '5.5.0', '>=')) {
             $ok = password_verify($password, $row->password);
         } else {
             $ok = crypt($password, $row->password) == $row->password;
         }
         if ($ok) {
             $user = static::get(trim($username));
             if (empty($user) || $user->active) {
                 return $user;
             } else {
                 Message::Error(Text::get('user-account-inactive'));
             }
         } else {
             return false;
         }
     }
     return false;
 }
예제 #29
0
파일: users.php 프로젝트: anvnguyen/Goteo
 public static function process($action = 'list', $id = null, $filters = array(), $subaction = '')
 {
     // @NODESYS
     $nodes = array();
     // @NODESYS
     $node = \GOTEO_NODE;
     $errors = array();
     switch ($action) {
         case 'add':
             // si llega post: creamos
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 // para crear se usa el mismo método save del modelo, hay que montar el objeto
                 $user = new Model\User();
                 $user->userid = $_POST['userid'];
                 $user->name = $_POST['name'];
                 $user->email = $_POST['email'];
                 $user->password = $_POST['password'];
                 $user->node = !empty($_POST['node']) ? $_POST['node'] : \GOTEO_NODE;
                 if (isset($_SESSION['admin_node']) && $user->node != $_SESSION['admin_node']) {
                     $user->node = $_SESSION['admin_node'];
                 }
                 $user->save($errors);
                 if (empty($errors)) {
                     // mensaje de ok y volvemos a la lista de usuarios
                     Message::Info(Text::get('user-register-success'));
                     throw new Redirection('/admin/users/manage/' . $user->id);
                 } else {
                     // si hay algun error volvemos a poner los datos en el formulario
                     $data = $_POST;
                     Message::Error(implode('<br />', $errors));
                 }
             }
             // vista de crear usuario
             return new View('view/admin/index.html.php', array('folder' => 'users', 'file' => 'add', 'data' => $data, 'nodes' => $nodes));
             break;
         case 'edit':
             $user = Model\User::get($id);
             // si llega post: actualizamos
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 $tocado = array();
                 // para crear se usa el mismo método save del modelo, hay que montar el objeto
                 if (!empty($_POST['email'])) {
                     $user->email = $_POST['email'];
                     $tocado[] = Text::_('el email');
                 }
                 if (!empty($_POST['password'])) {
                     $user->password = $_POST['password'];
                     $tocado[] = Text::_('la contraseña');
                 }
                 if (!empty($tocado) && $user->update($errors)) {
                     // Evento Feed
                     $log = new Feed();
                     $log->setTarget($user->id, 'user');
                     $log->populate(Text::_('Operación sobre usuario'), '/admin/users', \vsprintf('El admin %s ha %s del usuario %s', array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Tocado ' . implode(' y ', $tocado)), Feed::item('user', $user->name, $user->id))));
                     $log->doAdmin('user');
                     unset($log);
                     // mensaje de ok y volvemos a la lista de usuarios
                     Message::Info(Text::_('Datos actualizados'));
                     throw new Redirection('/admin/users');
                 } else {
                     // si hay algun error volvemos a poner los datos en el formulario
                     $data = $_POST;
                     Message::Error(Text::_('No se ha guardado correctamente. ') . implode('<br />', $errors));
                 }
             }
             // vista de editar usuario
             return new View('view/admin/index.html.php', array('folder' => 'users', 'file' => 'edit', 'user' => $user, 'data' => $data, 'nodes' => $nodes));
             break;
         case 'manage':
             // si llega post: ejecutamos + mensaje + seguimos editando
             // operación y acción para el feed
             $mngSa = static::_manageSubAct();
             $sql = $mngSa[$subaction]['sql'];
             $log_action = $mngSa[$subaction]['log'];
             if (!empty($sql)) {
                 $user = Model\User::getMini($id);
                 if (Model\User::query($sql, array(':user' => $id))) {
                     // mensaje de ok y volvemos a la gestion del usuario
                     //                            Message::Info('Ha <strong>' . $log_action . '</strong> al usuario <strong>'.$user->name.'</strong> CORRECTAMENTE');
                     $log_text = 'El admin %s ha %s al usuario %s';
                     // procesos adicionales
                     switch ($subaction) {
                         case 'admin':
                         case 'noadmin':
                             // @NODESYS : this admin/noadmin subactions are here for NODESYS module extra
                             break;
                         case 'translator':
                             // le ponemos todos los idiomas (excepto el español)
                             $sql = "INSERT INTO user_translang (user, lang) SELECT '{$id}' as user, id as lang FROM `lang` WHERE id != 'es'";
                             Model\User::query($sql);
                             break;
                         case 'notranslator':
                             // quitamos los idiomas
                             $sql = "DELETE FROM user_translang WHERE user = :user";
                             Model\User::query($sql, array(':user' => $id));
                             break;
                     }
                 } else {
                     // mensaje de error y volvemos a la gestion del usuario
                     Message::Error('Ha FALLADO cuando ha <strong>' . $log_action . '</strong> al usuario <strong>' . $id . '</strong>');
                     $log_text = 'Al admin %s le ha <strong>FALLADO</strong> cuando ha %s al usuario %s';
                 }
                 // Evento Feed
                 $log = new Feed();
                 $log->setTarget($user->id, 'user');
                 $log->populate(Text::_('Operación sobre usuario'), '/admin/users', \vsprintf($log_text, array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', $log_action), Feed::item('user', $user->name, $user->id))));
                 $log->doAdmin('user');
                 unset($log);
                 throw new Redirection('/admin/users/manage/' . $id);
             }
             $user = Model\User::get($id);
             $viewData = array('folder' => 'users', 'file' => 'manage', 'user' => $user, 'nodes' => $nodes);
             $viewData['roles'] = Model\User::getRolesList();
             $viewData['langs'] = Lang::getAll();
             // quitamos el español
             unset($viewData['langs']['es']);
             // vista de gestión de usuario
             return new View('view/admin/index.html.php', $viewData);
             break;
             // aplicar idiomas
         // aplicar idiomas
         case 'translang':
             if (!isset($_POST['user'])) {
                 Message::Error(Text::_('Hemos perdido de vista al usuario'));
                 throw new Redirection('/admin/users');
             } else {
                 $user = $_POST['user'];
             }
             $sql = "DELETE FROM user_translang WHERE user = :user";
             Model\User::query($sql, array(':user' => $user));
             $anylang = false;
             foreach ($_POST as $key => $value) {
                 if (\substr($key, 0, \strlen('lang_')) == 'lang_') {
                     $sql = "INSERT INTO user_translang (user, lang) VALUES (:user, :lang)";
                     if (Model\User::query($sql, array(':user' => $user, ':lang' => $value))) {
                         $anylang = true;
                     }
                 }
             }
             if (!$anylang) {
                 Message::Error(Text::_('No se ha seleccionado ningún idioma, este usuario tendrá problemas en su panel de traducción!'));
             } else {
                 Message::Info(Text::_('Se han aplicado al traductor los idiomas seleccionados'));
             }
             throw new Redirection('/admin/users/manage/' . $user);
             break;
         case 'impersonate':
             $user = Model\User::get($id);
             // vista de acceso a suplantación de usuario
             return new View('view/admin/index.html.php', array('folder' => 'users', 'file' => 'impersonate', 'user' => $user, 'nodes' => $nodes));
             break;
         case 'move':
             $user = Model\User::get($id);
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 $values = array(':id' => $id, ':node' => $_POST['node']);
                 try {
                     $sql = "UPDATE user SET node = :node WHERE id = :id";
                     if (Model\User::query($sql, $values)) {
                         $log_text = 'El admin %s ha <span class="red">movido</span> el usuario %s al nodo %s';
                     } else {
                         $log_text = 'Al admin %s le ha <span class="red">fallado al mover</span> el usuario %s al nodo %s';
                     }
                     // Evento Feed
                     $log = new Feed();
                     $log->setTarget($user->id, 'user');
                     $log->populate('User cambiado de nodo (admin)', '/admin/users', \vsprintf($log_text, array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('user', $user->name, $user->id), Feed::item('user', $nodes[$_POST['node']]))));
                     Message::Error($log->html);
                     $log->doAdmin('user');
                     unset($log);
                     throw new Redirection('/admin/users');
                 } catch (\PDOException $e) {
                     Message::Error("Ha fallado! " . $e->getMessage());
                 }
             }
             // vista de acceso a suplantación de usuario
             return new View('view/admin/index.html.php', array('folder' => 'users', 'file' => 'move', 'user' => $user, 'nodes' => $nodes));
             break;
         case 'list':
         default:
             if (!empty($filters['filtered'])) {
                 $users = Model\User::getAll($filters, $node);
             } else {
                 $users = array();
             }
             $status = array('active' => Text::_('Activo'), 'inactive' => Text::_('Inactivo'));
             $interests = Model\User\Interest::getAll();
             $roles = Model\User::getRolesList();
             $roles['user'] = Text::_('Solo usuario');
             $types = array('creators' => Text::_('Impulsores'), 'investors' => Text::_('Cofinanciadores'), 'supporters' => Text::_('Colaboradores'));
             $orders = array('created' => Text::_('Fecha de alta'), 'name' => Text::_('Alias'), 'id' => Text::_('User'), 'amount' => Text::_('Cantidad'), 'projects' => Text::_('Proyectos'));
             // proyectos con aportes válidos
             $projects = Model\Invest::projects(true, $node);
             return new View('view/admin/index.html.php', array('folder' => 'users', 'file' => 'list', 'users' => $users, 'filters' => $filters, 'status' => $status, 'interests' => $interests, 'roles' => $roles, 'types' => $types, 'nodes' => $nodes, 'projects' => $projects, 'orders' => $orders));
             break;
     }
 }
예제 #30
0
파일: user.php 프로젝트: anvnguyen/Goteo
 /**
  * Darse de baja
  * - Si no llega nada, mostrar formulario para que pongan el email de su cuenta
  * - Si llega post es una peticion, comprobar que el email que han puesto es válido
  *      si no es, dejarlos en el formulario y mensaje de error
  *      si es válido, enviar email con la url y mensaje de ok
  *
  * - Si llega un hash, verificar y dar de baja la cuenta (desactivar y ocultar)
  *
  * @param string $token     Codigo
  */
 public function leave($token = null)
 {
     // si el token mola, lo doy de baja
     if (!empty($token)) {
         $token = base64_decode($token);
         $parts = explode('¬', $token);
         if (count($parts) > 1) {
             $query = Model\User::query('SELECT id FROM user WHERE email = ? AND token = ?', array($parts[1], $token));
             if ($id = $query->fetchColumn()) {
                 if (!empty($id)) {
                     // el token coincide con el email y he obtenido una id
                     if (Model\User::cancel($id)) {
                         Message::Info(Text::get('leave-process-completed'));
                         throw new Redirection(SEC_URL . '/user/login');
                     } else {
                         Message::Error(Text::get('leave-process-fail'));
                         throw new Redirection(SEC_URL . '/user/login');
                     }
                 }
             }
         }
         $error = Text::get('leave-token-incorrect');
     }
     if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['leaving'])) {
         if (Model\User::leaving($_POST['email'], $_POST['reason'])) {
             $message = Text::get('leave-email-sended');
             unset($_POST['email']);
             unset($_POST['reason']);
         } else {
             $error = Text::get('leave-request-fail');
         }
     }
     return new View('view/user/leave.html.php', array('error' => $error, 'message' => $message));
 }