Example #1
0
 /**
  * Function called once this service is called
  * 
  * @param Request
  * @return Response
  * */
 public function _main(Request $request)
 {
     // do not allow blank searches
     if (empty($request->query)) {
         $response = new Response();
         $response->setResponseSubject("Debe insertar un texto a buscar");
         $response->createFromText("Usted no ha insertado ning&uacute;n texto a buscar en Wikipedia. Inserte el texto en el asunto del email, justo despu&eacute;s de la palabra WIKIPEDIA.<br/><br/>Por ejemplo: Asunto: WIKIPEDIA jose marti");
         return $response;
     }
     // find the right query in wikipedia
     $correctedQuery = $this->search($request->query);
     if (empty($correctedQuery)) {
         $response = new Response();
         $response->setResponseSubject("Su busqueda no produjo resultados");
         $response->createFromText("Su b&uacute;squeda <b>{$request->query}</b> no fue encontrada en Wikipedia. Por favor modifique el texto e intente nuevamente.");
         return $response;
     }
     // get the HTML code for the page
     $page = $this->get(urlencode($correctedQuery));
     // get the home image
     $imageName = empty($page['images']) ? false : $page['images'][0];
     // create a json object to send to the template
     $responseContent = array("title" => $page['title'], "body" => $page['body'], "image" => $imageName, "isLarge" => $page['isLarge']);
     // send the response to the template
     $response = new Response();
     $response->setResponseSubject("Wikipedia: {$page['title']}");
     $response->createFromTemplate("wikipedia.tpl", $responseContent, $page['images']);
     return $response;
 }
Example #2
0
 /**
  * Function executed when the service is called
  *
  * @param Request
  * @return Response
  * */
 public function _main(Request $request)
 {
     $response = new Response();
     $response->setResponseSubject("Terminos de uso de Apretaste");
     $response->createFromTemplate("basic.tpl", array());
     return $response;
 }
Example #3
0
 /**
  * Function executed when the service is called
  *
  * @param Request
  * @return Response
  * */
 public function _main($request)
 {
     // get list of services
     $connection = new Connection();
     $result = $connection->deepQuery("SELECT name, description, category FROM service WHERE listed=1");
     $services = array();
     $others = array();
     // to keep the categoty "others" at the end
     // create array of arrays
     foreach ($result as $res) {
         // to keep the categoty "others" at the end
         if ($res->category == "otros") {
             $others[] = $res;
             continue;
         }
         // group all other categories in a big array
         if (!isset($services[$res->category])) {
             $services[$res->category] = array();
         }
         array_push($services[$res->category], $res);
     }
     // sort by category alphabetically and merge to "other"
     ksort($services);
     $services = array_merge($services, array("otros" => $others));
     // get variables to send to the template
     $responseContent = array("services" => $services, "serviceNum" => count($result));
     // create response
     $response = new Response();
     $response->setResponseSubject("Lista de servicios de Apretaste");
     $response->createFromTemplate("basic.tpl", $responseContent);
     // return
     return $response;
 }
Example #4
0
 /**
  * Process the page when its submitted
  *
  * @author kuma, salvipascual
  * @version 1.0
  * */
 public function processAction()
 {
     // get the values from the post
     $captcha = trim($this->request->getPost('captcha'));
     $name = trim($this->request->getPost('name'));
     $inviter = trim($this->request->getPost('email'));
     $guest = trim($this->request->getPost('guest'));
     if (!isset($_SESSION['phrase'])) {
         $_SESSION['phrase'] = uniqid();
     }
     // throw a die()
     // check all values passed are valid
     if (strtoupper($captcha) != strtoupper($_SESSION['phrase']) || $name == "" || !filter_var($inviter, FILTER_VALIDATE_EMAIL) || !filter_var($guest, FILTER_VALIDATE_EMAIL)) {
         die("Error procesando, por favor valla atras y comience nuevamente.");
     }
     // params for the response
     $this->view->name = $name;
     $this->view->email = $inviter;
     // create classes needed
     $connection = new Connection();
     $email = new Email();
     $utils = new Utils();
     $render = new Render();
     // do not invite people who are already using Apretaste
     if ($utils->personExist($guest)) {
         $this->view->already = true;
         return $this->dispatcher->forward(array("controller" => "invitar", "action" => "index"));
     }
     // send notification to the inviter
     $response = new Response();
     $response->setResponseSubject("Gracias por darle internet a un Cubano");
     $response->setEmailLayout("email_simple.tpl");
     $response->createFromTemplate("invitationThankYou.tpl", array('num_notifications' => 0));
     $response->internal = true;
     $html = $render->renderHTML(new Service(), $response);
     $email->sendEmail($inviter, $response->subject, $html);
     // send invitations to the guest
     $response = new Response();
     $response->setResponseSubject("{$name} le ha invitado a revisar internet desde su email");
     $responseContent = array("host" => $name, "guest" => $guest, 'num_notifications' => 0);
     $response->createFromTemplate("invitation.tpl", $responseContent);
     $response->internal = true;
     $html = $render->renderHTML(new Service(), $response);
     $email->sendEmail($guest, $response->subject, $html);
     // save all the invitations into the database at the same time
     $connection->deepQuery("INSERT INTO invitations (email_inviter,email_invited,source) VALUES ('{$inviter}','{$guest}','abroad')");
     // redirect to the invite page
     $this->view->message = true;
     return $this->dispatcher->forward(array("controller" => "invitar", "action" => "index"));
 }
Example #5
0
 public function mainAction()
 {
     // inicialize supporting classes
     $timeStart = time();
     $connection = new Connection();
     $email = new Email();
     $service = new Service();
     $service->showAds = true;
     $render = new Render();
     $response = new Response();
     $wwwroot = $this->di->get('path')['root'];
     $log = "";
     // get people who did not finish a survey for the last 3 days
     $surveys = $connection->deepQuery("\n\t\t\tSELECT A.*, B.title, B.deadline, B.value FROM \n\t\t\t(\n\t\t\t\tSELECT email, survey,  \n\t\t\t\tDATEDIFF(CURRENT_DATE, MAX(date_choosen)) as days_since,\n\t\t\t\t(\n\t\t\t\t\tSELECT COUNT(*) \n\t\t\t\t\tFROM _survey_question \n\t\t\t\t\tWHERE _survey_question.survey = _survey_answer_choosen.survey\n\t\t\t\t) as total, \n\t\t\t\tCOUNT(question) as choosen from _survey_answer_choosen GROUP BY email, survey\n\t\t\t) A\n\t\t\tJOIN _survey B\n\t\t\tON A.survey = B.id\n\t\t\tWHERE A.total > A.choosen \n\t\t\tAND A.days_since >= 7\n\t\t\tAND B.active = 1\n\t\t\tAND DATEDIFF(B.deadline, B.date_created) > 0\n\t\t\tAND A.email NOT IN (SELECT DISTINCT email FROM remarketing WHERE type='SURVEY')");
     // send emails to users
     $log .= "\nSURVEY REMARKETING (" . count($surveys) . ")\n";
     foreach ($surveys as $survey) {
         $content = array("survey" => $survey->survey, "days" => $survey->days_since, "missing" => $survey->total - $survey->choosen, "title" => $survey->title, "deadline" => $survey->deadline, "value" => $survey->value);
         // create html response
         $response->setResponseSubject("No queremos que pierda \${$survey->value}");
         $response->createFromTemplate('surveyReminder.tpl', $content);
         $response->internal = true;
         // send email to the person
         $html = $render->renderHTML($service, $response);
         $email->sendEmail($survey->email, $response->subject, $html);
         // add entry to remarketing
         $connection->deepQuery("INSERT INTO remarketing(email, type) VALUES ('{$survey->email}', 'SURVEY');");
         // display notifications
         $log .= "\t{$survey->email} | surveyID: {$survey->survey} \n";
     }
     // get final delay
     $timeEnd = time();
     $timeDiff = $timeEnd - $timeStart;
     // printing log
     $log .= "EXECUTION TIME: {$timeDiff} seconds\n\n";
     echo $log;
     // saving the log
     $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/surveyreminder.log");
     $logger->log($log);
     $logger->close();
     // save the status in the database
     $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='survey'");
 }
Example #6
0
 public function _lista(Request $request)
 {
     $max = intval($request->query);
     if ($max > 10000) {
         $response = new Response();
         $response->setResponseSubject("Numero demasiado grande para procesar");
         $response->createFromText("El numero {$max} es demasiado grande para procesar la lista de primos.");
         return $response;
     }
     $primos = array();
     for ($i = 1; $i <= $max; $i++) {
         if ($this->esPrimo($i)) {
             $primos[] = $i;
         }
     }
     $response = new Response();
     $response->setResponseSubject("Lista de numeros primos hasta el {$max}");
     $response->createFromTemplate("lista.tpl", array("primos" => $primos, "max" => $max));
     return $response;
 }
Example #7
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 #8
0
 /**
  * Search and return based on number of results
  * 
  * @author salvipascual
  * */
 private function getResponseBasedOnNumberOfResults(Request $request, $numberOfResults)
 {
     // if the search is empty, return a message to the user
     if (empty($request->query)) {
         $serviceUsage = str_replace("{APRETASTE_EMAIL}", $this->utils->getValidEmailAddress(), nl2br($this->serviceUsage));
         $response = new Response();
         $response->setResponseSubject("Inserte un producto o servicio a buscar");
         $response->createFromText("Usted no ha insertado ning&uacute;n producto o servicio a buscar, use nuestra tienda de la siguiente manera:<br/><br/><br/>{$serviceUsage}");
         return $response;
     }
     // search for the results of the query
     $searchResult = $this->search($request->query, $numberOfResults);
     $count = $searchResult['count'];
     $items = $searchResult['items'];
     // return error to the user if no items were found
     if (count($items) == 0) {
         $response = new Response();
         $response->setResponseSubject("Su busqueda no produjo resultados");
         $response->createFromText("Su b&uacute;squeda '{$request->query}' no produjo ning&uacute;n resultado. Por favor utilice otra frase de b&uacute;squeda e intente nuevamente.");
         return $response;
     }
     // get the path
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     $wwwroot = $di->get('path')['root'];
     // check if is a buscar or buscartodo
     $isSimpleSearch = $numberOfResults <= 10;
     // clean the text and save the images
     $images = array();
     foreach ($items as $item) {
         // clean the text
         $item->ad_title = $this->clean($item->ad_title);
         $item->ad_body = $this->clean($item->ad_body);
         // save images if 10 results
         if ($isSimpleSearch) {
             if ($item->number_of_pictures == 0) {
                 continue;
             }
             $file = "{$wwwroot}/public/tienda/" . md5($item->source_url) . "_1.jpg";
             if (file_exists($file)) {
                 $images[] = $file;
             }
         }
     }
     // select template
     $template = $isSimpleSearch ? "buscar.tpl" : "buscartodo.tpl";
     // send variables to the template
     $responseContent = array("numberOfDisplayedResults" => $isSimpleSearch ? count($items) > 10 ? 10 : count($items) : count($items), "numberOfTotalResults" => $count, "searchQuery" => $request->query, "items" => $items, "wwwroot" => $wwwroot);
     // display the results in the template
     $response = new Response();
     $response->setResponseSubject("La busqueda que usted pidio");
     $response->createFromTemplate($template, $responseContent, $images);
     return $response;
 }
Example #9
0
 /**
  * Subservice utility for ENUM profile fields
  *
  * @param Request $request			
  * @param String $field			
  * @param array $enum			
  * @param String $wrong_template			
  * @param String $wrong_subject			
  * @param String $field			
  *
  * @return Response/void
  */
 private function subserviceEnum(Request $request, $field, $enum, $wrong_subject, $prefix = null, $synonymous = array())
 {
     if (!is_null($prefix)) {
         if (stripos($request->query, $prefix) === 0) {
             $request->query = trim(substr($request->query, strlen($prefix)));
         }
     }
     $query = strtoupper(trim($request->query));
     // if the query is empty, set to null the field
     if (empty($query)) {
         return new Response();
     } else {
         // search for $synonymous
         if (isset($synonymous[$query])) {
             $query = $synonymous[$query];
         }
         // search query in the list
         if (array_search($query, $enum) !== false) {
             // update the field
             $this->update("{$field} = '{$query}'", $request->email);
             return new Response();
         } else {
             // wrong query, return a response with selectable list
             $response = new Response();
             $response->setResponseSubject($wrong_subject);
             // NOTE: The template name include the field name
             // clear underscores
             foreach ($enum as $k => $v) {
                 $enum[$k] = str_replace('_', ' ', $v);
             }
             $response->createFromTemplate('wrong_' . $field . '.tpl', array('list' => $enum));
             return $response;
         }
     }
 }
Example #10
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 #11
0
 /**
  * A test for a subservice WIKIPEDIA
  * */
 function _test(Request $request)
 {
     $response = new Response();
     $response->setResponseSubject("Just a test for subservice");
     $response->createFromText("A test for the subservice WIKIPEDIA");
     return $response;
 }
Example #12
0
 /**
  * Common response
  *
  * @author kuma
  * @param string $title
  * @param string $url
  * @return Response
  */
 private function commonImageResponse($title, $url)
 {
     // download and prepare the image
     $image = $this->downloadAndPrepareImage($url);
     // create response
     $response = new Response();
     $response->setResponseSubject("Clima: " . html_entity_decode($title));
     $response->createFromTemplate("image.tpl", array("title" => $title, "image" => $image), array($image));
     return $response;
 }
Example #13
0
 /**
  * Return Survey response
  *
  * @param Request $request			
  * @param integer $survey_id			
  * @return Response
  */
 private function surveyResponse($request, $survey_id)
 {
     $survey = $this->getSurveyDetails($request->email, $survey_id);
     // do not process invalid responses
     if ($survey == false || !isset($survey[0]) || empty($survey)) {
         return new Response();
     }
     $newsurvey = new stdClass();
     $newsurvey->id = $survey[0]->survey;
     $newsurvey->title = $survey[0]->survey_title;
     $newsurvey->details = $survey[0]->survey_details;
     $newsurvey->questions = array();
     foreach ($survey as $r) {
         if (!isset($newsurvey->questions[$r->question])) {
             $obj = new stdClass();
             $obj->id = $r->question;
             $obj->title = $r->question_title;
             $obj->answers = array();
             $obj->selectable = true;
             $newsurvey->questions[$r->question] = $obj;
         }
         $obj = new stdClass();
         $obj->id = $r->answer;
         $obj->title = $r->answer_title;
         $obj->choosen = $r->choosen == '1' ? true : false;
         if ($obj->choosen) {
             $newsurvey->questions[$r->question]->selectable = false;
         }
         $newsurvey->questions[$r->question]->answers[] = $obj;
     }
     $response = new Response();
     $response->setResponseSubject('Encuesta: ' . $newsurvey->title);
     $response->createFromTemplate('survey.tpl', array('survey' => $newsurvey));
     return $response;
 }
Example #14
0
 /**
  * List of businesses that accept bitcoin
  *
  * @param Request
  * @return Response
  * */
 public function _negocios(Request $request)
 {
     // @TODO remove bulshit answer to use the service
     $response = new Response();
     $response->setResponseSubject("Bitcoin temporalmente no disponible");
     $response->createFromText("Lo sentimos, pero Bitcoin esta temporalmente detenido. Le dejaremos saber cuando empecemos a funcionar. Gracias!");
     return $response;
     // END TODO
     $path = $this->pathToService;
     $images = array("{$path}/images/airbnb.jpg", "{$path}/images/carnival.jpg", "{$path}/images/virgin-atlantic.jpg", "{$path}/images/unilever.jpg", "{$path}/images/netflix.png", "{$path}/images/DimeCuba.jpg");
     $response = new Response();
     $response->setResponseSubject("Negocios que aceptan BitCoin");
     $response->createFromTemplate("negocios.tpl", array("path" => $path), $images);
     return $response;
 }
Example #15
0
 /**
  * Subservice ESTADISTICAS
  *
  * @param Request $request        	
  * @return Response
  */
 public function _estadisticas(Request $request)
 {
     // get list of ads for the user
     $connection = new Connection();
     $result = $connection->deepQuery("SELECT * FROM ads WHERE owner = '{$request->email}' ORDER BY id");
     // list all the ads
     if (count($result) > 0) {
         $response = new Response();
         $response->setResponseSubject('Sus anuncios en Apretaste');
         $response->createFromTemplate('stats.tpl', array('stats' => $result));
         return $response;
     }
     // in case the user don't have any ads
     $response = new Response();
     $response->setResponseSubject('Usted no tiene anuncio corriendo');
     $response->createFromText('Usted no tiene ningun anuncio en Apretaste');
     return $response;
 }
Example #16
0
 /**
  * Recovers a pin and create a pin for users with blank pins
  *
  * @author salvipascual
  * @param GET email
  * @return JSON
  * */
 public function recoverAction()
 {
     $email = trim($this->request->get('email'));
     $utils = new Utils();
     $connection = new Connection();
     // check if the email exist
     if (!$utils->personExist($email)) {
         die('{"code":"error","message":"invalid user"}');
     }
     // get pin from the user
     $pin = $connection->deepQuery("SELECT pin FROM person WHERE email='{$email}'");
     $pin = $pin[0]->pin;
     // if pin is blank, create it
     if (empty($pin)) {
         $pin = mt_rand(1000, 9999);
         $connection->deepQuery("UPDATE person SET pin='{$pin}' WHERE email='{$email}'");
     }
     // create response to email the new code
     $subject = "Su codigo de Apretaste";
     $response = new Response();
     $response->setEmailLayout("email_simple.tpl");
     $response->setResponseSubject($subject);
     $response->createFromTemplate("pinrecover.tpl", array("pin" => $pin));
     $response->internal = true;
     // render the template as html
     $render = new Render();
     $body = $render->renderHTML(new Service(), $response);
     // email the code to the user
     $emailSender = new Email();
     $emailSender->sendEmail($email, $subject, $body);
     // return ok response
     die('{"code":"ok"}');
 }
Example #17
0
 /**
  * Display your relations
  *
  * @author kuma
  * @version 1.0
  * @param Request $request        	
  * @return Response
  */
 public function _relaciones(Request $request)
 {
     // connect to db
     $connection = new Connection();
     // prepare response
     $response = new Response();
     // requestor email
     $e = $request->email;
     // getting relations
     $sql = "      SELECT 'amigo' as what, user2 as who, inserted as since FROM relations WHERE user1 = '{$e}' AND type = 'friend' AND confirmed = 1\r\n\t\t\t\tUNION SELECT 'amigo' as what, user1 as who, inserted as since FROM relations WHERE user2 = '{$e}' AND type = 'friend' AND confirmed = 1\r\n\t\t\t\tUNION SELECT 'bloqueado' as what, user2 as who, inserted as since FROM relations WHERE user1 = '{$e}' AND type = 'blocked'\r\n\t\t\t\tUNION SELECT 'te bloque&oacute;' as what, user1 as who, inserted as since FROM relations WHERE user2 = '{$e}' AND type = 'blocked'\r\n\t\t\t\tUNION SELECT 'siguiendo' as what, user2 as who, inserted as since FROM relations WHERE user1 = '{$e}' AND type = 'follow'\r\n\t\t\t\tUNION SELECT 'seguidor' as what, user1 as who, inserted as since FROM relations WHERE user2 = '{$e}' AND type = 'follow'\r\n\t\t\t\tUNION SELECT 'te gusta' as what, user2 as who, inserted as since FROM relations WHERE user1 = '{$e}' AND type = 'like'\r\n\t\t\t\tUNION SELECT 'admirador' as what, user1 as who, inserted as since FROM relations WHERE user2 = '{$e}' AND type = 'like'\r\n\t\t\t\tUNION SELECT 'lo tocaste' as what, user2 as who, inserted as since FROM relations WHERE user1 = '{$e}' AND type = 'touch'\r\n\t\t\t\tUNION SELECT 'te dio un toque' as what, user1 as who, inserted as since FROM relations WHERE user2 = '{$e}' AND type = 'touch'\r\n\t\t\t\tUNION SELECT 'contacto' as what, user1 as who, inserted as since FROM relations WHERE user2 = '{$e}' AND type = 'contact'\r\n\t\t\t\tUNION SELECT 'contacto' as what, user2 as who, inserted as since FROM relations WHERE user1 = '{$e}' AND type = 'contact'\r\n\t\t\t\tUNION SELECT 'ignorado' as what, user1 as who, inserted as since FROM relations WHERE user2 = '{$e}' AND type = 'ignore'\r\n\t\t\t\tUNION SELECT 'te ignora' as what, user2 as who, inserted as since FROM relations WHERE user1 = '{$e}' AND type = 'ignore'\r\n\t\t\t\t\r\n\t\t\t\t";
     $relations = $connection->deepQuery(" SELECT * FROM ({$sql}) subq ORDER BY who;");
     foreach ($relations as $k => $v) {
         $relations[$k]->who = $this->utils->getPerson($v->who);
     }
     // send relations
     if (isset($relations[0])) {
         $response->setResponseSubject("Tus relaciones");
         $response->createFromTemplate('relations.tpl', array('relations' => $relations));
         return $response;
     }
     // get social services
     $services = $connection->deepQuery("SELECT * FROM service WHERE category = 'social';");
     // send suggestions
     $response->setResponseSubject("Te invitamos a socializar");
     $response->createFromTemplate('norelations.tpl', array('services' => $services));
     return $response;
 }
Example #18
0
 /**
  * Return common not member response
  *
  * @param string $email			
  * @return Response
  */
 private function getNotMemberResponse($email = null)
 {
     $response = new Response();
     if (is_null($email)) {
         $response->setResponseSubject("Usted no forma parte la red Cupido");
         $response->createFromText("Usted no forma parte la red Cupido");
     } else {
         $response->setResponseSubject("{$email} no forma parte la red Cupido");
         $response->createFromText("El usuario {$email} no forma parte la red Cupido");
     }
     return $response;
 }
Example #19
0
 /**
  * Insert a notification in the database
  *
  * @author kuma
  * @param string $email
  * @param string $origin
  * @param string $text
  * @param string $link
  * @param string $tag
  * @return integer
  */
 public function addNotification($email, $origin, $text, $link = '', $tag = 'INFO')
 {
     $connection = new Connection();
     $notifications = $this->getNumberOfNotifications($email);
     // insert notification
     $sql = "INSERT INTO notifications (email, origin, text, link, tag) VALUES ('{$email}','{$origin}','{$text}','{$link}','{$tag}');";
     $connection->deepQuery($sql);
     // get notification id
     $id = false;
     $r = $connection->deepQuery("SELECT LAST_INSERT_ID() as id;");
     if (isset($r[0]->id)) {
         $id = intval($r[0]->id);
     }
     // increase number of notifications
     $sql = "UPDATE person SET notifications = notifications + 1 WHERE email = '{$email}';";
     $connection->deepQuery($sql);
     // If more than 50 notifications, send the notifications to the user
     if ($notifications + 1 >= 50) {
         // getting notifications
         $sql = "SELECT * FROM notifications WHERE email ='{$email}' AND viewed = 0 ORDER BY inserted_date DESC;";
         $notificationsList = $connection->deepQuery($sql);
         if (!is_array($notificationsList)) {
             $notificationsList = array();
         }
         // create extra response
         $response = new Response();
         $response->setEmailLayout('email_default.tpl');
         $response->setResponseSubject("Tienes {$notifications} notificaciones sin leer");
         $response->createFromTemplate("notifications.tpl", array('notificactions' => $notificationsList));
         $response->internal = true;
         self::addExtraResponse($response);
         // Mark as seen
         $connection->deepQuery("UPDATE notifications SET viewed = 1, viewed_date = CURRENT_TIMESTAMP WHERE email ='{$email}'");
         // down to zero
         $connection->deepQuery("UPDATE person SET notifications = 0 WHERE email = '{$email}';");
     }
     return $id;
 }
Example #20
0
 /**
  * Function executed when the service is called
  *
  * @param Request
  * @return Response
  * */
 public function _main(Request $request)
 {
     // do not allow blank searches
     if (empty($request->query)) {
         $response = new Response();
         $response->setResponseSubject("De donde sacamos el mapa?");
         $response->createFromText("Usted no ha insertado ninguna direcci&oacute;n, coordenadas o lugar famoso a buscar. Inserte el texto en el asunto del email, justo despu&eacute;s de la palabra MAPA.<br/><br/>Por ejemplo: Asunto: <b>MAPA capitolio, cuba</b>");
         return $response;
     }
     // include google maps library
     require_once "{$this->pathToService}/lib/GoogleStaticMap.php";
     require_once "{$this->pathToService}/lib/GoogleStaticMapFeature.php";
     require_once "{$this->pathToService}/lib/GoogleStaticMapFeatureStyling.php";
     require_once "{$this->pathToService}/lib/GoogleStaticMapMarker.php";
     require_once "{$this->pathToService}/lib/GoogleStaticMapPath.php";
     require_once "{$this->pathToService}/lib/GoogleStaticMapPathPoint.php";
     // get and clean the argument
     $argument = $request->query;
     $argument = str_replace("\n", " ", $argument);
     $argument = str_replace("\r", "", $argument);
     $argument = trim(strtolower($argument));
     // detecting type
     $type = 'hibrido';
     $internalType = "hybrid";
     if (stripos($argument, 'fisico') !== false) {
         $type = 'fisico';
         $internalType = "satellite";
     } elseif (stripos($argument, 'politico') !== false) {
         $type = 'politico';
         $internalType = "roadmap";
     } elseif (stripos($argument, 'terreno') !== false) {
         $type = 'terreno';
         $internalType = "terrain";
     }
     // remove the type from the query to display on the template
     $argument = str_ireplace($type, '', $argument);
     // detecting zoom
     $zoom = null;
     for ($i = 22; $i >= 1; $i--) {
         if (stripos($argument, $i . 'x') !== false) {
             $zoom = $i;
             $argument = str_ireplace("{$i}x", '', $argument);
         }
     }
     // remove bad starting arguments
     if (substr($argument, 0, 3) == 'de ') {
         $argument = substr($argument, 3);
     }
     if (substr($argument, 0, 4) == 'del ') {
         $argument = substr($argument, 4);
     }
     // create the map
     $oStaticMap = new GoogleStaticMap();
     $oStaticMap->setScale(1);
     $oStaticMap->setHeight(400);
     $oStaticMap->setWidth(400);
     $oStaticMap->setLanguage("es");
     $oStaticMap->setHttps(true);
     $oStaticMap->setMapType($internalType);
     if (!is_null($zoom)) {
         $oStaticMap->setZoom($zoom);
     }
     $oStaticMap->setCenter($argument);
     // get path to the www folder
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     $wwwroot = $di->get('path')['root'];
     // save the image as a temp file
     $mapImagePath = "{$wwwroot}/temp/" . $this->utils->generateRandomHash() . ".jpg";
     $content = file_get_contents($oStaticMap);
     file_put_contents($mapImagePath, $content);
     // optimize the image
     $this->utils->optimizeImage($mapImagePath);
     // create the response variables
     $responseContent = array("type" => $type, "request" => $argument, "zoom" => $zoom, "image" => $mapImagePath);
     // create the response
     $response = new Response();
     $response->setResponseSubject("Mapa para " . $request->query);
     $response->createFromTemplate("basic.tpl", $responseContent, array($mapImagePath));
     return $response;
 }
Example #21
0
 /**
  * Get the last 50 messages sent by a user
  *
  * @author salvipascual
  * @param Request
  * @return Response
  *
  */
 public function _buscar(Request $request)
 {
     // do not work if the search comes in blank
     $query = trim($request->query);
     if (empty($query)) {
         $response = new Response();
         $response->createFromText("Por favor escriba un @username, un #hashtag o un texto a buscar.");
         return $response;
     }
     $connection = new Connection();
     // get the username from the email
     $usern = $connection->deepQuery("SELECT username FROM person WHERE email='{$request->email}'");
     $usern = $usern[0]->username;
     // check if the query is a date
     if (substr(strtolower($query), 0, 5) == 'fecha') {
         $query = trim(substr($query, 5));
         // by default
         $where = " TRUE ";
         $subject = "Ultimas 50 notas en Pizarra";
         // getting the date
         if ($query != '') {
             $valid_formats = array('YmdHis', 'Y-m-d H:i:s', 'Ymd', 'Y-m-d', 'd/m/Y H:i:s', 'd/m/Y', 'd-m-Y H:i:s', 'd-m-Y');
             foreach ($valid_formats as $vf) {
                 $date = date_create_from_format($vf, $query);
                 if ($date !== false) {
                     $where = " A.inserted >= '" . $date->format('Y-m-d H:i:s') . "' ";
                     $subject = "Ultimas notas a partir de " . $date->format('d/m/Y') . " a las " . $date->format('H:i:s') . 'hrs';
                     break;
                 }
             }
         }
     } else {
         // prepare to search for a text
         // @TODO make it work with levestein type algorithm
         $where = "A.text like '%{$query}%'";
         $subject = 'Notas con el texto "' . $query . '"';
         // get the number of words passed
         $numberOfWords = count(explode(" ", $query));
         // check if the query is a username
         if ($numberOfWords == 1 && strlen($query) > 2 && $query[0] == "@") {
             $username = str_replace("@", "", $query);
             // $where = "B.username = '******' OR A.text like '%$username%'";
             if (strcasecmp(trim($username), trim($usern)) === 0) {
                 $subject = 'Mis notas en pizarra';
             } else {
                 $subject = "Notas de {$query}";
             }
             $where = "B.username = '******'";
         }
         // check if the query is a hashtag
         if ($numberOfWords == 1 && strlen($query) > 2 && ($query[0] == "*" || $query[0] == "#")) {
             $hashtag = str_replace("*", "#", $query);
             $where = "A.text like '% {$hashtag}%'";
             $subject = "Veces que {$hashtag} es mencionado";
         }
     }
     // get the last 50 records from the db
     $connection = new Connection();
     $listOfNotes = $connection->deepQuery("\r\n\t\t\tSELECT A.*, B.username, B.first_name, B.last_name, B.province, B.picture, B.gender\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 {$where}\r\n\t\t\tORDER BY inserted DESC\r\n\t\t\tLIMIT 50");
     // display message if the response is blank
     if (empty($listOfNotes)) {
         $response = new Response();
         $response->createFromText("No se encontraron notas para el @username, #hashtag o texto que usted busc&oacute;.");
         return $response;
     }
     // format the array of notes
     $notes = array();
     foreach ($listOfNotes as $note) {
         // 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, $usern);
         // 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);
     }
     // 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']);
     }
     $content = array("header" => $subject, "notes" => $notes);
     // create the response
     $response = new Response();
     $response->setResponseSubject($subject);
     $response->createFromTemplate("notas.tpl", $content);
     return $response;
 }