Example #1
0
 /**
  * Subservice LIKE
  *
  * @param Request $request			
  * @return Reponse/Array
  */
 public function _like(Request $request)
 {
     $user = $this->utils->getPerson($request->email);
     $completion = $this->utils->getProfileCompletion($request->email);
     // Verifying profile completion
     /*if ($completion * 1 < 70 || empty($user->gender) || empty($user->full_name))
     		{
     			 $response = new Response();
     			 $response->setResponseSubject("Cree su perfil en Apretaste!");
     			 $response->createFromTemplate('not_profile.tpl', array('email' => $request->email));
     			 return $response;
     		}*/
     // check if you are a member
     if (!$this->isMember($request->email)) {
         return $this->getNotMemberResponse();
     }
     if (empty(trim($request->query))) {
         $response = new Response();
         $response->setResponseSubject('No indicaste el nombre de usuario que te gusta');
         $response->createFromText('No indicaste el nombre de usuario que te gusta. Para hacerlo debes escribir el nombre de usuario en el asunto seguido del texto CUIPIDO LIKE.');
         return $response;
     }
     // get current user
     $currentUser = $this->utils->getPerson($request->email);
     // get caption depending of the gender
     $admirador_caption = 'un(a) admirador(a)';
     if ($currentUser->gender = 'F') {
         $admirador_caption = 'una admiradora';
     }
     if ($currentUser->gender = 'M') {
         $admirador_caption = 'un admirador';
     }
     $emails = $this->getEmailsFromRequest($request);
     if (!isset($emails[0])) {
         $response = new Response();
         $response->setResponseSubject('El nombre de usuario que te gusta no existe en Apretaste.');
         $response->createFromText('Indicaste un nombre de usuario que no existe en Apretaste. Para hacerlo debes escribir el nombre de usuario en el asunto seguido del texto CUIPIDO LIKE.');
         return $response;
     }
     $likes = array();
     $email = $emails[0];
     if (!$this->isMember($email)) {
         return $this->getNotMemberResponse($email);
     }
     // get the person whom you hit like
     $person = $this->utils->getPerson($email);
     if ($this->isLike($request->email, $email)) {
         $like = array('full_name' => $person->full_name, 'username' => $person->username, 'ya' => true);
     } else {
         $sql = "INSERT INTO relations (user1,user2,type,confirmed) VALUES ('{$request->email}','{$email}','like',1);";
         $this->db()->deepQuery($sql);
         // Generate a notification
         $this->utils->addNotification($email, 'cupido like', 'Tienes ' . $admirador_caption . '. Nuestro usuario @' . $currentUser->username . ' ha dicho que le gustas.', 'PERFIL @' . $currentUser->username);
         if (empty($person->full_name)) {
             $person->full_name = "@" . $person->username;
         }
         $like = array('full_name' => $person->full_name, 'username' => $person->username, 'ya' => false);
     }
     $user = $this->utils->getPerson($request->email);
     $response2 = new Response();
     $response2->setResponseEmail($email);
     $response2->setResponseSubject('Tienes ' . $admirador_caption);
     $response2->createFromTemplate("like_you.tpl", array('user' => $user));
     $response1 = new Response();
     $response1->setResponseSubject('Te gusta @' . $person->username);
     if (empty($user->full_name)) {
         $user->full_name = "@" . $user->username;
     }
     $response1->createFromTemplate('like.tpl', array('like' => $like, 'admirador' => $admirador_caption));
     return array($response1, $response2);
 }
Example #2
0
 /**
  * Get the list of conversations
  *
  * @param Request
  * @return Response
  * */
 public function _main(Request $request)
 {
     $argument = trim($request->query);
     $person = $this->utils->getPerson($request->email);
     // Extracting username and text
     $parts = explode(' ', $argument);
     $un = false;
     $nt = false;
     if (isset($parts[0]) && !empty($parts[0])) {
         $un = $parts[0];
     }
     if (isset($parts[1])) {
         $nt = trim(substr($argument, strlen($un)));
         if ($nt == '') {
             $nt = false;
         }
     }
     if ($un !== false) {
         if ($un[0] == '@') {
             $un = substr($un, 1);
         }
     }
     // Connecting to database
     $db = new Connection();
     // If subject's query is empty ...
     if ($un === false) {
         // Searching contacts of the current user
         $contacts = $db->deepQuery("SELECT (select username FROM person WHERE person.email = subq.username) as username,  \r\n\t\t\t\t\t\t\t\t\t\tsubq.username as email \r\n\t\t\t\t\t\t\t\t\t\tFROM (SELECT from_user as username FROM _note WHERE to_user = '******'\r\n\t\t\t\t\t\t\t\t\t\tUNION SELECT to_user as username FROM _note WHERE from_user = '******') as subq \r\n\t\t\t\t\t\t\t\t\t\tWHERE username <> '' AND username IS NOT NULL GROUP BY username");
         // Preparing contacts list
         if (is_array($contacts)) {
             foreach ($contacts as $k => $contact) {
                 $last_note = $this->getConversation($person->email, $contact->email, 1);
                 $contacts[$k]->last_note = array('from' => $last_note[0]->from_username, 'note' => $last_note[0]->text, 'date' => $last_note[0]->date);
             }
         }
         // Return the response
         $response = new Response();
         $response->setResponseSubject("Deseas enviar una nota?");
         $response->createFromTemplate("nouser.tpl", array("contacts" => $contacts));
         return $response;
     }
     // Searching the user $un in the database
     $friend = false;
     $find = $db->deepQuery("SELECT email FROM person WHERE username = '******';");
     // The user $un not exists
     if (!isset($find[0])) {
         $response = new Response();
         $response->setResponseSubject("El usuario @{$un} no existe");
         $response->createFromTemplate("user_not_exists.tpl", array("username" => $un));
         return $response;
     }
     $friend = $this->utils->getPerson($find[0]->email);
     // Sending the note
     if ($nt !== false) {
         if ($nt == 'Reemplace este texto por su nota') {
             $response = new Response();
             $response->setResponseSubject("No reemplazaste el texto por tu nota");
             $response->createFromTemplate("howto.tpl", array());
             return $response;
         }
         // Store note in database
         $db->deepQuery("INSERT INTO _note (from_user, to_user, text) VALUES ('{$request->email}','{$friend->email}','{$nt}');");
         // Retrieve notes between users
         $notes = $this->getConversation($person->email, $friend->email);
         // Response for friend
         $response = new Response();
         $response->setResponseEmail($friend->email);
         $response->setResponseSubject("Nueva nota de @{$person->username}");
         $response->createFromTemplate("basic.tpl", array('username' => $person->username, 'notes' => $notes));
         // Generate a notification
         $this->utils->addNotification($request->email, 'nota', "Enviamos su nota a @{$un}", 'NOTA');
         return $response;
     }
     // Empty note, sending conversation...
     $notes = $this->getConversation($person->email, $friend->email);
     $response = new Response();
     $response->setResponseSubject("Su charla con @{$friend->username}");
     $response->createFromTemplate("basic.tpl", array('username' => $friend->username, 'notes' => $notes));
     return $response;
 }
Example #3
0
 /**
  * Respond to a request based on the parameters passed
  *
  * @author salvipascual
  * @param String, email
  * @param String
  * @param String, email
  * @param String
  * @param Array of Objects {type,content,path}
  * @param Enum: html,json,email
  * @param String, email
  * @param String $messageID
  * */
 private function renderResponse($email, $fromEmail, $subject, $sender = "", $body = "", $attachments = array(), $format = "html", $messageID = NULL)
 {
     // get the time when the service started executing
     $execStartTime = date("Y-m-d H:i:s");
     // remove double spaces and apostrophes from the subject
     // sorry apostrophes break the SQL code :-(
     $subject = trim(preg_replace('/\\s{2,}/', " ", preg_replace('/\'|`/', "", $subject)));
     // get the name of the service based on the subject line
     $subjectPieces = explode(" ", $subject);
     $serviceName = strtolower($subjectPieces[0]);
     unset($subjectPieces[0]);
     // check the service requested actually exists
     $utils = new Utils();
     $connection = new Connection();
     // select the default service if service does not exist
     $alias = $serviceName;
     if (!$utils->serviceExist($serviceName)) {
         $serviceName = $utils->getDefaultService($fromEmail);
     } else {
         if ($serviceName !== $alias) {
             // increase the counter for alias
             $connection->deepQuery("UPDATE service_alias SET used = used + 1 WHERE alias = '{$alias}';");
         }
     }
     // update topics if you are contacting via the secure API
     if ($serviceName == "secured") {
         // disregard any footer message and decript new subject
         $message = trim(explode("--", $body)[0]);
         $subject = $utils->decript($email, $message);
         // get the name of the service based on the subject line
         $subjectPieces = explode(" ", $subject);
         $serviceName = strtolower($subjectPieces[0]);
         unset($subjectPieces[0]);
         // if the service don't exist, throw an error and exit
         if (!$utils->serviceExist($serviceName)) {
             error_log("Service {$serviceName} do not exist");
             exit;
         }
     }
     // include the service code
     $wwwroot = $this->di->get('path')['root'];
     include "{$wwwroot}/services/{$serviceName}/service.php";
     // check if a subservice is been invoked
     $subServiceName = "";
     if (isset($subjectPieces[1]) && !preg_match('/\\?|\\(|\\)|\\\\|\\/|\\.|\\$|\\^|\\{|\\}|\\||\\!/', $subjectPieces[1])) {
         $serviceClassMethods = get_class_methods($serviceName);
         if (preg_grep("/^_{$subjectPieces[1]}\$/i", $serviceClassMethods)) {
             $subServiceName = strtolower($subjectPieces[1]);
             unset($subjectPieces[1]);
         }
     }
     // get the service query
     $query = implode(" ", $subjectPieces);
     // create a new Request object
     $request = new Request();
     $request->email = $email;
     $request->name = $sender;
     $request->subject = $subject;
     $request->body = $body;
     $request->attachments = $attachments;
     $request->service = $serviceName;
     $request->subservice = trim($subServiceName);
     $request->query = trim($query);
     // get the path to the service
     $servicePath = $utils->getPathToService($serviceName);
     // get details of the service
     if ($this->di->get('environment') == "sandbox") {
         // get details of the service from the XML file
         $xml = simplexml_load_file("{$servicePath}/config.xml");
         $serviceCreatorEmail = trim((string) $xml->creatorEmail);
         $serviceDescription = trim((string) $xml->serviceDescription);
         $serviceCategory = trim((string) $xml->serviceCategory);
         $serviceUsageText = trim((string) $xml->serviceUsage);
         $showAds = isset($xml->showAds) && $xml->showAds == 0 ? 0 : 1;
         $serviceInsertionDate = date("Y/m/d H:m:s");
     } else {
         // get details of the service from the database
         $sql = "SELECT * FROM service WHERE name = '{$serviceName}'";
         $result = $connection->deepQuery($sql);
         $serviceCreatorEmail = $result[0]->creator_email;
         $serviceDescription = $result[0]->description;
         $serviceCategory = $result[0]->category;
         $serviceUsageText = $result[0]->usage_text;
         $serviceInsertionDate = $result[0]->insertion_date;
         $showAds = $result[0]->ads == 1;
     }
     // create a new service Object of the user type
     $userService = new $serviceName();
     $userService->serviceName = $serviceName;
     $userService->serviceDescription = $serviceDescription;
     $userService->creatorEmail = $serviceCreatorEmail;
     $userService->serviceCategory = $serviceCategory;
     $userService->serviceUsage = $serviceUsageText;
     $userService->insertionDate = $serviceInsertionDate;
     $userService->pathToService = $servicePath;
     $userService->showAds = $showAds;
     $userService->utils = $utils;
     // run the service and get a response
     if (empty($subServiceName)) {
         $response = $userService->_main($request);
     } else {
         $subserviceFunction = "_{$subServiceName}";
         $response = $userService->{$subserviceFunction}($request);
     }
     // a service can return an array of Response or only one.
     // we always treat the response as an array
     $responses = is_array($response) ? $response : array($response);
     // adding extra responses from Utils
     $extraResponses = Utils::getExtraResponses();
     $responses = array_merge($responses, $extraResponses);
     Utils::clearExtraResponses();
     // clean the empty fields in the response
     foreach ($responses as $rs) {
         $rs->email = empty($rs->email) ? $email : $rs->email;
         // check if is first request of the day
         $requestsToday = $utils->getTotalRequestsTodayOf($rs->email);
         $stars = 0;
         if ($requestsToday == 0) {
             // run the tickets's game
             // @note: este chequeo se hace despues de verificar si es el primer
             // correo del dia, para no preguntar chequear mas veces
             // innecesariamente en el resto del dia
             $stars = $utils->getRaffleStarsOf($rs->email, false);
             if ($stars === 4) {
                 // insert 10 tickets for user
                 $sqlValues = "('{$email}', 'GAME')";
                 $sql = "INSERT INTO ticket(email, origin) VALUES " . str_repeat($sqlValues . ",", 9) . "{$sqlValues};";
                 $connection->deepQuery($sql);
                 // add notification to user
                 $utils->addNotification($rs->email, "GAME", "Haz ganado 10 tickets para Rifa por utilizar Apretaste durante 5 d&iacute;as seguidos", "RIFA", "IMPORTANT");
             }
             $stars++;
         }
         $rs->subject = empty($rs->subject) ? "Respuesta del servicio {$serviceName}" : $rs->subject;
         $rs->content['num_notifications'] = $utils->getNumberOfNotifications($rs->email);
         $rs->content['raffle_stars'] = $stars;
         $rs->content['requests_today'] = $requestsToday;
     }
     // create a new render
     $render = new Render();
     // render the template and echo on the screen
     if ($format == "html") {
         $html = "";
         for ($i = 0; $i < count($responses); $i++) {
             $html .= "<br/><center><small><b>To:</b> " . $responses[$i]->email . ". <b>Subject:</b> " . $responses[$i]->subject . "</small></center><br/>";
             $html .= $render->renderHTML($userService, $responses[$i]);
             if ($i < count($responses) - 1) {
                 $html .= "<br/><hr/><br/>";
             }
         }
         $usage = nl2br(str_replace('{APRETASTE_EMAIL}', $utils->getValidEmailAddress(), $serviceUsageText));
         $html .= "<br/><hr><center><p><b>XML DEBUG</b></p><small>";
         $html .= "<p><b>Owner: </b>{$serviceCreatorEmail}</p>";
         $html .= "<p><b>Category: </b>{$serviceCategory}</p>";
         $html .= "<p><b>Description: </b>{$serviceDescription}</p>";
         $html .= "<p><b>Usage: </b><br/>{$usage}</p></small></center>";
         return $html;
     }
     // echo the json on the screen
     if ($format == "json") {
         return $render->renderJSON($response);
     }
     // render the template email it to the user
     // only save stadistics for email requests
     if ($format == "email") {
         // get the person, false if the person does not exist
         $person = $utils->getPerson($email);
         // if the person exist in Apretaste
         if ($person !== false) {
             // update last access time to current and make person active
             $connection->deepQuery("UPDATE person SET active=1, last_access=CURRENT_TIMESTAMP WHERE email='{$email}'");
         } else {
             $inviteSource = 'alone';
             // alone if the user came by himself, no invitation
             $sql = "START TRANSACTION;";
             // start the long query
             // check if the person was invited to Apretaste
             $invites = $connection->deepQuery("SELECT * FROM invitations WHERE email_invited='{$email}' AND used=0 ORDER BY invitation_time DESC");
             if (count($invites) > 0) {
                 // check how this user came to know Apretaste, for stadistics
                 $inviteSource = $invites[0]->source;
                 // give prizes to the invitations via service invitar
                 // if more than one person invites X, they all get prizes
                 foreach ($invites as $invite) {
                     switch ($invite->source) {
                         case "internal":
                             // assign tickets and credits
                             $sql .= "INSERT INTO ticket (email, origin) VALUES ('{$invite->email_inviter}', 'RAFFLE');";
                             $sql .= "UPDATE person SET credit=credit+0.25 WHERE email='{$invite->email_inviter}';";
                             // email the invitor
                             $newTicket = new Response();
                             $newTicket->setResponseEmail($invite->email_inviter);
                             $newTicket->setEmailLayout("email_simple.tpl");
                             $newTicket->setResponseSubject("Ha ganado un ticket para nuestra Rifa");
                             $newTicket->createFromTemplate("invitationWonTicket.tpl", array("guest" => $email));
                             $newTicket->internal = true;
                             $responses[] = $newTicket;
                             break;
                         case "abroad":
                             $newGuest = new Response();
                             $newGuest->setResponseEmail($invite->email_inviter);
                             $newGuest->setResponseSubject("Tu amigo ha atendido tu invitacion");
                             $inviter = $utils->usernameFromEmail($invite->email_inviter);
                             $pInviter = $utils->getPerson($invite->email_inviter);
                             if (!isset($pInviter->name)) {
                                 $pInviter->name = '';
                             }
                             if ($pInviter !== false) {
                                 if (trim($pInviter->name) !== '') {
                                     $inviter = $pInviter->name;
                                 }
                             }
                             $pGuest = $utils->getPerson($email);
                             $guest = $email;
                             if ($pGuest !== false) {
                                 $guest = $pGuest->username;
                             }
                             $newGuest->createFromTemplate("invitationNewGuest.tpl", array("inviter" => $inviter, "guest" => $guest, "guest_email" => $email));
                             $newGuest->internal = true;
                             $responses[] = $newGuest;
                             break;
                     }
                 }
                 // mark all opened invitations to that email as used
                 $sql .= "UPDATE invitations SET used=1, used_time=CURRENT_TIMESTAMP WHERE email_invited='{$email}' AND used=0;";
             }
             // create a unique username and save the new person
             $username = $utils->usernameFromEmail($email);
             $sql .= "INSERT INTO person (email, username, last_access, source) VALUES ('{$email}', '{$username}', CURRENT_TIMESTAMP, '{$inviteSource}');";
             // save details of first visit
             $sql .= "INSERT INTO first_timers (email, source) VALUES ('{$email}', '{$fromEmail}');";
             // check list of promotor's emails
             $promoters = $connection->deepQuery("SELECT email FROM promoters WHERE email='{$fromEmail}' AND active=1;");
             $prize = count($promoters) > 0;
             if ($prize) {
                 // update the promotor
                 $sql .= "UPDATE promoters SET `usage`=`usage`+1, last_usage=CURRENT_TIMESTAMP WHERE email='{$fromEmail}';";
                 // add credit and tickets
                 $sql .= "UPDATE person SET credit=credit+5, source='promoter' WHERE email='{$email}';";
                 $sqlValues = "('{$email}', 'PROMOTER')";
                 $sql .= "INSERT INTO ticket(email, origin) VALUES " . str_repeat($sqlValues . ",", 9) . "{$sqlValues};";
             }
             // run the long query all at the same time
             $connection->deepQuery($sql . "COMMIT;");
             // send the welcome email
             $welcome = new Response();
             $welcome->setResponseEmail($email);
             $welcome->setEmailLayout("email_simple.tpl");
             $welcome->setResponseSubject("Bienvenido a Apretaste!");
             $welcome->createFromTemplate("welcome.tpl", array("email" => $email, "prize" => $prize, "source" => $fromEmail));
             $welcome->internal = true;
             $responses[] = $welcome;
         }
         // create and configure to send email
         $emailSender = new Email();
         $emailSender->setRespondEmailID($messageID);
         $emailSender->setEmailGroup($fromEmail);
         // get params for the email and send the response emails
         foreach ($responses as $rs) {
             if ($rs->render) {
                 // save impressions in the database
                 $ads = $rs->getAds();
                 if ($userService->showAds && !empty($ads)) {
                     $sql = "";
                     if (!empty($ads[0])) {
                         $sql .= "UPDATE ads SET impresions=impresions+1 WHERE id='{$ads[0]->id}';";
                     }
                     if (!empty($ads[1])) {
                         $sql .= "UPDATE ads SET impresions=impresions+1 WHERE id='{$ads[1]->id}';";
                     }
                     $connection->deepQuery($sql);
                 }
                 // prepare the email variable
                 $emailTo = $rs->email;
                 $subject = $rs->subject;
                 $images = $rs->images;
                 $attachments = $rs->attachments;
                 $body = $render->renderHTML($userService, $rs);
                 // remove dangerous characters that may break the SQL code
                 $subject = trim(preg_replace('/\'|`/', "", $subject));
                 // send the response email
                 $emailSender->sendEmail($emailTo, $subject, $body, $images, $attachments);
             }
         }
         // saves the openning date if the person comes from remarketing
         $connection->deepQuery("UPDATE remarketing SET opened=CURRENT_TIMESTAMP WHERE opened IS NULL AND email='{$email}'");
         // calculate execution time when the service stopped executing
         $currentTime = new DateTime();
         $startedTime = new DateTime($execStartTime);
         $executionTime = $currentTime->diff($startedTime)->format('%H:%I:%S');
         // get the user email domainEmail
         $emailPieces = explode("@", $email);
         $domain = $emailPieces[1];
         // get the top and bottom Ads
         $ads = isset($responses[0]->ads) ? $responses[0]->ads : array();
         $adTop = isset($ads[0]) ? $ads[0]->id : "NULL";
         $adBottom = isset($ads[1]) ? $ads[1]->id : "NULL";
         // save the logs on the utilization table
         $safeQuery = $connection->escape($query);
         $sql = "INSERT INTO utilization\t(service, subservice, query, requestor, request_time, response_time, domain, ad_top, ad_bottom) VALUES ('{$serviceName}','{$subServiceName}','{$safeQuery}','{$email}','{$execStartTime}','{$executionTime}','{$domain}',{$adTop},{$adBottom})";
         $connection->deepQuery($sql);
         // return positive answer to prove the email was quequed
         return true;
     }
     // false if no action could be taken
     return false;
 }
Example #4
0
 /**
  * Subservice PUBLICAR
  *
  * @param Request $request        	
  */
 public function _publicar($request)
 {
     $connection = new Connection();
     $title = substr(trim($request->query), 0, 100);
     $body = substr(trim($request->body), 0, 1000);
     if ($title == '') {
         $title = substr($body, 0, 100);
     }
     $title = $connection->escape($title);
     $body = $connection->escape($body);
     $title = str_replace("'", '\\' . "'", $title);
     $body = str_replace("'", '\\' . "'", $body);
     $hash = $this->utils->generateRandomHash();
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     $wwwroot = $di->get('path')['root'];
     // insert new ad with a year of life
     $connection->deepQuery("INSERT INTO ads (title,description,owner,expiration_date) VALUES ('{$title}','{$body}','{$request->email}',DATE_ADD(CURRENT_DATE, INTERVAL 1 YEAR));");
     // get id of the new ad inserted
     $id = $connection->deepQuery("SELECT id FROM ads WHERE owner = '{$request->email}' ORDER BY time_inserted DESC LIMIT 100;");
     $id = $id[0]->id;
     // insert one image for the ad
     foreach ($request->attachments as $at) {
         if (isset($at->type) && strpos("jpg,jpeg,image/jpg,image/jpeg,image/png,png,image/gif,gif", $at->type) !== false && isset($at->path)) {
             // save the image
             $img = file_get_contents($at->path);
             $filePath = "{$wwwroot}/public/ads/" . md5($id) . ".jpg";
             file_put_contents($filePath, $img);
             // optimize the image
             $this->utils->optimizeImage($filePath);
             // only first image
             break;
         }
     }
     // respond to the owner of the ad
     $response = new Response();
     $response->setResponseSubject("Su anuncio ha sido agregado");
     $response->createFromTemplate('publish.tpl', array('id' => $id, 'userEmail' => $request->email));
     // alert us about the new ad
     $alert = new Response();
     $alert->setResponseEmail("*****@*****.**");
     $alert->setEmailLayout("email_simple.tpl");
     $alert->setResponseSubject('Nueva publicidad en Apretaste');
     $alert->createFromTemplate('notify.tpl', array('owner' => $request->email, 'title' => $title, 'body' => $body));
     return array($response, $alert);
 }
Example #5
0
 /**
  * To list lastest notes or post a new note
  *
  * @param Request
  * @return Response
  */
 public function _main(Request $request)
 {
     if ($request->query == "reemplace este texto por su nota") {
         $response = new Response();
         $responseContent = array("message" => 'Para que podamos escribir su nota, &iexcl;Usted primero debe escribirla!</p><p>Por favor presione el bot&oacute;n m&oacute;s abajo y reemplace en el asunto del email donde dice <b>"reemplace este texto por su nota"</b> con el texto a escribir e intente nuevamente.');
         $response->setResponseSubject("No nos ha enviado ninguna nota!");
         $response->createFromTemplate("message.tpl", $responseContent);
         return $response;
     }
     // connect to the database
     $connection = new Connection();
     $email = $request->email;
     // get the user from the database
     $res = $connection->deepQuery("SELECT username FROM person WHERE email='{$email}'");
     $user = null;
     if (isset($res[0])) {
         $user = $res[0]->username;
     }
     // post whatever the user types
     if (!empty($request->query)) {
         // do not post notes without real information like empty mentions
         if (strlen($request->query) < 16) {
             return new Response();
         }
         // emails in text
         $emailsMentioned = $this->getAddressFrom($request->query);
         if (is_array($emailsMentioned)) {
             foreach ($emailsMentioned as $em) {
                 $person = $this->utils->getPerson($em);
                 if ($person !== false) {
                     $request->query = str_replace($em, '@' . $person->username, $request->query);
                 }
             }
         }
         // save note to the database
         $text = substr($request->query, 0, 130);
         $text = $connection->escape($text);
         $connection->deepQuery("INSERT INTO _pizarra_notes (email, text) VALUES ('{$email}', '{$text}')");
         // search for mentions and alert the user mentioned
         $mentions = $this->findUsersMentionedOnText($request->query);
         $usersMentioned = "";
         foreach ($mentions as $mention) {
             // do not allow self-mentioning
             if ($mention[0] == $user) {
                 continue;
             }
             // save the list of users mentioned
             $usersMentioned .= "@" . $mention[0] . ", ";
             // email the user mentioned
             $responseContent = array("message" => "El usuario <b>@{$user}</b> le ha mencionado en una nota escrita en la pizarra. La nota se lee a continuaci&oacute;n:<br/><br/><br/>{$request->query}");
             $response = new Response();
             $response->setResponseEmail($mention[1]);
             // email the user mentioned
             $response->setResponseSubject("Han mencionado su nombre en la pizarra");
             $response->createFromTemplate("message.tpl", $responseContent);
             $responses[] = $response;
             // generate a notification
             $this->utils->addNotification($mention[1], 'pizarra', "<b>@{$user}</b> le ha mencionado en Pizarra.<br/>&gt;{$request->query}", 'PIZARRA BUSCAR @' . $user, 'IMPORTANT');
         }
         // post in tweeter
         $text = trim(str_replace(" @", " ", $text), "@");
         // remove @usernames for twitter
         $twitter = new TwitterOAuth($this->KEY, $this->KEY_SECRET, $this->TOKEN, $this->TOKEN_SECRET);
         try {
             $twitter->post("statuses/update", array("status" => "{$user}~> {$text}"));
         } catch (Exception $e) {
         }
         // save a notificaction
         $this->utils->addNotification($request->email, 'pizarra', 'Su nota ha sido publicada en Pizarra', 'PIZARRA');
         // do not return any response when posting
         return new Response();
     }
     // get the last 50 records from the db
     $listOfNotes = $connection->deepQuery("\n\t\t\tSELECT \r\n\t\t\t\tA.*, B.username, B.first_name, B.last_name, B.province, B.picture, B.gender,\r\n\t\t\t\tA.likes*0.5 as loved,\r\n\t\t\t\tDATEDIFF(inserted,CURRENT_DATE)+7 as days,\r\n\t\t\t\t(SELECT COUNT(user1) FROM relations WHERE user1='{$request->email}' AND user2 = A.email AND type = 'follow') * 3 AS friend,\r\n\t\t\t\t(SELECT COUNT(user1) FROM relations WHERE user2 = A.email AND type = 'follow') * 3 AS popular,\r\n\t\t\t\tRAND() as luck,\r\n\t\t\t\t(SELECT count(*) FROM _pizarra_seen_notes WHERE _pizarra_seen_notes.email = '{$request->email}' AND _pizarra_seen_notes.note = A.id) * 3 as seen\r\n\t\t\tFROM _pizarra_notes A\r\n\t\t\tLEFT JOIN person B\r\n\t\t\tON A.email = B.email\r\n\t\t\tWHERE A.email NOT IN (SELECT user2 FROM relations WHERE user1 = '{$request->email}' and type = 'blocked')\r\n\t\t\tAND A.email NOT IN (SELECT relations.user2 FROM relations WHERE relations.user1 = '{$request->email}' AND relations.type = 'blocked')\r\n\t\t\tAND A.email <> '{$request->email}'\r\n\t\t\tORDER BY inserted DESC\r\n\t\t\tLIMIT 300");
     // sort results by weight. Too complex and slow in MySQL
     function cmp($a, $b)
     {
         $one = $a->loved + $a->days + $a->friend + $a->popular + $a->luck - $a->seen;
         $two = $b->loved + $b->days + $b->friend + $b->popular + $b->luck - $b->seen;
         if ($one == $two) {
             return 0;
         }
         return $one > $two ? -1 : 1;
     }
     usort($listOfNotes, "cmp");
     // format the array of notes
     $emails = array();
     $notes = array();
     foreach ($listOfNotes as $note) {
         // only accept the first 5 notes per person
         if (!isset($emails[$note->email])) {
             $emails[$note->email] = 1;
         } elseif ($emails[$note->email] < 3) {
             $emails[$note->email]++;
         } else {
             continue;
         }
         // get the name
         $name = trim("{$note->first_name} {$note->last_name}");
         if (empty($name)) {
             $name = $note->email;
         }
         // get the location
         if (empty($note->province)) {
             $location = "Cuba";
         } else {
             $location = ucwords(strtolower(str_replace("_", " ", $note->province)));
         }
         // highlight usernames and link it to NOTA
         $note->text = $this->hightlightUsernames($note->text, $user);
         // add the text to the array
         $notes[] = array("id" => $note->id, "name" => $note->username, "location" => $location, "gender" => $note->gender, "picture" => $note->picture, "text" => $note->text, "inserted" => date("Y-m-d H:i:s", strtotime($note->inserted)), "likes" => $note->likes, 'source' => $note->source, 'email' => $note->email, "friend" => $note->friend > 0);
         // check as seen
         $connection->deepQuery("INSERT IGNORE INTO _pizarra_seen_notes (note, email) VALUES ('{$note->id}', '{$request->email}');");
         // only parse the first 50 notes
         if (count($notes) > 50) {
             break;
         }
     }
     // highlight hash tags
     for ($i = 0; $i < count($notes); $i++) {
         $notes[$i]['text'] = ucfirst(strtolower($notes[$i]['text']));
         // fix case
         $notes[$i]['text'] = $this->highlightHashTags($notes[$i]['text']);
     }
     // get the likes, follows and blocks
     $likes = $connection->deepQuery("SELECT SUM(likes) as likes FROM _pizarra_notes WHERE email='{$email}'")[0]->likes;
     $follows = $connection->deepQuery("SELECT COUNT(*) as follows FROM relations WHERE user2='{$email}'")[0]->follows;
     $blocks = $connection->deepQuery("SELECT COUNT(*) as blocks FROM relations WHERE user2='{$email}'")[0]->blocks;
     // get last note
     $lastnote = $connection->deepQuery("SELECT * FROM _pizarra_notes WHERE email = '{$email}' ORDER BY inserted DESC LIMIT 1 OFFSET 0;");
     if (!isset($lastnote[0])) {
         $lastnote = false;
     } else {
         $lastnote = $lastnote[0];
     }
     // create variables for the template
     $responseContent = array("likes" => $likes, "follows" => $follows, "blocks" => $blocks, "isProfileIncomplete" => $this->utils->getProfileCompletion($email) < 70, "notes" => $notes, "lastnote" => $lastnote, "username" => $user);
     // create the response
     $response = new Response();
     $response->setResponseSubject("Ultimas 50 notas");
     $response->createFromTemplate("pizarra.tpl", $responseContent);
     return $response;
 }