Beispiel #1
0
 public static function check($url = \GOTEO_REQUEST_URI, $user = null, $node = \GOTEO_NODE)
 {
     $url = static::fixURL($url);
     if (is_null($user)) {
         if (!User::isLogged()) {
             // @FIXME: Ajuste para permitir un perfil público sin usuario registrado.
             // (Es provisional hasta que se decida lo contrario)
             $user = new User();
             $user->id = '*';
             $user->roles = array((object) array('id' => 'public', 'name' => 'Perfil público'));
             $id = $user->id;
         } else {
             $user = $_SESSION['user'];
             $id = $user->id;
         }
     } elseif ($user instanceof User) {
         $id = $user->id;
     } else {
         if ($user = Model\User::get($user)) {
             $id = $user->id;
         }
     }
     $roles = $user->roles;
     array_walk($roles, function (&$role) {
         $role = $role->id;
     });
     $query = Model::query("\r\n                SELECT\r\n                    acl.allow\r\n                FROM acl\r\n                WHERE (:node LIKE REPLACE(acl.node_id, '*', '%'))\r\n                AND (:roles REGEXP REPLACE(acl.role_id, '*', '.'))\r\n                AND (:user LIKE REPLACE(acl.user_id, '*', '%'))\r\n                AND (:url LIKE REPLACE(acl.url, '*', '%'))\r\n                ORDER BY acl.id DESC\r\n                LIMIT 1\r\n                ", array(':node' => $node, ':roles' => implode(', ', $roles), ':user' => $id, ':url' => $url));
     return (bool) $query->fetchColumn();
 }
Beispiel #2
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');
     }
 }
Beispiel #3
0
 public static function getList($blog, $limit = null)
 {
     $list = array();
     $sql = "\n                SELECT\n                    comment.id,\n                    comment.post,\n                    DATE_FORMAT(comment.date, '%d | %m | %Y') as date,\n                    comment.text,\n                    comment.user\n                FROM    comment\n                INNER JOIN user\n                    ON  user.id = comment.user\n                    AND (user.hide = 0 OR user.hide IS NULL)\n                WHERE comment.post IN (SELECT id FROM post WHERE blog = ?)\n                ORDER BY comment.date DESC, comment.id DESC\n                ";
     if (!empty($limit)) {
         $sql .= "LIMIT {$limit}";
     }
     $query = static::query($sql, array($blog));
     foreach ($query->fetchAll(\PDO::FETCH_CLASS, __CLASS__) as $comment) {
         $comment->user = \Goteo\Model\User::getMini($comment->user);
         // reconocimiento de enlaces y saltos de linea
         $comment->text = nl2br(Text::urlink($comment->text));
         $list[$comment->id] = $comment;
     }
     return $list;
 }
Beispiel #4
0
 public static function process($action = 'list', $id = null, $filters = array())
 {
     $node = isset($_SESSION['admin_node']) ? $_SESSION['admin_node'] : \GOTEO_NODE;
     // métodos de pago
     $methods = Model\Invest::methods();
     // estados del proyecto
     $status = Model\Project::status();
     // estados de aporte
     $investStatus = Model\Invest::status();
     // listado de proyectos
     $projects = Model\Invest::projects(false, $node);
     // 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');
     // detalles del aporte
     if ($action == 'details') {
         $invest = Model\Invest::get($id);
         $project = Model\Project::get($invest->project);
         $userData = Model\User::get($invest->user);
         if (!empty($invest->droped)) {
             $droped = Model\Invest::get($invest->droped);
         } else {
             $droped = null;
         }
         if ($project->node != $node) {
             throw new Redirection('/admin/invests');
         }
         return new View('view/admin/index.html.php', array('folder' => 'invests', 'file' => 'details', 'invest' => $invest, 'project' => $project, 'user' => $userData, 'status' => $status, 'investStatus' => $investStatus, 'droped' => $droped, 'calls' => $calls));
     }
     // listado de aportes
     if ($filters['filtered'] == 'yes') {
         if (!empty($filters['calls'])) {
             $filters['types'] = '';
         }
         $list = Model\Invest::getList($filters, $node, 999);
     } else {
         $list = array();
     }
     $viewData = array('folder' => 'invests', 'file' => 'list', 'list' => $list, 'filters' => $filters, 'projects' => $projects, 'users' => $users, 'calls' => $calls, 'methods' => $methods, 'types' => $types, 'investStatus' => $investStatus);
     return new View('view/admin/index.html.php', $viewData);
 }
Beispiel #5
0
 /**
  * Lista de tareas
  *
  * @param  bool $visible    true|false
  * @return mixed            Array de objetos de tareas
  */
 public static function getAll($filters = array(), $node = null, $undoneOnly = false)
 {
     $values = array();
     $list = array();
     $sqlFilter = "";
     $and = " WHERE";
     if (!empty($filters['done'])) {
         if ($filters['done'] == 'done') {
             $sqlFilter .= "{$and} done IS NOT NULL";
             $and = " AND";
         } else {
             $sqlFilter .= "{$and} done IS NULL";
             $and = " AND";
         }
     }
     if (!empty($filters['user'])) {
         $sqlFilter .= "{$and} done = :user";
         $values[':user'] = $filters['user'];
         $and = " AND";
     }
     if (!empty($filters['node'])) {
         $sqlFilter .= "{$and} node = :node";
         $values[':node'] = $filters['node'];
         $and = " AND";
     } elseif (!empty($node)) {
         $sqlFilter .= "{$and} node = :node";
         $values[':node'] = $node;
         $and = " AND";
     }
     if ($undoneOnly) {
         $sqlFilter .= "{$and} (done IS NULL OR done = '')";
         $and = " AND";
     }
     $sql = "SELECT *\n                    FROM task\n                    {$sqlFilter}\n                    ORDER BY datetime DESC\n                    ";
     echo $sql . '<br />';
     $query = self::query($sql, $values);
     foreach ($query->fetchAll(\PDO::FETCH_CLASS, __CLASS__) as $item) {
         if (!empty($item->done)) {
             $item->user = \Goteo\Model\User::getMini($item->done);
         }
         $list[] = $item;
     }
     return $list;
 }
Beispiel #6
0
 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));
 }
Beispiel #7
0
 public static function getAll($project, $filter = null)
 {
     /*
      * Estos son los filtros
      */
     $filters = array('date' => Text::_('Fecha'), 'user' => Text::_('Usuario'), 'reward' => Text::_('Recompensa'), 'pending' => Text::_('Pendientes'), 'fulfilled' => Text::_('Cumplidos'));
     $invests = array();
     $query = static::query("\n                SELECT  *\n                FROM  invest\n                WHERE   invest.project = ?\n                AND invest.status IN ('0', '1', '3', '4')\n                ", array($project));
     foreach ($query->fetchAll(\PDO::FETCH_CLASS, __CLASS__) as $invest) {
         // datos del usuario
         $invest->user = User::get($invest->user);
         $query = static::query("\n                    SELECT  *\n                    FROM  invest_reward\n                    INNER JOIN reward\n                        ON invest_reward.reward = reward.id\n                    WHERE   invest_reward.invest = ?\n                    ", array($invest->id));
         $invest->rewards = $query->fetchAll(\PDO::FETCH_OBJ);
         $query = static::query("\n                    SELECT  address, zipcode, location, country\n                    FROM  invest_address\n                    WHERE   invest_address.invest = ?\n                    ", array($invest->id));
         $invest->address = $query->fetchObject();
         // si no tiene dirección, sacamos la dirección del usuario
         if (empty($invest->address)) {
             $usr_address = User::getPersonal($invest->user->id);
             $invest->address = $usr_address;
         }
         $invests[$invest->id] = $invest;
     }
     return $invests;
 }
Beispiel #8
0
 public static function doPay($invest, &$errors = array())
 {
     try {
         $project = Project::getMini($invest->project);
         $userData = User::getMini($invest->user);
         // Create request object
         $payRequest = new \ExecutePaymentRequest();
         $payRequest->payKey = $invest->payment;
         $payRequest->requestEnvelope = 'SOAP';
         // Create service wrapper object
         $ap = new \AdaptivePayments();
         // invoke business method on service wrapper passing in appropriate request params
         $response = $ap->ExecutePayment($payRequest);
         // Check response
         if (strtoupper($ap->isSuccess) == 'FAILURE') {
             $soapFault = $ap->getLastError();
             if (is_array($soapFault->error)) {
                 $errorId = $soapFault->error[0]->errorId;
                 $errorMsg = $soapFault->error[0]->message;
             } else {
                 $errorId = $soapFault->error->errorId;
                 $errorMsg = $soapFault->error->message;
             }
             if (is_array($soapFault->payErrorList->payError)) {
                 $errorId = $soapFault->payErrorList->payError[0]->error->errorId;
                 $errorMsg = $soapFault->payErrorList->payError[0]->error->message;
             }
             // tratamiento de errores
             switch ($errorId) {
                 case '569013':
                     // preapproval cancelado por el usuario desde panel paypal
                 // preapproval cancelado por el usuario desde panel paypal
                 case '539012':
                     // preapproval no se llegó a autorizar
                     if ($invest->cancel()) {
                         $action = 'Aporte cancelado';
                         // Evento Feed
                         $log = new Feed();
                         $log->setTarget($project->id);
                         $log->populate('Aporte cancelado por preaproval cancelado por el usuario paypal', '/admin/invests', \vsprintf('Se ha <span class="red">Cancelado</span> el aporte de %s de %s (id: %s) al proyecto %s del dia %s por preapproval cancelado', array(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('system');
                         unset($log);
                     }
                     break;
             }
             if (empty($errorId)) {
                 $errors[] = 'NO es soapFault pero no es Success: <pre>' . print_r($ap, 1) . '</pre>';
                 @mail(\GOTEO_FAIL_MAIL, 'Error en implementacion Paypal API', 'ERROR en ' . __FUNCTION__ . ' No es un soap fault pero no es un success.<br /><pre>' . print_r($ap, 1) . '</pre>');
             } else {
                 $errors[] = "{$action} {$errorMsg} [{$errorId}]";
             }
             return false;
         }
         // verificar el campo paymentExecStatus
         if ($response->paymentExecStatus == 'COMPLETED') {
             if ($invest->setStatus('3')) {
                 return true;
             } else {
                 $errors[] = "Obtenido estatus de ejecución {$response->paymentExecStatus} pero no se ha actualizado el registro de aporte id {$invest->id}.";
                 @mail(\GOTEO_FAIL_MAIL, 'Error al actualizar registro aporte (setStatus)', 'ERROR en ' . __FUNCTION__ . ' Metodo paypal::setStatus ha fallado.<br /><pre>' . print_r($response, 1) . '</pre>');
                 return false;
             }
         } else {
             $errors[] = 'No se ha completado el pago encadenado, no se ha pagado al proyecto.';
             @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . ' aporte id ' . $invest->id . '. No payment exec status completed.<br /><pre>' . print_r($response, 1) . '</pre>');
             return false;
         }
     } catch (Exception $e) {
         $fault = new \FaultMessage();
         $errorData = new \ErrorData();
         $errorData->errorId = $ex->getFile();
         $errorData->message = $ex->getMessage();
         $fault->error = $errorData;
         $errors[] = 'No se ha podido inicializar la comunicación con Paypal, se ha reportado la incidencia.';
         @mail(\GOTEO_FAIL_MAIL, 'Error fatal en comunicacion Paypal API', 'ERROR en ' . __FUNCTION__ . '<br />No se ha podido inicializar la comunicación con Paypal.<br /><pre>' . print_r($fault, 1) . '</pre>');
         return false;
     }
 }
Beispiel #9
0
 private function process_userPersonal(&$project, &$errors)
 {
     if (!isset($_POST['process_userPersonal'])) {
         return false;
     }
     // campos que guarda este paso
     $fields = array('contract_name', 'contract_nif', 'contract_email', 'phone', 'contract_birthdate', 'address', 'zipcode', 'location', 'country');
     $personalData = array();
     foreach ($fields as $field) {
         if (isset($_POST[$field])) {
             $project->{$field} = $_POST[$field];
             $personalData[$field] = $_POST[$field];
         }
     }
     if (!$_POST['secondary_address']) {
         $project->post_address = null;
         $project->post_zipcode = null;
         $project->post_location = null;
         $project->post_country = null;
     }
     // actualizamos estos datos en los personales del usuario
     if (!empty($personalData)) {
         Model\User::setPersonal($project->owner, $personalData, true);
     }
     // cuentas bancarias
     $ppacc = !empty($_POST['paypal']) ? $_POST['paypal'] : '';
     $bankacc = !empty($_POST['bank']) ? $_POST['bank'] : '';
     // primero checkeamos si la cuenta Paypal es tipo email
     if (!Check::mail($ppacc)) {
         $project->errors['userPersonal']['paypal'] = Text::get('validate-project-paypal_account');
     } else {
         $project->okeys['userPersonal']['paypal'] = true;
     }
     $accounts = Model\Project\Account::get($project->id);
     $accounts->paypal = $ppacc;
     $accounts->bank = $bankacc;
     $accounts->save($project->errors['userPersonal']);
     return true;
 }
Beispiel #10
0
 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;
     }
 }
Beispiel #11
0
 public static function Projects($debug = false)
 {
     // proyectos a notificar
     $projects = Model\Project::review();
     // para cada uno,
     foreach ($projects as $project) {
         // por ahora solo tratamos los de primera ronda y hasta 2 meses tras la financiación
         if ($project->days > 40 || $project->days > 360) {
             continue;
         }
         if ($debug) {
             echo "Proyecto {$project->name}, Impulsor:  {$project->user->name}, email: {$project->user->email}, estado {$project->status}, lleva {$project->days} dias<br />";
         }
         // primero los que no se bloquean
         // Recuerdo al autor proyecto, 2 meses despues de campaña finalizada
         if ($project->days == 140) {
             // si quedan recompensas/retornos pendientes por cumplir
             if (!Model\Project\Reward::areFulfilled($project->id) || !Model\Project\Reward::areFulfilled($project->id, 'social')) {
                 if ($debug) {
                     echo "Recompensas/Retornos pendientes<br />";
                 }
                 Send::toOwner('2m_after', $project);
             } else {
                 if ($debug) {
                     echo "Recompensas/Retornos cumplidas, no se envía<br />";
                 }
             }
         }
         // Recuerdo al autor proyecto, 8 meses despues de campaña finalizada
         if ($project->days == 320) {
             // si quedan retornos pendientes por cumplir
             if (!Model\Project\Reward::areFulfilled($project->id, 'social')) {
                 if ($debug) {
                     echo "Retornos pendientes<br />";
                 }
                 Send::toOwner('8m_after', $project);
             } else {
                 if ($debug) {
                     echo "Retornos cumplidos, no se envía<br />";
                 }
             }
         }
         // ahora checkeamos bloqueo de consejos
         $prefs = Model\User::getPreferences($project->owner);
         if ($prefs->tips) {
             if ($debug) {
                 echo "Bloqueado por preferencias<hr />";
             }
             continue;
         }
         // flag de aviso
         $avisado = false;
         // Consejos/avisos puntuales
         switch ($project->days) {
             // NO condicionales
             case 1:
                 // Difunde, difunde, difunde
             // Difunde, difunde, difunde
             case 2:
                 // Comienza por lo más próximo
             // Comienza por lo más próximo
             case 3:
                 // Una acción a diario, por pequeña que sea
             // Una acción a diario, por pequeña que sea
             case 4:
                 // Llama a todas las puertas
             // Llama a todas las puertas
             case 5:
                 // Busca dónde está tu comunidad
             // Busca dónde está tu comunidad
             case 8:
                 // Agradece en público e individualmente
                 $template = 'tip_' . $project->days;
                 if ($debug) {
                     echo "Envío {$template}<br />";
                 }
                 Send::toOwner($template, $project);
                 break;
                 // periodico condicional
             // periodico condicional
             case 6:
                 // Publica novedades!
                 // y  se repite cada 6 días (fechas libres) mientras no haya posts
             // Publica novedades!
             // y  se repite cada 6 días (fechas libres) mientras no haya posts
             case 12:
             case 18:
             case 24:
             case 30:
             case 36:
                 // si ya hay novedades, nada
                 if (Model\Blog::hasUpdates($project->id)) {
                     if ($debug) {
                         echo "Ya ha publicado novedades<br />";
                     }
                 } else {
                     if ($debug) {
                         echo "Envío aviso de que no ha publicado novedades<br />";
                     }
                     Send::toOwner('any_update', $project);
                     $avisado = true;
                 }
                 break;
                 // comprobación periódica pero solo un envío
             // comprobación periódica pero solo un envío
             case 7:
                 // Apóyate en quienes te van apoyando ,  si más de 20 cofinanciadores
                 // o en cuanto llegue a 20 backers (en fechas libres)
             // Apóyate en quienes te van apoyando ,  si más de 20 cofinanciadores
             // o en cuanto llegue a 20 backers (en fechas libres)
             case 14:
             case 17:
             case 21:
             case 24:
             case 27:
                 // Si ya se mandó esta plantilla (al llegar a los 20 por primera vez) no se envía de nuevo
                 $sql = "\n                            SELECT\n                                id\n                            FROM mail\n                            WHERE mail.email = :email\n                            AND mail.template = 46\n                            ORDER BY mail.date DESC\n                            LIMIT 1";
                 $query = Model\Project::query($sql, array(':email' => $project->user->email));
                 $sended = $query->fetchColumn(0);
                 if (!$sended) {
                     if ($project->num_investors >= 20) {
                         if ($debug) {
                             echo "Tiene 20 backers y no se le habia enviado aviso antes<br />";
                         }
                         Send::toOwner('20_backers', $project);
                     } else {
                         if ($debug) {
                             echo "No llega a los 20 backers<br />";
                         }
                     }
                 } else {
                     if ($debug) {
                         echo "Ya enviado<br />";
                     }
                 }
                 break;
             case 9:
                 // Busca prescriptores e implícalos
                 // si no tiene padrinos
                 if ($project->patrons > 0) {
                     if ($debug) {
                         echo "Tiene padrino<br />";
                     }
                 } else {
                     if ($debug) {
                         echo "No tiene padrino<br />";
                     }
                     Send::toOwner('tip_9', $project);
                 }
                 break;
             case 10:
                 // Luce tus recompensas y retornos
                 // que no se envie a los que solo tienen recompensas de agradecimiento
                 $thanksonly = true;
                 // recompensas
                 $rewards = Model\Project\Reward::getAll($project->id, 'individual', \LANG);
                 foreach ($rewards as $rew) {
                     if ($rew->icon != 'thanks') {
                         $thanksonly = false;
                         break;
                         // ya salimos del bucle, no necesitamos más
                     }
                 }
                 if ($thanksonly) {
                     if ($debug) {
                         echo "Solo tiene recompensas de agradecimiento<br />";
                     }
                 } else {
                     if ($debug) {
                         echo "Tienen recompensas<br />";
                     }
                     uasort($rewards, function ($a, $b) {
                         if ($a->amount == $b->amount) {
                             return 0;
                         }
                         return $a->amount > $b->amount ? 1 : -1;
                     });
                     // sacar la primera y la última
                     $lower = reset($rewards);
                     $project->lower = $lower->reward;
                     $higher = end($rewards);
                     $project->higher = $higher->reward;
                     Send::toOwner('tip_10', $project);
                 }
                 break;
             case 11:
                 // Refresca tu mensaje de motivacion
                 // si no tiene video motivacional
                 if (empty($project->video)) {
                     if ($debug) {
                         echo "No tiene video motivacional<br />";
                     }
                     Send::toOwner('tip_11', $project);
                 } else {
                     if ($debug) {
                         echo "Tiene video motivacional<br />";
                     }
                 }
                 break;
             case 15:
                 // Sigue los avances y calcula lo que falta
                 // si no ha llegado al mínimo
                 if ($project->invested < $project->mincost) {
                     if ($debug) {
                         echo "No ha llegado al mínimo<br />";
                     }
                     Send::toOwner('tip_15', $project);
                 } else {
                     if ($debug) {
                         echo "Ha llegado al mínimo<br />";
                     }
                 }
                 break;
             case 25:
                 // No bajes la guardia!
                 // si no ha llegado al mínimo
                 if ($project->invested < $project->mincost) {
                     if ($debug) {
                         echo "No ha llegado al mínimo<br />";
                     }
                     Send::toOwner('two_weeks', $project);
                 } else {
                     if ($debug) {
                         echo "Ha llegado al mínimo<br />";
                     }
                 }
                 break;
             case 32:
                 // Al proyecto le faltan 8 días para archivarse
                 // si no ha llegado al mínimo
                 if ($project->invested < $project->mincost) {
                     if ($debug) {
                         echo "No ha llegado al mínimo<br />";
                     }
                     Send::toOwner('8_days', $project);
                 } else {
                     if ($debug) {
                         echo "Ha llegado al mínimo<br />";
                     }
                 }
                 break;
             case 38:
                 // Al proyecto le faltan 2 días para archivarse
                 // si no ha llegado al mínimo pero está por encima del 70%
                 if ($project->invested < $project->mincost && $project->percent >= 70) {
                     if ($debug) {
                         echo "No ha llegado al mínimo<br />";
                     }
                     Send::toOwner('2_days', $project);
                 } else {
                     if ($debug) {
                         echo "Ha llegado al mínimo o lleva menos de 70%<br />";
                     }
                 }
                 break;
         }
         // Avisos periodicos
         // si lleva más de 15 días: si no se han publicado novedades en la última semana
         // Ojo! que si no a enviado ninguna no lanza este sino la de cada 6 días
         if (!$avisado && $project->days > 15) {
             if ($debug) {
                 echo "ya lleva una quincena de campaña, verificamos novedades<br />";
             }
             // veamos si ya le avisamos hace una semana
             // Si ya se mandó esta plantilla (al llegar a los 20 por primera vez) no se envía de nuevo
             $sql = "\n                        SELECT\n                            id,\n                            DATE_FORMAT(\n                                from_unixtime(unix_timestamp(now()) - unix_timestamp(date))\n                                , '%j'\n                            ) as days\n                        FROM mail\n                        WHERE mail.email = :email\n                        AND mail.template = 23\n                        ORDER BY mail.date DESC\n                        LIMIT 1";
             $query = Model\Project::query($sql, array(':email' => $project->user->email));
             $lastsend = $query->fetchObject();
             if (!$lastsend->id || $lastsend->days > 7) {
                 // veamos cuanto hace de la última novedad
                 $sql = "\n                            SELECT\n                                DATE_FORMAT(\n                                    from_unixtime(unix_timestamp(now()) - unix_timestamp(date))\n                                    , '%j'\n                                ) as days\n                            FROM post\n                            INNER JOIN blog\n                                ON  post.blog = blog.id\n                                AND blog.type = 'project'\n                                AND blog.owner = :project\n                            WHERE post.publish = 1\n                            ORDER BY post.date DESC\n                            LIMIT 1";
                 $query = Model\Project::query($sql, array(':project' => $project->id));
                 $lastUpdate = $query->fetchColumn(0);
                 if ($lastUpdate > 7) {
                     if ($debug) {
                         echo "Ultima novedad es de hace más de una semana<br />";
                     }
                     Send::toOwner('no_updates', $project);
                 } elseif (is_numeric($lastUpdate)) {
                     if ($debug) {
                         echo "Publicó novedad hace menos de una semana<br />";
                     }
                 } else {
                     if ($debug) {
                         echo "No se ha publicado nada, recibirá el de cada 6 días<br />";
                     }
                 }
             } else {
                 if ($debug) {
                     echo "Se le avisó por novedades hace menos de una semana<br />";
                 }
             }
         }
         if ($debug) {
             echo "<hr />";
         }
     }
     if ($debug) {
         echo "<br />Auto-tips Listo!<hr />";
     }
     return;
 }
Beispiel #12
0
 public static function process($action = 'list', $id = null, $filters = array())
 {
     // año fiscal
     $year = Model\User\Donor::$currYear;
     $year0 = $year;
     $year1 = $year - 1;
     $errors = array();
     $node = isset($_SESSION['admin_node']) ? $_SESSION['admin_node'] : \GOTEO_NODE;
     // Valores de filtro
     $interests = Model\User\Interest::getAll();
     $status = Model\Project::status();
     $methods = Model\Invest::methods();
     $types = array('investor' => 'Cofinanciadores', 'owner' => 'Autores', 'user' => 'Usuarios');
     $roles = array('admin' => 'Administrador', 'checker' => 'Revisor', 'translator' => 'Traductor');
     // una variable de sesion para mantener los datos de todo esto
     if (!isset($_SESSION['mailing'])) {
         $_SESSION['mailing'] = array();
     }
     switch ($action) {
         case 'edit':
             $_SESSION['mailing']['receivers'] = array();
             $values = array();
             $sqlFields = '';
             $sqlInner = '';
             $sqlFilter = '';
             // cargamos los destiantarios
             //----------------------------
             // por tipo de usuario
             switch ($filters['type']) {
                 case 'investor':
                     $sqlInner .= "INNER JOIN invest\n                                    ON invest.user = user.id\n                                    AND (invest.status = 0 OR invest.status = 1 OR invest.status = 3 OR invest.status = 4)\n                                INNER JOIN project\n                                    ON project.id = invest.project\n                                    ";
                     $sqlFields .= ", project.name as project";
                     $sqlFields .= ", project.id as projectId";
                     break;
                 case 'owner':
                     $sqlInner .= "INNER JOIN project\n                                    ON project.owner = user.id\n                                    ";
                     $sqlFields .= ", project.name as project";
                     $sqlFields .= ", project.id as projectId";
                     break;
                 default:
                     break;
             }
             $_SESSION['mailing']['filters_txt'] = 'los <strong>' . $types[$filters['type']] . '</strong> ';
             if (!empty($filters['project']) && !empty($sqlInner)) {
                 $sqlFilter .= " AND project.name LIKE (:project) ";
                 $values[':project'] = '%' . $filters['project'] . '%';
                 $_SESSION['mailing']['filters_txt'] .= 'de proyectos que su nombre contenga <strong>\'' . $filters['project'] . '\'</strong> ';
             } elseif (empty($filters['project']) && !empty($sqlInner)) {
                 $_SESSION['mailing']['filters_txt'] .= 'de cualquier proyecto ';
             }
             if (isset($filters['status']) && $filters['status'] > -1 && !empty($sqlInner)) {
                 $sqlFilter .= "AND project.status = :status ";
                 $values[':status'] = $filters['status'];
                 $_SESSION['mailing']['filters_txt'] .= 'en estado <strong>' . $status[$filters['status']] . '</strong> ';
             } elseif ($filters['status'] < 0 && !empty($sqlInner)) {
                 $_SESSION['mailing']['filters_txt'] .= 'en cualquier estado ';
             }
             if ($filters['type'] == 'investor') {
                 if (!empty($filters['method']) && !empty($sqlInner)) {
                     $sqlFilter .= "AND invest.method = :method ";
                     $values[':method'] = $filters['method'];
                     $_SESSION['mailing']['filters_txt'] .= 'mediante <strong>' . $methods[$filters['method']] . '</strong> ';
                 } elseif (empty($filters['method']) && !empty($sqlInner)) {
                     $_SESSION['mailing']['filters_txt'] .= 'mediante cualquier metodo ';
                 }
             }
             if (!empty($filters['interest'])) {
                 $sqlInner .= "INNER JOIN user_interest\n                                ON user_interest.user = user.id\n                                AND user_interest.interest = :interest\n                                ";
                 $values[':interest'] = $filters['interest'];
                 if ($filters['interest'] == 15) {
                     $_SESSION['mailing']['filters_txt'] .= 'del grupo de testeo ';
                 } else {
                     $_SESSION['mailing']['filters_txt'] .= 'interesados en fin <strong>' . $interests[$filters['interest']] . '</strong> ';
                 }
             }
             if (!empty($filters['role'])) {
                 $sqlInner .= "INNER JOIN user_role\n                                ON user_role.user_id = user.id\n                                AND user_role.role_id = :role\n                                ";
                 $values[':role'] = $filters['role'];
                 $_SESSION['mailing']['filters_txt'] .= 'que sean <strong>' . $roles[$filters['role']] . '</strong> ';
             }
             if (!empty($filters['name'])) {
                 $sqlFilter .= " AND ( user.name LIKE (:name) OR user.email LIKE (:name) ) ";
                 $values[':name'] = '%' . $filters['name'] . '%';
                 $_SESSION['mailing']['filters_txt'] .= 'que su nombre o email contenga <strong>\'' . $filters['name'] . '\'</strong> ';
             }
             if (!empty($filters['donant'])) {
                 if ($filters['type'] == 'investor') {
                     $sqlFilter .= " AND invest.resign = 1\n                                AND invest.status IN (1, 3)\n                                AND invest.charged >= '{$year0}-01-01'\n                                AND invest.charged < '{$year1}-01-01'\n                                AND (project.passed IS NOT NULL AND project.passed != '0000-00-00')\n                                ";
                     $_SESSION['mailing']['filters_txt'] .= 'que haya hecho algun donativo ';
                 } else {
                     Message::Error('Solo se filtran donantes si se envia "A los: Cofinanciadores"');
                 }
             }
             if ($node != \GOTEO_NODE) {
                 $sqlFilter .= " AND user.node = :node";
                 $values[':node'] = $node;
                 if (!empty($sqlInner)) {
                     $sqlFilter .= " AND project.node = :node";
                 }
             }
             $sql = "SELECT\n                                user.id as id,\n                                user.id as user,\n                                user.name as name,\n                                user.email as email\n                                {$sqlFields}\n                            FROM user\n                            {$sqlInner}\n                            WHERE user.active = 1\n                            {$sqlFilter}\n                            GROUP BY user.id\n                            ORDER BY user.name ASC\n                            ";
             //                        die('<pre>'.$sql . '<br />'.print_r($values, 1).'</pre>');
             if ($query = Model\User::query($sql, $values)) {
                 foreach ($query->fetchAll(\PDO::FETCH_OBJ) as $receiver) {
                     $_SESSION['mailing']['receivers'][$receiver->id] = $receiver;
                 }
             } else {
                 Message::Error('Fallo el SQL!!!!! <br />' . $sql . '<pre>' . print_r($values, 1) . '</pre>');
             }
             // si no hay destinatarios, salta a la lista con mensaje de error
             if (empty($_SESSION['mailing']['receivers'])) {
                 Message::Error('No se han encontrado destinatarios para ' . $_SESSION['mailing']['filters_txt']);
                 throw new Redirection('/admin/mailing/list');
             }
             // si hay, mostramos el formulario de envio
             return new View('view/admin/index.html.php', array('folder' => 'mailing', 'file' => 'edit', 'filters' => $filters, 'interests' => $interests, 'status' => $status, 'types' => $types, 'roles' => $roles));
             break;
         case 'send':
             //                    die(\trace($_POST));
             $URL = NODE_ID != GOTEO_NODE ? NODE_URL : SITE_URL;
             // Enviando contenido recibido a destinatarios recibidos
             $receivers = array();
             $subject = $_POST['subject'];
             $templateId = !empty($_POST['template']) ? $_POST['template'] : 11;
             $content = \str_replace('%SITEURL%', $URL, $_POST['content']);
             // quito usuarios desmarcados
             foreach ($_SESSION['mailing']['receivers'] as $usr => $userData) {
                 $errors = array();
                 $campo = 'receiver_' . $usr;
                 if (!isset($_POST[$campo])) {
                     $_SESSION['mailing']['receivers'][$usr]->ok = null;
                 } else {
                     $receivers[] = $userData;
                 }
             }
             // montamos el mailing
             // - se crea un registro de tabla mail
             $sql = "INSERT INTO mail (id, email, html, template, node) VALUES ('', :email, :html, :template, :node)";
             $values = array(':email' => 'any', ':html' => $content, ':template' => $templateId, ':node' => $node);
             $query = \Goteo\Core\Model::query($sql, $values);
             $mailId = \Goteo\Core\Model::insertId();
             // - se usa el metodo initializeSending para grabar el envío (parametro para autoactivar)
             // - initiateSending ($mailId, $subject, $receivers, $autoactive = 0)
             if (\Goteo\Library\Sender::initiateSending($mailId, $subject, $receivers, 1)) {
                 $ok = true;
                 // Evento Feed
                 $log = new Feed();
                 $log->populate('comunicación masiva a usuarios (admin)', '/admin/mailing', \vsprintf("El admin %s ha iniciado una %s a %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Comunicacion masiva'), $_SESSION['mailing']['filters_txt'])));
                 $log->doAdmin('admin');
                 unset($log);
             } else {
                 $ok = false;
                 // Evento Feed
                 $log = new Feed();
                 $log->populate('comunicación masiva a usuarios (admin)', '/admin/mailing', \vsprintf("El admin %s le ha %s una %s a %s", array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'fallado'), Feed::item('relevant', 'Comunicacion masiva'), $_SESSION['mailing']['filters_txt'])));
                 $log->doAdmin('admin');
                 unset($log);
             }
             return new View('view/admin/index.html.php', array('folder' => 'mailing', 'file' => 'send', 'subject' => $subject, 'interests' => $interests, 'status' => $status, 'methods' => $methods, 'types' => $types, 'roles' => $roles, 'users' => $receivers, 'ok' => $ok));
             break;
     }
     return new View('view/admin/index.html.php', array('folder' => 'mailing', 'file' => 'list', 'interests' => $interests, 'status' => $status, 'methods' => $methods, 'types' => $types, 'roles' => $roles, 'filters' => $filters));
 }
Beispiel #13
0
 public static function investors($project, $projNum = false, $showall = false)
 {
     $worth = array();
     $investors = array();
     $sql = "\n                SELECT\n                    invest.user as user,\n                    user.name as name,\n                    user.avatar as avatar,\n                    user.worth as worth,\n                    invest.amount as amount,\n                    DATE_FORMAT(invest.invested, '%d/%m/%Y') as date,\n                    ";
     $sql .= "user.hide as hide,\n                     invest.anonymous as anonymous\n                FROM    invest\n                INNER JOIN user\n                    ON  user.id = invest.user\n                WHERE   project = ?\n                AND     invest.status IN ('0', '1', '3', '4')\n                ORDER BY invest.invested DESC, invest.id DESC\n                ";
     $query = self::query($sql, array($project));
     foreach ($query->fetchAll(\PDO::FETCH_OBJ) as $investor) {
         $investor->avatar = Image::get($investor->avatar);
         if (empty($investor->avatar->id) || !$investor->avatar instanceof Image) {
             $investor->avatar = Image::get(1);
         }
         // si el usuario es hide o el aporte es anonymo, lo ponemos como el usuario anonymous (avatar 1)
         if (!$showall && ($investor->hide == 1 || $investor->anonymous == 1)) {
             // mantenemos la fecha del anonimo mas reciente
             $anonymous_date = empty($investors['anonymous']->date) ? $investor->date : $investors['anonymous']->date;
             $investors[] = (object) array('user' => 'anonymous', 'name' => Text::get('regular-anonymous'), 'projects' => null, 'avatar' => Image::get(1), 'worth' => $investor->worth, 'amount' => $investor->amount, 'date' => $investor->date);
         } else {
             if (!isset($worth[$investor->user])) {
                 $worth[$investor->user] = \Goteo\Model\User::calcWorth($investor->user);
             }
             $investors[] = (object) array('user' => $investor->user, 'name' => $investor->name, 'projects' => $investor->projects, 'avatar' => $investor->avatar, 'worth' => $worth[$investor->user], 'amount' => $investor->amount, 'date' => $investor->date);
         }
     }
     return $investors;
 }
Beispiel #14
0
 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);
 }
Beispiel #15
0
 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);
 }
Beispiel #16
0
 /**
  * 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;
     }
 }
Beispiel #17
0
 public static function process($action = 'list', $id = null, $filters = array())
 {
     $node = isset($_SESSION['admin_node']) ? $_SESSION['admin_node'] : \GOTEO_NODE;
     // métodos de pago
     $methods = Model\Invest::methods();
     // estados del proyecto
     $status = Model\Project::status();
     // estados de aporte
     $investStatus = Model\Invest::status();
     // listado de proyectos
     $projects = Model\Invest::projects(false, $node);
     // 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');
     if ($action == 'csv') {
         $invest = Model\Invest::getPreapproval($id);
         foreach ($invest as $value) {
             $csv[] = array($value->id, $value->amount);
         }
         $fileName = "axes_" . date("YmdHis") . ".csv";
         header("Content-Disposition: attachment; filename=\"{$filename}\"");
         header("Content-type: application/octet-stream");
         header("Pragma: no-cache");
         header("Expires: 0");
         $fp = fopen('php://output', 'w');
         foreach ($csv as $fields) {
             fputcsv($fp, $fields);
         }
         fclose($fp);
         exit;
     }
     if ($action == 'dopay') {
         $query = \Goteo\Core\Model::query("\n                    SELECT  *\n                    FROM  invest\n                    WHERE   invest.project = ?\n                    AND     (invest.status = 0\n                        OR (invest.method = 'tpv'\n                            AND invest.status = 1\n                        )\n                        OR (invest.method = 'cash'\n                            AND invest.status = 1\n                        )\n                    )\n                    AND (invest.campaign IS NULL OR invest.campaign = 0)\n                    ", array($id));
         $invests = $query->fetchAll(\PDO::FETCH_CLASS, '\\Goteo\\Model\\Invest');
         foreach ($invests as $key => $invest) {
             if ($invest->setPayment(date("YmdHis"))) {
                 $invest->setStatus(1);
                 Model\Invest::setDetail($invest->id, 'executed', 'Preapproval has been executed, has initiated the chained payment. Process cron / execute');
                 if ($invest->issue) {
                     Model\Invest::unsetIssue($invest->id);
                     Model\Invest::setDetail($invest->id, 'issue-solved', 'The incidence has been resolved upon success by the automatic process');
                 }
             }
         }
         Message::Info("処理しました");
         throw new Redirection('/admin/projects/list');
         exit;
     }
     // detalles del aporte
     if ($action == 'details') {
         $invest = Model\Invest::get($id);
         $project = Model\Project::get($invest->project);
         $userData = Model\User::get($invest->user);
         if (!empty($invest->droped)) {
             $droped = Model\Invest::get($invest->droped);
         } else {
             $droped = null;
         }
         if ($project->node != $node) {
             throw new Redirection('/admin/invests');
         }
         return new View('view/admin/index.html.php', array('folder' => 'invests', 'file' => 'details', 'invest' => $invest, 'project' => $project, 'user' => $userData, 'status' => $status, 'investStatus' => $investStatus, 'droped' => $droped, 'calls' => $calls));
     }
     // listado de aportes
     if ($filters['filtered'] == 'yes') {
         if (!empty($filters['calls'])) {
             $filters['types'] = '';
         }
         $list = Model\Invest::getList($filters, $node, 999);
     } else {
         $list = array();
     }
     $viewData = array('folder' => 'invests', 'file' => 'list', 'list' => $list, 'filters' => $filters, 'projects' => $projects, 'users' => $users, 'calls' => $calls, 'methods' => $methods, 'types' => $types, 'investStatus' => $investStatus);
     return new View('view/admin/index.html.php', $viewData);
 }
Beispiel #18
0
 public static function getList($filters = array(), $published = true)
 {
     $values = array(':lang' => \LANG);
     $list = array();
     $sql = "\n                SELECT\n                    post.id as id,\n                    post.blog as blog,\n                    IFNULL(post_lang.title, post.title) as title,\n                    IFNULL(post_lang.text, post.text) as `text`,\n                    IFNULL(post_lang.legend, post.legend) as `legend`,\n                    post.image as `image`,\n                    post.media as `media`,\n                    DATE_FORMAT(post.date, '%d-%m-%Y') as fecha,\n                    post.publish as publish,\n                    post.home as home,\n                    post.footer as footer,\n                    post.author as author,\n                    blog.type as owner_type,\n                    blog.owner as owner_id\n                FROM    post\n                INNER JOIN blog\n                    ON  blog.id = post.blog\n                LEFT JOIN post_lang\n                    ON  post_lang.id = post.id\n                    AND post_lang.lang = :lang\n                ";
     if (in_array($filters['show'], array('all', 'home', 'footer'))) {
         $sql .= " WHERE blog.id IS NOT NULL\n                ";
     } elseif ($filters['show'] == 'updates') {
         $sql .= " WHERE blog.type = 'project'\n                ";
     } else {
         $sql .= " WHERE blog.type = 'node'\n                ";
     }
     if (!empty($filters['blog'])) {
         $sql .= " AND post.blog = :blog\n                ";
         $values[':blog'] = $filters['blog'];
     }
     if (!empty($filters['tag'])) {
         $sql .= " AND post.id IN (SELECT post FROM post_tag WHERE tag = :tag)\n                ";
         $values[':tag'] = $filters['tag'];
     }
     if (!empty($filters['author'])) {
         $sql .= " AND post.author = :author\n                ";
         $values[':author'] = $filters['author'];
     }
     // solo las publicadas
     if ($published || $filters['show'] == 'published') {
         $sql .= " AND post.publish = 1\n                ";
         if (empty($filters['blog'])) {
             $sql .= " AND blog.owner IN (SELECT id FROM node WHERE active = 1)\n                    AND blog.owner != 'testnode'\n                ";
         }
     }
     // solo las del propio blog
     if ($filters['show'] == 'owned') {
         $sql .= " AND blog.owner = :node\n                ";
         $values[':node'] = $filters['node'];
     }
     // solo las de la portada
     if ($filters['show'] == 'home') {
         if ($filters['node'] == \GOTEO_NODE) {
             $sql .= " AND post.home = 1\n                    ";
         } else {
             $sql .= " AND post.id IN (SELECT post FROM post_node WHERE node = :node)\n                    ";
             $values[':node'] = $filters['node'];
         }
     }
     if ($filters['show'] == 'footer') {
         if ($filters['node'] == \GOTEO_NODE) {
             $sql .= " AND post.footer = 1\n                    ";
         }
     }
     $sql .= "\n                ORDER BY post.date DESC, post.id DESC\n                ";
     $query = static::query($sql, $values);
     foreach ($query->fetchAll(\PDO::FETCH_CLASS, __CLASS__) as $post) {
         // galeria
         $post->gallery = Image::getAll($post->id, 'post');
         $post->image = $post->gallery[0];
         // video
         if (isset($post->media)) {
             $post->media = new Media($post->media);
         }
         $post->num_comments = Post\Comment::getCount($post->id);
         // datos del autor del  post
         switch ($post->owner_type) {
             case 'project':
                 $proj_blog = Project::getMini($post->owner_id);
                 $post->author = $proj_blog->owner;
                 $post->user = $proj_blog->user;
                 $post->owner_name = $proj_blog->name;
                 break;
             case 'node':
                 $post->user = User::getMini($post->author);
                 $node_blog = Node::get($post->owner_id);
                 $post->owner_name = $node_blog->name;
                 break;
         }
         $list[$post->id] = $post;
     }
     return $list;
 }
Beispiel #19
0
 public static function process($action = 'list', $id = null, $filters = array())
 {
     $node = isset($_SESSION['admin_node']) ? $_SESSION['admin_node'] : \GOTEO_NODE;
     $errors = array();
     switch ($action) {
         case 'add':
             // proyectos que están más allá de edición y con traducción deshabilitada
             $availables = Model\User\Translate::getAvailables('project', $_SESSION['admin_node']);
             if (empty($availables)) {
                 Message::Error(Text::_('No hay más proyectos disponibles para traducir'));
                 throw new Redirection('/admin/translates');
             }
         case 'edit':
         case 'assign':
         case 'unassign':
         case 'send':
             // a ver si tenemos proyecto
             if (empty($id) && !empty($_POST['project'])) {
                 $id = $_POST['project'];
             }
             if (!empty($id)) {
                 $project = Model\Project::getMini($id);
             } elseif ($action != 'add') {
                 Message::Error(Text::_('No hay proyecto sobre el que operar'));
                 throw new Redirection('/admin/translates');
             }
             // asignar o desasignar
             // la id de revision llega en $id
             // la id del usuario llega por get
             $user = $_GET['user'];
             if (!empty($user)) {
                 $userData = Model\User::getMini($user);
                 $assignation = new Model\User\Translate(array('item' => $project->id, 'type' => 'project', 'user' => $user));
                 switch ($action) {
                     case 'assign':
                         // se la ponemos
                         $what = Text::_('Asignado');
                         if ($assignation->save($errors)) {
                             Message::Info(Text::_('Traducción asignada correctamente'));
                             throw new Redirection('/admin/translates/edit/' . $project->id);
                         } else {
                             Message::Error(Text::_('No se ha guardado correctamente. ') . implode(', ', $errors));
                         }
                         break;
                     case 'unassign':
                         // se la quitamos
                         $what = Text::_('Desasignado');
                         if ($assignation->remove($errors)) {
                             Message::Info(Text::_('Traducción desasignada correctamente'));
                             throw new Redirection('/admin/translates/edit/' . $project->id);
                         } else {
                             Message::Error(Text::_('No se ha guardado correctamente. ') . implode(', ', $errors));
                         }
                         break;
                 }
                 if (empty($errors)) {
                     // Evento Feed
                     $log = new Feed();
                     $log->setTarget($userData->id, 'user');
                     $log->populate($what . ' traduccion (admin)', '/admin/translates', \vsprintf('El admin %s ha %s a %s la traducción del proyecto %s', array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', $what), Feed::item('user', $userData->name, $userData->id), Feed::item('project', $project->name, $project->id))));
                     $log->doAdmin('admin');
                     unset($log);
                 }
                 $action = 'edit';
             }
             // fin asignar o desasignar
             // añadir o actualizar
             // se guarda el idioma original y si la traducción está abierta o cerrada
             if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save'])) {
                 if (empty($id)) {
                     Message::Error(Text::_('Hemos perdido de vista el proyecto'));
                     throw new Redirection('/admin/translates');
                 }
                 // ponemos los datos que llegan
                 $sql = "UPDATE project SET lang = :lang, translate = 1 WHERE id = :id";
                 if (Model\Project::query($sql, array(':lang' => $_POST['lang'], ':id' => $id))) {
                     if ($action == 'add') {
                         Message::Info('El proyecto ' . $project->name . ' se ha habilitado para traducir');
                     } else {
                         Message::Info(Text::_('Datos de traducción actualizados'));
                     }
                     if ($action == 'add') {
                         // Evento Feed
                         $log = new Feed();
                         $log->setTarget($project->id);
                         $log->populate(Text::_('proyecto habilitado para traducirse (admin)'), '/admin/translates', \vsprintf('El admin %s ha %s la traducción del proyecto %s', array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Habilitado'), Feed::item('project', $project->name, $project->id))));
                         $log->doAdmin('admin');
                         unset($log);
                         throw new Redirection('/admin/translates/edit/' . $project->id);
                     } else {
                         throw new Redirection('/admin/translates');
                     }
                 } else {
                     if ($action == 'add') {
                         Message::Error(Text::_('Ha fallado al habilitar la traducción del proyecto ') . $project->name);
                     } else {
                         Message::Error(Text::_('Ha fallado al actualizar los datos de la traducción'));
                     }
                 }
             }
             if ($action == 'send') {
                 // Informar al autor de que la traduccion está habilitada
                 // Obtenemos la plantilla para asunto y contenido
                 $template = Template::get(26);
                 // Sustituimos los datos
                 $subject = str_replace('%PROJECTNAME%', $project->name, $template->title);
                 $search = array('%OWNERNAME%', '%PROJECTNAME%', '%SITEURL%');
                 $replace = array($project->user->name, $project->name, SITE_URL);
                 $content = \str_replace($search, $replace, $template->text);
                 // iniciamos mail
                 $mailHandler = new Mail();
                 $mailHandler->to = $project->user->email;
                 $mailHandler->toName = $project->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()) {
                     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);
                 $action = 'edit';
             }
             $project->translators = Model\User\Translate::translators($id);
             $translators = Model\User::getAll(array('role' => 'translator'));
             // añadimos al dueño del proyecto en el array de traductores
             array_unshift($translators, $project->user);
             return new View('view/admin/index.html.php', array('folder' => 'translates', 'file' => 'edit', 'action' => $action, 'availables' => $availables, 'translators' => $translators, 'project' => $project));
             break;
         case 'close':
             // la sentencia aqui mismo
             // el campo translate del proyecto $id a false
             $sql = "UPDATE project SET translate = 0 WHERE id = :id";
             if (Model\Project::query($sql, array(':id' => $id))) {
                 Message::Info('La traducción del proyecto ' . $project->name . ' se ha finalizado');
                 Model\Project::query("DELETE FROM user_translate WHERE type = 'project' AND item = :id", array(':id' => $id));
                 // Evento Feed
                 $log = new Feed();
                 $log->setTarget($project->id);
                 $log->populate(Text::_('traducción finalizada (admin)'), '/admin/translates', \vsprintf('El admin %s ha dado por %s la traducción del proyecto %s', array(Feed::item('user', $_SESSION['user']->name, $_SESSION['user']->id), Feed::item('relevant', 'Finalizada'), Feed::item('project', $project->name, $project->id))));
                 $log->doAdmin('admin');
                 unset($log);
             } else {
                 Message::Error(Text::_('Falló al finalizar la traducción'));
             }
             break;
     }
     $projects = Model\Project::getTranslates($filters, $node);
     $owners = Model\User::getOwners();
     $translators = Model\User::getAll(array('role' => 'translator'));
     return new View('view/admin/index.html.php', array('folder' => 'translates', 'file' => 'list', 'projects' => $projects, 'filters' => $filters, 'fields' => array('owner', 'translator'), 'owners' => $owners, 'translators' => $translators));
 }
Beispiel #20
0
 /**
  * Realiza el envio masivo a participantees o cofinanciadores
  * 
  * @param type $option 'messegers' || 'rewards'
  * @param type $project Instancia del proyecto de trabajo
  * @return boolean
  */
 public static function process_mailing($option, $project)
 {
     $who = array();
     // verificar que hay mensaje
     if (empty($_POST['message'])) {
         Message::Error(Text::get('dashboard-investors-mail-text-required'));
         return false;
     } else {
         $msg_content = nl2br(\strip_tags($_POST['message']));
     }
     // si a todos los participantes
     if ($option == 'messegers' && !empty($_POST['msg_all'])) {
         // a todos los participantes
         foreach (Model\Message::getMessegers($project->id) as $messeger => $msgData) {
             if ($messeger == $project->owner) {
                 continue;
             }
             $who[$messeger] = $messeger;
             //                    unset($msgData); // los datos del mensaje del participante no se usan
         }
     } elseif ($option == 'rewards' && !empty($_POST['msg_all'])) {
         // a todos los cofinanciadores
         foreach (Model\Invest::investors($project->id, false, true) as $user => $investor) {
             // no duplicar
             $who[$investor->user] = $investor->user;
         }
     } elseif (!empty($_POST['msg_user'])) {
         // a usuario individual
         $who[$_POST['msg_user']] = $_POST['msg_user'];
     } elseif ($option == 'rewards') {
         $msg_rewards = array();
         // estos son msg_reward-[rewardId], a un grupo de recompensa
         foreach ($_POST as $key => $value) {
             $parts = explode('-', $key);
             if ($parts[0] == 'msg_reward' && $value == 1) {
                 $msg_rewards[] = $parts[1];
             }
         }
         // para cada recompensa
         foreach ($msg_rewards as $reward) {
             foreach (Model\Invest::choosed($reward) as $user) {
                 $who[$user] = $user;
             }
         }
     }
     // no hay destinatarios
     if (count($who) == 0) {
         Message::Error(Text::get('dashboard-investors-mail-nowho'));
         return false;
     }
     // obtener contenido
     // segun destinatarios
     $allsome = explode('/', Text::get('regular-allsome'));
     $enviandoa = !empty($_POST['msg_all']) ? $allsome[0] : $allsome[1];
     if ($option == 'messegers') {
         Message::Info(Text::get('dashboard-messegers-mail-sendto', $enviandoa));
     } else {
         Message::Info(Text::get('dashboard-investors-mail-sendto', $enviandoa));
     }
     // Obtenemos la plantilla para asunto y contenido
     $template = Template::get(2);
     // Sustituimos los datos
     if (!empty($_POST['subject'])) {
         $subject = $_POST['subject'];
     } else {
         $subject = str_replace('%PROJECTNAME%', $project->name, $template->title);
     }
     $remite = $project->name . ' ' . Text::get('regular-from') . ' ';
     $remite .= NODE_ID != GOTEO_NODE ? NODE_NAME : GOTEO_MAIL_NAME;
     $search = array('%MESSAGE%', '%PROJECTNAME%', '%PROJECTURL%', '%OWNERURL%', '%OWNERNAME%');
     $replace = array($msg_content, $project->name, SITE_URL . "/project/" . $project->id, SITE_URL . "/user/profile/" . $project->owner, $project->user->name);
     $content = \str_replace($search, $replace, $template->text);
     // para usar el proceso Sender:
     // - $who debe ser compatible con el formato $receivers
     // (falta nombre e email), sacarlo con getMini
     $receivers = array();
     foreach ($who as $userId) {
         $user = Model\User::getMini($userId);
         $user->user = $user->id;
         $receivers[] = $user;
     }
     // - en la plantilla hay que cambiar %NAME% por %USERNAME% para que sender reemplace
     // -
     // - se crea un registro de tabla mail
     $sql = "INSERT INTO mail (id, email, html, template, node) VALUES ('', :email, :html, :template, :node)";
     $values = array(':email' => 'any', ':html' => $content, ':template' => $template->id, ':node' => \GOTEO_NODE);
     $query = \Goteo\Core\Model::query($sql, $values);
     $mailId = \Goteo\Core\Model::insertId();
     // - se usa el metodo initializeSending para grabar el envío (parametro para autoactivar)
     // , también metemos el reply y repplyName (remitente) en la instancia de envío
     if (\Goteo\Library\Sender::initiateSending($mailId, $subject, $receivers, 1, $project->user->email, $remite)) {
         Message::Info(Text::get('dashboard-investors-mail-sended', 'la cola de envíos'));
         // cambiar este texto
     } else {
         Message::Error(Text::get('dashboard-investors-mail-fail', 'la cola de envíos'));
         // cambiar este texto
     }
     return true;
 }
Beispiel #21
0
 public function dopay($project)
 {
     die('Ya no realizamos pagos secundarios mediante sistema');
     if (\defined('CRON_EXEC')) {
         die('Este proceso no necesitamos lanzarlo automaticamente');
     }
     @mail(\GOTEO_FAIL_MAIL, 'Se ha lanzado el cron ' . __FUNCTION__ . ' en ' . SITE_URL, 'Se ha lanzado manualmente el cron ' . __FUNCTION__ . ' para el proyecto ' . $project . ' en ' . SITE_URL . ' a las ' . date('H:i:s') . ' Usuario ' . $_SESSION['user']->id);
     // a ver si existe el bloqueo
     $block_file = GOTEO_PATH . 'logs/cron-' . __FUNCTION__ . '.block';
     if (file_exists($block_file)) {
         echo 'Ya existe un archivo de log ' . date('Ymd') . '_' . __FUNCTION__ . '.log<br />';
         $block_content = \file_get_contents($block_file);
         echo 'El contenido del bloqueo es: ' . $block_content;
         // lo escribimos en el log
         $log_file = GOTEO_PATH . 'logs/cron/' . date('Ymd') . '_' . __FUNCTION__ . '.log';
         \file_put_contents($log_file, \ob_get_contents(), FILE_APPEND);
         \chmod($log_file, 0777);
         /*
                         @mail(\GOTEO_FAIL_MAIL, 'Cron '. __FUNCTION__ .' bloqueado en ' . SITE_URL,
            'Se ha encontrado con que el cron '. __FUNCTION__ .' está bloqueado el '.date('d-m-Y').' a las ' . date ('H:i:s') . '
                El contenido del bloqueo es: '. $block_content);
         */
         die;
     } else {
         $block = 'Bloqueo ' . $block_file . ' activado el ' . date('d-m-Y') . ' a las ' . date('H:i:s') . '<br />';
         if (\file_put_contents($block_file, $block, FILE_APPEND)) {
             \chmod($block_file, 0777);
             echo $block;
         } else {
             echo 'No se ha podido crear el archivo de bloqueo<br />';
             @mail(\GOTEO_FAIL_MAIL, 'Cron ' . __FUNCTION__ . ' no se ha podido bloquear en ' . SITE_URL, 'No se ha podido crear el archivo ' . $block_file . ' el ' . date('d-m-Y') . ' a las ' . date('H:i:s'));
         }
     }
     $projectData = Model\Project::getMini($project);
     // necesitamos la cuenta del proyecto y que sea la misma que cuando el preapproval
     $projectAccount = Model\Project\Account::get($project);
     if (empty($projectAccount->paypal)) {
         // iniciamos mail
         $mailHandler = new Mail();
         $mailHandler->to = \GOTEO_MAIL;
         $mailHandler->toName = 'Goteo.org';
         $mailHandler->subject = 'El proyecto ' . $projectData->name . ' no tiene cuenta PayPal';
         $mailHandler->content = 'Hola Goteo, el proyecto ' . $projectData->name . ' no tiene cuenta PayPal y se estaba intentando realizar pagos secundarios.';
         $mailHandler->html = false;
         $mailHandler->template = null;
         $mailHandler->send();
         unset($mailHandler);
         die('El proyecto ' . $projectData->name . ' no tiene la cuenta PayPal!!');
     }
     // tratamiento de aportes pendientes
     $query = Model\Project::query("\n                SELECT  *\n                FROM  invest\n                WHERE   invest.status = 1\n                AND     invest.method = 'paypal'\n                AND     invest.project = ?\n                ", array($project));
     $invests = $query->fetchAll(\PDO::FETCH_CLASS, '\\Goteo\\Model\\Invest');
     echo 'Vamos a tratar ' . count($invests) . ' aportes para el proyecto ' . $projectData->name . '<br />';
     foreach ($invests as $key => $invest) {
         $errors = array();
         $userData = Model\User::getMini($invest->user);
         echo 'Tratando: Aporte (id: ' . $invest->id . ') de ' . $userData->name . ' [' . $userData->email . ']<br />';
         if (Paypal::doPay($invest, $errors)) {
             echo 'Aporte (id: ' . $invest->id . ') pagado al proyecto. Ver los detalles en la <a href="/admin/accounts/details/' . $invest->id . '">gestion de transacciones</a><br />';
             $log_text = Text::_("Se ha realizado el pago de %s PayPal al proyecto %s por el aporte de %s (id: %s) del dia %s");
             Model\Invest::setDetail($invest->id, 'payed', 'Se ha realizado el pago secundario al proyecto. Proceso cron/doPay');
         } else {
             echo 'Fallo al pagar al proyecto el aporte (id: ' . $invest->id . '). Ver los detalles en la <a href="/admin/accounts/details/' . $invest->id . '">gestion de transacciones</a><br />' . implode('<br />', $errors);
             $log_text = Text::_("Ha fallado al realizar el pago de %s PayPal al proyecto %s por el aporte de %s (id: %s) del dia %s");
             Model\Invest::setDetail($invest->id, 'pay-failed', 'Fallo al realizar el pago secundario: ' . implode('<br />', $errors) . '. Proceso cron/doPay');
         }
         // Evento Feed
         $log = new Feed();
         $log->setTarget($projectData->id);
         $log->populate('Pago al proyecto encadenado-secundario (cron)', '/admin/accounts', \vsprintf($log_text, array(Feed::item('money', $invest->amount . ' &yen;'), Feed::item('project', $projectData->name, $project), Feed::item('user', $userData->name, $userData->id), Feed::item('system', $invest->id), Feed::item('system', date('d/m/Y', strtotime($invest->invested))))));
         $log->doAdmin();
         unset($log);
         echo '<hr />';
     }
     // desbloqueamos
     if (unlink($block_file)) {
         echo 'Cron ' . __FUNCTION__ . ' desbloqueado<br />';
     } else {
         echo 'ALERT! Cron ' . __FUNCTION__ . ' no se ha podido desbloquear<br />';
         if (file_exists($block_file)) {
             echo 'El archivo ' . $block_file . ' aun existe!<br />';
         } else {
             echo 'No hay archivo de bloqueo ' . $block_file . '!<br />';
         }
     }
     // recogemos el buffer para grabar el log
     $log_file = GOTEO_PATH . 'logs/cron/' . date('Ymd') . '_' . __FUNCTION__ . '.log';
     \file_put_contents($log_file, \ob_get_contents(), FILE_APPEND);
     \chmod($log_file, 0777);
 }
Beispiel #22
0
 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;
 }
Beispiel #23
0
 public static function shareAll($category)
 {
     $array = array();
     try {
         $values = array(':interest' => $category);
         $sql = "SELECT DISTINCT(user_interest.user) as id\n                        FROM user_interest\n                        INNER JOIN user\n                            ON  user.id = user_interest.user\n                            AND (user.hide = 0 OR user.hide IS NULL)\n                        WHERE user_interest.interest = :interest\n                        ";
         $query = static::query($sql, $values);
         $shares = $query->fetchAll(\PDO::FETCH_ASSOC);
         foreach ($shares as $share) {
             // nombre i avatar
             $user = \Goteo\Model\User::get($share['id']);
             if (empty($user->avatar)) {
                 $user->avatar = (object) array('id' => 1);
             }
             // meritocracia
             $support = (object) $user->support;
             // proyectos publicados
             $query = self::query('SELECT COUNT(id) FROM project WHERE owner = ? AND status > 2', array($share['id']));
             $projects = $query->fetchColumn(0);
             $array[] = (object) array('user' => $share['id'], 'avatar' => $user->avatar, 'name' => $user->name, 'projects' => $projects, 'invests' => $support->invests);
         }
         return $array;
     } catch (\PDOException $e) {
         throw new \Goteo\Core\Exception($e->getMessage());
     }
 }
Beispiel #24
0
     }
     break;
 case 'supporters':
     // segun el paso de aporte
     if (!empty($step) && in_array($step, array('start', 'login', 'confirm', 'continue', 'ok', 'fail'))) {
         switch ($step) {
             case 'continue':
                 echo new View('view/project/widget/investMsg.html.php', array('message' => $step, 'user' => $user)), new View('view/project/widget/invest_redirect.html.php', array('project' => $project, 'personal' => $personalData, 'step' => $step, 'allowpp' => $this['allowpp']));
                 break;
             case 'ok':
                 echo new View('view/project/widget/investMsg.html.php', array('message' => $step, 'user' => $user)), new View('view/project/widget/spread.html.php', array('project' => $project));
                 //sacarlo de div#center
                 $printSendMsg = true;
                 break;
             case 'fail':
                 echo new View('view/project/widget/investMsg.html.php', array('message' => $step, 'user' => User::get($_SESSION['user']->id))), new View('view/project/widget/invest.html.php', array('project' => $project, 'personal' => User::getPersonal($_SESSION['user']->id), 'allowpp' => $this['allowpp']));
                 break;
             default:
                 echo new View('view/project/widget/investMsg.html.php', array('message' => $step, 'user' => $user)), new View('view/project/widget/invest.html.php', array('project' => $project, 'personal' => $personalData, 'step' => $step, 'allowpp' => $this['allowpp']));
                 break;
         }
     } else {
         echo new View('view/project/widget/supporters.html.php', $this), new View('view/worth/legend.html.php');
     }
     break;
 case 'messages':
     echo new View('view/project/widget/messages.html.php', array('project' => $project));
     break;
 case 'rewards':
     echo new View('view/project/widget/rewards-summary.html.php', array('project' => $project));
     break;
Beispiel #25
0
 public function index($project = null)
 {
     if (empty($project)) {
         throw new Redirection('/discover', Redirection::TEMPORARY);
     }
     $message = '';
     $projectData = Model\Project::get($project);
     $methods = static::_methods();
     // si no está en campaña no pueden esta qui ni de coña
     if ($projectData->status != 3) {
         throw new Redirection('/project/' . $project, Redirection::TEMPORARY);
     }
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         $errors = array();
         $los_datos = $_POST;
         $method = \strtolower($_POST['method']);
         if (!isset($methods[$method])) {
             Message::Error(Text::get('invest-method-error'));
             throw new Redirection(SEC_URL . "/project/{$project}/invest/?confirm=fail", Redirection::TEMPORARY);
         }
         if (empty($_POST['amount'])) {
             Message::Error(Text::get('invest-amount-error'));
             throw new Redirection(SEC_URL . "/project/{$project}/invest/?confirm=fail", Redirection::TEMPORARY);
         }
         // dirección de envio para las recompensas
         // o datoas fiscales del donativo
         $address = array('name' => $_POST['fullname'], 'nif' => $_POST['nif'], 'address' => $_POST['address'], 'zipcode' => $_POST['zipcode'], 'location' => $_POST['location'], 'country' => $_POST['country']);
         if ($projectData->owner == $_SESSION['user']->id) {
             Message::Error(Text::get('invest-owner-error'));
             throw new Redirection(SEC_URL . "/project/{$project}/invest/?confirm=fail", Redirection::TEMPORARY);
         }
         // añadir recompensas que ha elegido
         $chosen = $_POST['selected_reward'];
         if ($chosen == 0) {
             // renuncia a las recompensas, bien por el/ella
             $resign = true;
             $reward = false;
         } else {
             // ya no se aplica esto de recompensa es de tipo Reconocimiento para donativo
             $resign = false;
             $reward = true;
         }
         // insertamos los datos personales del usuario si no tiene registro aun
         Model\User::setPersonal($_SESSION['user']->id, $address, false);
         $invest = new Model\Invest(array('amount' => $_POST['amount'], 'user' => $_SESSION['user']->id, 'project' => $project, 'method' => $method, 'status' => '-1', 'invested' => date('Y-m-d'), 'anonymous' => $_POST['anonymous'], 'resign' => $resign));
         if ($reward) {
             $invest->rewards = array($chosen);
         }
         $invest->address = (object) $address;
         if ($invest->save($errors)) {
             $invest->urlOK = SEC_URL . "/invest/confirmed/{$project}/{$invest->id}";
             $invest->urlNOK = SEC_URL . "/invest/fail/{$project}/{$invest->id}";
             Model\Invest::setDetail($invest->id, 'init', 'Se ha creado el registro de aporte, el usuario ha clickado el boton de tpv o paypal. Proceso controller/invest');
             switch ($method) {
                 case 'tpv':
                     // redireccion al tpv
                     if (Tpv::preapproval($invest, $errors)) {
                         die;
                     } else {
                         Message::Error(Text::get('invest-tpv-error_fatal'));
                     }
                     break;
                 case 'paypal':
                     // Petición de preapproval y redirección a paypal
                     if (Paypal::preapproval($invest, $errors)) {
                         die;
                     } else {
                         Message::Error(Text::get('invest-paypal-error_fatal'));
                     }
                     break;
                 case 'cash':
                     // En betatest aceptamos cash para pruebas
                     if (GOTEO_ENV != 'real') {
                         $invest->setStatus('1');
                         throw new Redirection($invest->urlOK);
                     } else {
                         throw new Redirection('/');
                     }
                     break;
             }
         } else {
             Message::Error(Text::get('invest-create-error'));
         }
     } else {
         Message::Error(Text::get('invest-data-error'));
     }
     throw new Redirection("/project/{$project}/invest/?confirm=fail");
 }
Beispiel #26
0
 /**
  * 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));
 }
Beispiel #27
0
                 echo
                     new View('view/m/project/widget/investMsg.html.php', array('message' => $step, 'user' => $user)),
                     new View('view/m/project/widget/invest_redirect.html.php', array('project' => $project, 'personal' => $personalData, 'step' => $step, 'allowpp'=> $this['allowpp']));
                 break;
                 
             case 'ok':
                 echo
                     new View('view/m/project/widget/investMsg.html.php', array('message' => $step, 'user' => $user)), new View('view/project/widget/spread.html.php',array('project' => $project));
                     //sacarlo de div#center
                     $printSendMsg=true;                                     
                 break;
                 
             case 'fail':
                 echo
                     new View('view/m/project/widget/investMsg.html.php', array('message' => $step, 'user' => User::get($_SESSION['user']->id))),
                     new View('view/m/project/widget/invest.html.php', array('project' => $project, 'personal' => User::getPersonal($_SESSION['user']->id), 'allowpp'=> $this['allowpp']));
                 break;
             default:
                 echo
                     new View('view/m/project/widget/investMsg.html.php', array('message' => $step, 'user' => $user)),
                     new View('view/m/project/widget/invest.html.php', array('project' => $project, 'personal' => $personalData, 'step' => $step, 'allowpp'=> $this['allowpp']));
                 break;
         }
     } else {
         echo
             new View('view/m/project/widget/supporters.html.php', $this),
             new View('view/m/worth/legend.html.php');
     }
     break;
     
 case 'messages':
Beispiel #28
0
 /**
  * @param $_param
  * @return false|Model\obj
  */
 private function _get_user($_param)
 {
     if (!empty($_param)) {
         $_result = \Goteo\Model\User::get($_param, 'ja');
     }
     return $_result;
 }
Beispiel #29
0
 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));
 }
Beispiel #30
0
 public static function getMessegers($id)
 {
     $list = array();
     $sql = "SELECT \n                        message.user as user,\n                        message.message as text,\n                        respond.message as thread_text\n                    FROM message\n                    LEFT JOIN message as respond\n                        ON respond.id = message.thread\n                    WHERE message.project = :id";
     $query = self::query($sql, array(':id' => $id));
     foreach ($query->fetchAll(\PDO::FETCH_OBJ) as $msg) {
         $msgData = (object) array('text' => $msg->text, 'thread_text' => $msg->thread_text);
         if (isset($list[$msg->user])) {
             $list[$msg->user]->messages[] = $msgData;
         } else {
             $user = User::getMini($msg->user);
             $user->messages = array();
             $user->messages[] = $msgData;
             $list[$msg->user] = $user;
         }
     }
     return $list;
 }