/** * 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ún texto a buscar en Wikipedia. Inserte el texto en el asunto del email, justo despué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ú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; }
/** * 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; }
/** * Get the latest raffle * * @param Request * @return Response * */ public function _main(Request $request) { // set Spanish so the date come in Spanish setlocale(LC_TIME, "es_ES"); // get the current raffle $raffle = $this->utils->getCurrentRaffle(); // show message if there is no open raffle if (!$raffle) { $response = new Response(); $response->subject = "No hay ninguna Rifa abierta"; $response->createFromText("Lo sentimos, no hay ninguna Rifa abierta ahora mismo. Pruebe nuevamente en algunos días."); return $response; } // get number of tickets adquired by the user $connection = new Connection(); $userTickets = $connection->deepQuery("SELECT count(*) as tickets FROM ticket WHERE raffle_id is NULL AND email = '{$request->email}'"); $userTickets = $userTickets[0]->tickets; // link to connect cuba logo $connectCubaLogo = "{$this->pathToService}/images/connectcuba.jpg"; // create a json object to send to the template $responseContent = array("description" => $raffle->item_desc, "startDate" => $raffle->start_date, "endDate" => $raffle->end_date, "tickets" => $raffle->tickets, "image" => $raffle->image, "userTickets" => $userTickets, "connectCubaLogo" => $connectCubaLogo); // create the final user Response $response = new Response(); $response->subject = "La Rifa de Apretaste"; $response->createFromTemplate("basic.tpl", $responseContent, array($raffle->image, $connectCubaLogo)); return $response; }
public function mainAction() { // inicialize supporting classes $connection = new Connection(); $email = new Email(); $service = new Service(); $service->showAds = false; $render = new Render(); $response = new Response(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; // get valid people $people = $connection->deepQuery("\n\t\t\tSELECT email, username, first_name, last_access\n\t\t\tFROM person\n\t\t\tWHERE active=1\n\t\t\tAND email not in (SELECT DISTINCT email FROM delivery_dropped)\n\t\t\tAND DATE(last_access) > DATE('2016-05-01')\n\t\t\tAND email like '%.cu'\n\t\t\tAND email not like '*****@*****.**'"); // send the remarketing $log = ""; foreach ($people as $person) { // get the email address $newEmail = "apretaste+{$person->username}@gmail.com"; // create the variabels to pass to the template $content = array("newemail" => $newEmail, "name" => $person->first_name); // create html response $response->setEmailLayout("email_simple.tpl"); $response->createFromTemplate('newEmail.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // send the email $email->sendEmail($person->email, "Sorteando las dificultades, un email lleno de alegria", $html); $log .= $person->email . "\n"; } // saving the log $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/newemail.log"); $logger->log($log); $logger->close(); }
/** * Function executed when the service is called * * @param Request * @return Response * */ public function _main(Request $request) { // display help for an specific service if (!empty($request->query)) { // check if the query passed is a service $connection = new Connection(); $res = $connection->deepQuery("SELECT * FROM service WHERE name = '{$request->query}'"); if (count($res) > 0) { $service = $res[0]; // update the valid email on the usage text $utils = new Utils(); $validEmailAddress = $utils->getValidEmailAddress(); $usage = str_replace('{APRETASTE_EMAIL}', $validEmailAddress, $service->usage_text); // send variables to the template $responseContent = array("name" => $service->name, "description" => $service->description, "category" => $service->category, "usage" => nl2br($usage)); // create response for an specific service $response = new Response(); $response->subject = "Ayuda para el servicio " . ucfirst($service->name); $response->createFromTemplate("service.tpl", $responseContent); return $response; } } // create response $responseContent = array("userEmail" => $request->email); $response = new Response(); $response->subject = "Ayuda de Apretaste"; $response->createFromTemplate("basic.tpl", $responseContent); return $response; }
/** * 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; }
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(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; $log = ""; // people who were invited but never used Apretaste $invitedPeople = $connection->deepQuery("\n\t\t\tSELECT invitation_time, email_inviter, email_invited\n\t\t\tFROM invitations \n\t\t\tWHERE used=0 \n\t\t\tAND DATEDIFF(CURRENT_DATE, invitation_time) > 15 \n\t\t\tAND email_invited NOT IN (SELECT DISTINCT email from delivery_dropped)\n\t\t\tAND email_invited NOT IN (SELECT DISTINCT email from remarketing)\n\t\t\tORDER BY invitation_time DESC\n\t\t\tLIMIT 450"); // send the first remarketing $log .= "\nINVITATIONS (" . count($invitedPeople) . ")\n"; foreach ($invitedPeople as $person) { // check number of days since the invitation was sent $datediff = time() - strtotime($person->invitation_time); $daysSinceInvitation = floor($datediff / (60 * 60 * 24)); // validate old invitations to avoid bounces if ($daysSinceInvitation > 60) { // re-validate the email $res = $utils->deepValidateEmail($person->email_invited); // if response not ok or temporal, delete from invitations list if ($res[0] != "ok" && $res[0] != "temporal") { $connection->deepQuery("DELETE FROM invitations WHERE email_invited = '{$person->email_invited}'"); $log .= "\t --skiping {$person->email_invited}\n"; continue; } } // send data to the template $content = array("date" => $person->invitation_time, "inviter" => $person->email_inviter, "invited" => $person->email_invited, "expires" => strtotime('next month')); // create html response $response->createFromTemplate('pendinginvitation.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // send the invitation email $subject = "Su amigo {$person->email_inviter} esta esperando por usted!"; $email->sendEmail($person->email_invited, $subject, $html); // insert into remarketing table $connection->deepQuery("INSERT INTO remarketing(email, type) VALUES ('{$person->email_invited}', 'INVITE')"); // display notifications $log .= "\t{$person->email_invited}\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/remarketing_invitation.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='invitation'"); }
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(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; $log = ""; // people in the list to be automatically invited $people = $connection->deepQuery("\n\t\t\tSELECT * FROM autoinvitations\n\t\t\tWHERE email NOT IN (SELECT email FROM person)\n\t\t\tAND email NOT IN (SELECT DISTINCT email FROM delivery_dropped)\n\t\t\tAND email NOT IN (SELECT DISTINCT email from remarketing)\n\t\t\tAND error=0\n\t\t\tLIMIT 450"); // send the first remarketing $log .= "\nAUTOMATIC INVITATIONS (" . count($people) . ")\n"; foreach ($people as $person) { // if response not ok, check the email as error $res = $utils->deepValidateEmail($person->email); if ($res[0] != "ok") { $connection->deepQuery("UPDATE autoinvitations SET error=1, processed=CURRENT_TIMESTAMP WHERE email='{$person->email}'"); $log .= "\t --skiping {$person->email}\n"; continue; } // create html response $content = array("email" => $person->email); $response->createFromTemplate('autoinvitation.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // send invitation email $subject = "Dos problemas, y una solucion"; $email->sendEmail($person->email, $subject, $html); // mark as sent $connection->deepQuery("\n\t\t\t\tSTART TRANSACTION;\n\t\t\t\tDELETE FROM autoinvitations WHERE email='{$person->email}';\n\t\t\t\tINSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'AUTOINVITE');\n\t\t\t\tCOMMIT;"); // display notifications $log .= "\t{$person->email}\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/remarketing_autoinvitation.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='autoinvitation'"); }
/** * 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")); }
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'"); }
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; }
/** * 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"}'); }
/** * 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; }
/** * 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; }
/** * 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í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; }
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(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; $log = ""; /* * FIRST REMINDER * */ // people missed for the last 30 days and with no remarketing emails unopened $firstReminderPeople = $connection->deepQuery("\n\t\t\tSELECT email, last_access \n\t\t\tFROM person \n\t\t\tWHERE active=1 \n\t\t\tAND IFNULL(DATEDIFF(CURRENT_DATE, last_access),99) > 30 \n\t\t\tAND email not in (SELECT DISTINCT email FROM remarketing WHERE opened IS NULL)\n\t\t\tORDER BY insertion_date ASC\n\t\t\tLIMIT 200"); // send the remarketing $log .= "\nFIRST REMINDER (" . count($firstReminderPeople) . ")\n"; foreach ($firstReminderPeople as $person) { // check number of days since the email was last checked $datediff = time() - strtotime($person->last_access); $daysSinceLastChecked = floor($datediff / (60 * 60 * 24)); // validate old emails to avoid bounces if ($daysSinceLastChecked > 60) { // re-validate the email $res = $utils->deepValidateEmail($person->email); // keep it for later if it was temporal if ($res[0] == "temporal") { $log .= "\t --skiping {$person->email}\n"; continue; } // for other than ok, unsubscribe and do not email if ($res[0] != "ok") { $utils->unsubscribeFromEmailList($person->email); $connection->deepQuery("UPDATE person SET active=0 WHERE email='{$person->email}'"); $log .= "\t --skiping {$person->email}\n"; continue; } } // get services that changed since last time $sql = "SELECT * FROM service WHERE insertion_date BETWEEN '{$person->last_access}' AND CURRENT_TIMESTAMP AND listed=1"; $services = $connection->deepQuery($sql); // create the variabels to pass to the template $content = array("services" => $services); $images = array("{$wwwroot}/public/images/missyou.jpg"); // create html response $response->createFromTemplate('remindme1.tpl', $content, $images); $response->internal = true; $html = $render->renderHTML($service, $response); // move remarketing to the next state and add $1 to his/her account $email->sendEmail($person->email, "Se le extranna por Apretaste", $html, $images); // move remarketing to the next state and add +1 credits $connection->deepQuery("\n\t\t\t\tSTART TRANSACTION;\n\t\t\t\tUPDATE person SET credit=credit+1 WHERE email='{$person->email}';\r\n\t\t\t\tINSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'REMINDER1');\n\t\t\t\tCOMMIT;"); // display notifications $log .= "\t{$person->email}\n"; } /* * SECOND REMINDER * */ // people with REMINDER1 unaswered for the last 30 days, and without REMINDER2 created $secondReminderPeople = $connection->deepQuery("\n\t\t\tSELECT email\n\t\t\tFROM remarketing A\n\t\t\tWHERE type='REMINDER1'\n\t\t\tAND opened IS NULL\n\t\t\tAND DATEDIFF(CURRENT_DATE, sent) > 30\n\t\t\tAND (SELECT COUNT(email) FROM remarketing WHERE type='REMINDER2' AND opened IS NULL AND email=A.email)=0"); // send the remarketing $log .= "SECOND REMINDER (" . count($secondReminderPeople) . ")\n"; foreach ($secondReminderPeople as $person) { // create html response $response->createFromTemplate('remindme2.tpl', array()); $response->internal = true; $html = $render->renderHTML($service, $response); // send email to the $person->email $email->sendEmail($person->email, "Hace rato no le veo", $html); // move remarketing to the next state and add +1 credits $connection->deepQuery("\r\n\t\t\t\tSTART TRANSACTION;\r\n\t\t\t\tUPDATE person SET credit=credit+1 WHERE email='{$person->email}';\n\t\t\t\tINSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'REMINDER2');\r\n\t\t\t\tCOMMIT;"); // display notifications $log .= "\t{$person->email}\n"; } /* * EXCLUDE * */ // people with REMINDER2 unaswered, sent 30 days ago and not EXCLUDED $thirdReminderPeople = $connection->deepQuery("\n\t\t\tSELECT email\n\t\t\tFROM remarketing A\n\t\t\tWHERE type='REMINDER2'\n\t\t\tAND opened IS NULL\n\t\t\tAND DATEDIFF(CURRENT_DATE, sent) > 30\n\t\t\tAND (SELECT COUNT(email) from remarketing WHERE type='EXCLUDED' AND opened IS NULL AND email=A.email)=0"); // unsubcribe people $log .= "UNSUSCRIBING (" . count($thirdReminderPeople) . ")\n"; foreach ($thirdReminderPeople as $person) { // unsubscribe person $utils->unsubscribeFromEmailList($person->email); // move remarketing to the next state and unsubscribe $connection->deepQuery("\r\n\t\t\t\tSTART TRANSACTION;\r\n\t\t\t\tUPDATE person SET active=0 WHERE email='{$person->email}';\n\t\t\t\tINSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'EXCLUDED');\r\n\t\t\t\tCOMMIT;"); // display notifications $log .= "\t{$person->email}\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/remarketing.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='remarketing'"); }
/** * 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ú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úsqueda '{$request->query}' no produjo ningún resultado. Por favor utilice otra frase de bú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; }
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(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; $log = ""; // list and total of services $services = $connection->deepQuery("SELECT name, description FROM service WHERE name <> 'ayuda' AND name <> 'terminos' AND name <> 'excluyeme' AND listed = 1;"); $arr = array(); foreach ($services as $servicex) { $arr[$servicex->name] = $servicex; } $services = $arr; $total_services = count($services); // users by service $sql_users_by_service = "SELECT requestor, service FROM utilization WHERE service <> 'rememberme' GROUP BY requestor, service"; // usage of services $sql_usage = "SELECT requestor, count(service) as part, {$total_services} as total FROM ({$sql_users_by_service}) subq1 GROUP BY requestor, total"; // filtering by less usage $sql_less_usage = "SELECT requestor as email, (SELECT sent FROM remarketing WHERE remarketing.email = subq2.requestor ORDER BY sent DESC LIMIT 1) as last_remarketing FROM ({$sql_usage}) subq2 WHERE part/total <= 0.2 "; // filtering by last remarketing (one by month) $sql = "SELECT email FROM ({$sql_less_usage}) subq3 WHERE datediff(CURRENT_DATE, last_remarketing) > 30 or datediff(CURRENT_DATE, last_remarketing) is null group by email"; $users = $connection->deepQuery("{$sql};"); // send the remarketing $log .= "\nLESS USAGE REMARKETING (" . count($users) . ")\n"; foreach ($users as $person) { // all services $his_services = $services; // getting services used by user $services_of_user = $connection->deepQuery("SELECT service as name FROM ({$sql_users_by_service}) subq1 WHERE requestor = '{$person->email}';"); // remove services used by user from the list foreach ($services_of_user as $servicex) { if (isset($his_services[$servicex->name])) { unset($his_services[$servicex->name]); } } // create the variabels to pass to the template $content = array("services" => $his_services); // create html response $response->createFromTemplate('lessusage.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // move remarketing to the next state and add $1 to his/her account $email->sendEmail($person->email, "Lo que te estas perdiendo en Apretaste", $html); // move remarketing to the next state and add +1 credits $connection->deepQuery("INSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'LESSUSAGE');"); // display notifications $log .= "\t{$person->email}\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/lessusage.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='lessusage'"); }
/** * 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; } } }
/** * 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); }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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ó' 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; }
/** * Function executed when the subservice is called * * @param Request * @return Response * */ public function _aceptar(Request $request) { $hash = $request->query; // get the transfer details, ensure the transfer is valid $connection = new Connection(); $transfer = $connection->deepQuery("SELECT * FROM transfer WHERE confirmation_hash = '{$hash}' && transfered = 0"); // error if the hash was not valid or the transaction was used already if (empty($hash) || empty($transfer)) { $response = new Response(); $response->subject = "Error procesando su transferencia o pago"; $response->createFromText("Tuvimos un error procesando su transferencia, o puede que esta transferencia ya se halla cobrado. Su crédito no ha sido afectado. Por favor intente nuevamente."); return $response; } // get the elapsed time since the transfer was requested $transferRow = $transfer[0]; $seconds = time() - strtotime($transferRow->transfer_time); $elapsedTimeInHours = $seconds / 60 / 60; // error if the transfer is out of date if ($elapsedTimeInHours > 1) { $response = new Response(); $response->subject = "Su transferencia o pago ha expirado"; $responseContent = array("amount" => $transferRow->amount, "receiver" => $transferRow->receiver); $response->createFromTemplate("expired.tpl", $responseContent); return $response; } // check if you still have enough credit to transfer $utils = new Utils(); $profile = $utils->getPerson($transferRow->sender); if ($profile->credit < $transferRow->amount) { // send response to the user $responseContent = array("amount" => $transferRow->amount, "credit" => $profile->credit, "email" => $transferRow->receiver); $response = new Response(); $response->subject = "No tiene suficiente credito"; $response->createFromTemplate("nocredit.tpl", $responseContent); return $response; } // make the transfer $sql = "\r\n\t\t\tSTART TRANSACTION;\r\n\t\t\tUPDATE person SET credit=credit-{$transferRow->amount} WHERE email='{$request->email}';\r\n\t\t\tUPDATE person SET credit=credit+{$transferRow->amount} WHERE email='{$transferRow->receiver}';\r\n\t\t\tUPDATE transfer SET transfered=1 WHERE id='{$transferRow->id}';\r\n\t\t\tCOMMIT;"; $connection->deepQuery($sql); // if it is a transfer if ($transferRow->inventory_code == "NULL") { $template = "receipt.tpl"; $itemBought = ""; // empty for transfers $subject = "Su transferencia ha sido realizada correctamente"; } else { // get the transfer row $inventory = $connection->deepQuery("SELECT * FROM inventory WHERE code = '{$transferRow->inventory_code}'")[0]; $serviceName = strtolower($inventory->service); // include the service include_once $utils->getPathToService($serviceName) . "/service.php"; $object = new $serviceName(); // if the object has a method payment if (method_exists($object, "payment")) { // create the payment object $payment = new Payment(); $payment->code = $inventory->code; $payment->price = $inventory->price; $payment->name = $inventory->name; $payment->seller = $inventory->seller; $payment->buyer = $request->email; $payment->transfer = $transferRow; // call the payment function $object->payment($payment); } $template = "receiptPurchase.tpl"; $subject = "Su pago se ha efectuado correctamente"; $itemBought = $inventory->name; } // create response to send to the user $responseContent = array("amount" => $transferRow->amount, "receiver" => $transferRow->receiver, "itemBought" => $itemBought); $responses = array(); // send the receipt to the sender $response = new Response(); $response->subject = $subject; $response->createFromTemplate($template, $responseContent); $responses[] = $response; // Let the receiver know $responseContent = array("amount" => $transferRow->amount, "sender" => $request->email); $response = new Response(); $response->email = $transferRow->receiver; $response->subject = "Usted ha recibido \${$transferRow->amount} en credito de Apretaste"; $response->createFromTemplate("information.tpl", $responseContent); $responses[] = $response; // Generate a notification $this->utils->addNotification($transferRow->receiver, 'credito', $response->subject, 'CREDITO', 'IMPORTANT'); return $responses; }
/** * 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; }
/** * 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ón, coordenadas o lugar famoso a buscar. Inserte el texto en el asunto del email, justo despué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; }
/** * 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ó."); 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; }