예제 #1
0
 public function droppedAction()
 {
     // do not allow empty calls
     if (empty($_POST)) {
         die("EMPTY CALL");
     }
     // get the params from post
     $email = $_POST['recipient'];
     $domain = $_POST['domain'];
     $reason = $_POST['reason'];
     $code = isset($_POST['code']) ? $_POST['code'] : "";
     $desc = isset($_POST['description']) ? str_replace("'", "", $_POST['description']) : "";
     // do not save Spam as hardfail
     if (stripos($desc, 'spam') !== false) {
         $reason = "spam";
     }
     // mark as bounced if the email is part of the latest campaign
     $connection = new Connection();
     $campaign = $connection->deepQuery("\n\t\t\tSELECT campaign, email FROM (\n\t\t\t\tSELECT * FROM `campaign_sent`\n\t\t\t\tWHERE campaign = (SELECT id FROM campaign WHERE status='SENT' ORDER BY sending_date DESC LIMIT 1)\n\t\t\t) A WHERE email = '{$email}'");
     if (count($campaign) > 0) {
         // increase the bounce number for the campaign
         $campaign = $campaign[0];
         $connection->deepQuery("\n\t\t\t\tUPDATE campaign SET\tbounced=bounced+1 WHERE id={$campaign->campaign};\n\t\t\t\tUPDATE campaign_sent SET status='BOUNCED', date_opened=CURRENT_TIMESTAMP WHERE id={$campaign->campaign} AND email='{$email}'");
         // unsubscribe from the list
         $utils = new Utils();
         $utils->unsubscribeFromEmailList($email);
     }
     // save into the database
     $sql = "INSERT INTO delivery_dropped(email,sender,reason,code,description) VALUES ('{$email}','{$domain}','{$reason}','{$code}','{$desc}')";
     $connection->deepQuery($sql);
     // echo completion message
     echo "FINISHED";
 }
예제 #2
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();
     $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'");
 }
예제 #3
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();
     $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'");
 }
예제 #4
0
파일: service.php 프로젝트: Apretaste/rifa
 /**
  * Function executed when a payment is finalized
  * Add new tickets to the database when the user pays
  * 
  *  @author salvipascual
  * */
 public function payment(Payment $payment)
 {
     // get the number of times the loop has to iterate
     $numberTickets = null;
     if ($payment->code == "1TICKET") {
         $numberTickets = 1;
     }
     if ($payment->code == "5TICKETS") {
         $numberTickets = 5;
     }
     if ($payment->code == "10TICKETS") {
         $numberTickets = 10;
     }
     // do not give tickets for wrong codes
     if (empty($numberTickets)) {
         return false;
     }
     // create as many tickets as necesary
     $query = "INSERT INTO ticket(email,origin) VALUES ";
     for ($i = 0; $i < $numberTickets; $i++) {
         $query .= "('{$payment->buyer}','PURCHASE')";
         $query .= $i < $numberTickets - 1 ? "," : ";";
     }
     // save the tickets in the database
     $connection = new Connection();
     $transfer = $connection->deepQuery($query);
 }
예제 #5
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;
 }
예제 #6
0
 /**
  * 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;
 }
예제 #7
0
 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();
 }
예제 #8
0
파일: Utils.php 프로젝트: Apretaste/Sandbox
 /**
  * Get a person's profile
  *
  * @author salvipascual
  * @return Array or false
  * */
 public function getPerson($email)
 {
     // get the person
     $connection = new Connection();
     $person = $connection->deepQuery("SELECT * FROM person WHERE email = '{$email}'");
     // return false if there is no person with that email
     if (count($person) == 0) {
         return false;
     } else {
         $person = $person[0];
     }
     // get number of tickets for the raffle adquired by the user
     $tickets = $connection->deepQuery("SELECT count(*) as tickets FROM ticket WHERE raffle_id is NULL AND email = '{$email}'");
     $tickets = $tickets[0]->tickets;
     // get the person's full name
     $fullName = "{$person->first_name} {$person->middle_name} {$person->last_name} {$person->mother_name}";
     $fullName = trim(preg_replace("/\\s+/", " ", $fullName));
     // get the image of the person
     $image = NULL;
     $thumbnail = NULL;
     if ($person->picture) {
         $di = \Phalcon\DI\FactoryDefault::getDefault();
         $wwwroot = $di->get('path')['root'];
         if (file_exists("{$wwwroot}/public/profile/{$email}.jpg")) {
             $image = "{$wwwroot}/public/profile/{$email}.jpg";
         }
         if (file_exists("{$wwwroot}/public/profile/thumbnail/{$email}.jpg")) {
             $thumbnail = "{$wwwroot}/public/profile/thumbnail/{$email}.jpg";
         }
     }
     // get the interests as an array
     $person->interests = preg_split('@,@', $person->interests, NULL, PREG_SPLIT_NO_EMPTY);
     // remove all whitespaces at the begining and ending
     foreach ($person as $key => $value) {
         if (!is_array($value)) {
             $person->{$key} = trim($value);
         }
     }
     // add elements to the response
     $person->full_name = $fullName;
     $person->picture = $image;
     $person->thumbnail = $thumbnail;
     $person->raffle_tickets = $tickets;
     return $person;
 }
예제 #9
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'");
 }
예제 #10
0
 public function mainAction()
 {
     // inicialize supporting classes
     $timeStart = time();
     $utils = new Utils();
     $connection = new Connection();
     $sender = new Email();
     // get the first campaign created that is waiting to be sent
     $campaign = $connection->deepQuery("\n\t\t\tSELECT id, subject, content\n\t\t\tFROM campaign\n\t\t\tWHERE sending_date < CURRENT_TIMESTAMP\n\t\t\tAND status = 'WAITING'\n\t\t\tGROUP BY sending_date ASC\n\t\t\tLIMIT 1");
     // check if there are not campaigns
     if (empty($campaign)) {
         return;
     } else {
         $campaign = $campaign[0];
     }
     // check campaign as SENDING
     $connection->deepQuery("UPDATE campaign SET status='SENDING' WHERE id = {$campaign->id}");
     // get the list of people in the list who hsa not receive this campaign yet
     // so in case the campaign fails when it tries again starts from the same place
     $people = $connection->deepQuery("\n\t\t\tSELECT email FROM person\n\t\t\tWHERE mail_list=1 AND active=1\n\t\t\tAND email NOT IN (SELECT email FROM campaign_sent WHERE campaign={$campaign->id})");
     // show initial message
     $total = count($people);
     echo "\nSTARTING COUNT: {$total}\n";
     // email people one by one
     $counter = 1;
     foreach ($people as $person) {
         // show message
         echo "{$counter}/{$total} - {$person->email}\n";
         $counter++;
         // replace the template variables
         $content = $utils->campaignReplaceTemplateVariables($person->email, $campaign->content, $campaign->id);
         // send test email
         $sender->trackCampaign = $campaign->id;
         $result = $sender->sendEmail($person->email, $campaign->subject, $content);
         // add to bounced and unsubscribe if there are issues sending
         $bounced = "";
         $status = "SENT";
         if (!$result) {
             $utils->unsubscribeFromEmailList($person->email);
             $bounced = "bounced=bounced+1,";
             $status = "BOUNCED";
         }
         // save status before moving to the next email
         $connection->deepQuery("\n\t\t\t\tINSERT INTO campaign_sent (email, campaign, status) VALUES ('{$person->email}', '{$campaign->id}', '{$status}');\n\t\t\t\tUPDATE campaign SET {$bounced} sent=sent+1 WHERE id='{$campaign->id}'");
     }
     // set the campaign as SENT
     $connection->deepQuery("UPDATE campaign SET status='SENT' WHERE id='{$campaign->id}'");
     // get final delay
     $timeEnd = time();
     $timeDiff = $timeEnd - $timeStart;
     // saving the log
     $wwwroot = $this->di->get('path')['root'];
     $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/campaigns.log");
     $logger->log("ID: {$campaign->id}, RUNTIME: {$timeDiff}, SUBJECT: {$campaign->subject}");
     $logger->close();
     // save the status in the database
     $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='campaign'");
 }
예제 #11
0
 /**
  * Get the content from outside sources and post it in Pizarra
  * 
  * @author kuma
  * */
 public function mainAction()
 {
     $connection = new Connection();
     // create a twitter handler
     $twitter = new TwitterOAuth($this->KEY, $this->KEY_SECRET, $this->TOKEN, $this->TOKEN_SECRET);
     // loop all sources and get their content
     foreach ($this->sources as $email => $query) {
         // get the last
         $listOfTweets = $twitter->get("search/tweets", array("q" => $query, "count" => 50));
         // pick the newest, unpicked tweet form the list
         $total = count($listOfTweets->statuses);
         for ($i = 0; $i < $total; $i++) {
             // get the original post
             if (isset($listOfTweets->statuses[$i]->retweeted_status->text)) {
                 $note = $listOfTweets->statuses[$i]->retweeted_status->text;
             } else {
                 $note = $listOfTweets->statuses[$i]->text;
             }
             // trim, escape and format text
             $note = str_replace("'", "", $note);
             $note = str_replace("@", "", $note);
             $note = str_replace("“", '"', $note);
             $note = str_replace("”", '"', $note);
             $note = $this->removeAccents($note);
             $note = substr($note, 0, 140);
             // check if that nota already exist
             $notescount = $connection->deepQuery("SELECT COUNT(*) as total FROM _pizarra_notes WHERE text='{$note}'");
             if ($notescount[0]->total > 0) {
                 continue;
             }
             // save note into the database
             $connection->deepQuery("INSERT INTO _pizarra_notes (email,text,auto) VALUES ('{$email}', '{$note}',1)");
             break;
         }
     }
     // save the status in the database
     $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP WHERE task='pizarra'");
 }
예제 #12
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"));
 }
예제 #13
0
 /**
  * Get up to five services related and return an array with them
  * 
  * @author salvipascual
  * @param String $serviceName, name of the service
  * @return Array
  */
 private function getServicesRelatedArray($serviceName)
 {
     // get last 5 services inserted with the same category
     $query = "SELECT name FROM service \n\t\t\tWHERE category = (SELECT category FROM service WHERE name='{$serviceName}')\n\t\t\tAND name <> '{$serviceName}'\n\t\t\tORDER BY insertion_date\n\t\t\tLIMIT 5";
     $connection = new Connection();
     $result = $connection->deepQuery($query);
     // create returning array
     $servicesRelates = array();
     foreach ($result as $res) {
         $servicesRelates[] = $res->name;
     }
     // return the array
     return $servicesRelates;
 }
예제 #14
0
 public function indexAction()
 {
     // START visitors
     $connection = new Connection();
     $visits = $connection->deepQuery("\n\t\t\tSELECT\n\t\t\t\tcount(*) as received, \n\t\t\t\tDATE_FORMAT(request_time,'%Y-%m') as inserted \n\t\t\tFROM utilization\n\t\t\tGROUP BY DATE_FORMAT(request_time,'%Y-%m')\n\t\t\tHAVING inserted <> DATE_FORMAT(curdate(), '%Y-%m')\n\t\t\tORDER BY inserted DESC \n\t\t\tLIMIT 5");
     $visitors = array();
     $visitorsPerMonth = 0;
     foreach ($visits as $visit) {
         if ($visit->received > $visitorsPerMonth) {
             $visitorsPerMonth = $visit->received;
         }
         $visitors[] = ["date" => date("M Y", strtotime($visit->inserted)), "emails" => $visit->received];
     }
     $visitors = array_reverse($visitors);
     // END visitors
     $this->view->visitors = $visitors;
     $this->view->visitorsPerMonth = $visitorsPerMonth;
     $this->view->wwwhttp = $this->di->get('path')['http'];
     $this->view->wwwroot = $this->di->get('path')['root'];
     $this->view->stripePushibleKey = $this->di->get('config')['stripe']['pushible'];
     $this->view->pick("index/bienvenido");
 }
예제 #15
0
 public function getMarketProductAction()
 {
     $utils = new Utils();
     $code = $this->request->getPost('code');
     $code = $utils->clearStr($code, "1234567890");
     $connection = new Connection();
     $product = $connection->deepQuery("SELECT * FROM _tienda_products WHERE code = '{$code}';");
     $wwwroot = $this->di->get('path')['root'];
     if (is_array($product)) {
         $product = $product[0];
         $product->image = false;
         if (file_exists("{$wwwroot}/public/products/{$code}")) {
             $product->image = true;
         }
         $product->price_friendly = '$' . number_format($product->price, 2);
         $product->shipping_price_friendly = '$' . number_format($product->shipping_price, 2);
         $product->credits_friendly = '$' . number_format($product->credits, 2);
         echo "{product:" . json_encode($product) . "}";
     } else {
         echo "{product: false}";
     }
     $this->view->disable();
 }
예제 #16
0
파일: Deploy.php 프로젝트: Apretaste/Core
 /**
  * Add a new service to the filesystem, database and create the specific service tables
  *
  * @author salvipascual
  * @author kuma
  * @param Service
  * @param String , the path to the location of the zip
  * @param String , the path to the location of the files
  * @paran Boolean , if service are updating
  * */
 public function addService($service, $pathToZip, $pathToService, $updating = false)
 {
     $utils = $this->getUtils();
     // get the path
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     $wwwroot = $di->get('path')['root'];
     // create a new connection
     $connection = new Connection();
     // save the new service in the database
     $insertUserQuery = "\n\t\t\tINSERT INTO service (name,description,usage_text,creator_email,category,listed,ads) \n\t\t\tVALUES ('{$service['serviceName']}','{$service['serviceDescription']}','{$service['serviceUsage']}','{$service['creatorEmail']}','{$service['serviceCategory']}','{$service['listed']}','{$service['showAds']}')";
     $connection->deepQuery($insertUserQuery);
     // clear old alias
     $sqlClear = "DELETE FROM service_alias WHERE alias <> '";
     $sqlClear .= implode("' AND alias <> '", $service['serviceAlias']);
     $sqlClear .= "' AND service = '{$service['serviceName']}' ;";
     $connection->deepQuery($sqlClear);
     // insert new alias
     foreach ($service['serviceAlias'] as $alias) {
         $connection->deepQuery("INSERT IGNORE INTO service_alias (service, alias) VALUES ('{$service['serviceName']}','{$alias}');");
     }
     // clear old ads
     $connection->deepQuery("DELETE FROM ads WHERE related_service = '{$service['serviceName']}';");
     // create the owner of ad
     $sql = "INSERT IGNORE INTO person (email, username, credit) VALUES ('*****@*****.**', 'soporteap', 1000000);";
     $sql .= "UPDATE person SET credit = 1000000 WHERE email = '*****@*****.**';";
     $connection->deepQuery($sql);
     $serviceName = strtoupper($service['serviceName']);
     $serviceDesc = $connection->escape($service['serviceDescription']);
     $toaddress = $utils->getValidEmailAddress();
     // create an Ad for new service
     $body = "<p>Hola,<br/><br/>Nos alegra decir que tenemos un servicio nuevo en Apretatse. El servicio es {$serviceName} y {$serviceDesc}. ";
     $body .= "Espero que le sea de su agrado, y si quiere saber mas al respecto, el enlace a continuacion le explicar&aacute; como se usa y detallar&aacute; m&aacute;s sobre el mismo.";
     $body .= '<center><a href="mailto:' . $toaddress . '?subject=AYUDA ' . $serviceName . '">Conocer m&aacute;s sobre este servicio</a></center>';
     $body .= "<br/><br/>Gracias por usar Apretaste.<p>";
     if ($updating) {
         $body = "<p>Hola,<br/><br/>Tenemos una actualizaci&oacute;n al servicio {$serviceName} en Apretaste!";
         $body .= "Con las actualizaciones vienen mejoras, nuevas funciones y soluciones a problemas antiguos. Espero que le sea de su agrado, y si quiere saber mas al respecto, el enlace a continuacion le explicar&aacute; como se usa y detallar&aacute; m&aacute;s sobre el mismo.";
         $body .= '<center><a href="mailto:' . $toaddress . '?subject=AYUDA ' . $serviceName . '">Conocer m&aacute;s sobre este servicio</a></center>';
         $body .= "<br/><br/>Gracias por usar Apretaste.<p>";
     }
     $title = 'Presentando el servicio ' . $serviceName . ' a nuestros usuarios de Apretaste';
     if ($updating) {
         $title = 'Buenas noticias! Hemos realizado mejoras al servicio ' . $serviceName;
     }
     $sql = "INSERT INTO ads (title,description,owner,expiration_date,related_service) \n\t\t\t    VALUES ('{$title}', '{$body}','*****@*****.**', DATE_ADD(CURRENT_DATE, INTERVAL 1 WEEK), '{$service['serviceName']}');";
     $connection->deepQuery($sql);
     // copy files to the service folder and remove temp files
     rename($pathToService, "{$wwwroot}/services/{$service['serviceName']}");
     unlink($pathToZip);
 }
예제 #17
0
 /**
  * Main action
  */
 public function mainAction()
 {
     // get path to the www folder
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     $wwwroot = $di->get('path')['root'];
     // inicialize supporting classes
     $timeStart = microtime(true);
     $addressesCount = 0;
     $tempFolder = "{$wwwroot}/temp/email_extractor";
     $logFile = "{$tempFolder}/extractor.log";
     $listFile = "{$tempFolder}/files.list";
     $memoryLimit = str_replace(array('M', 'K', 'B'), '', ini_get('memory_limit') . '') * 1;
     $db = new Connection();
     $this->log("Starting email extractor...");
     $this->log("Temp folder: {$tempFolder}");
     $this->log("Log filer: {$logFile}");
     $this->log("List of files: {$listFile}");
     // preparing temporal folder
     if (!file_exists($tempFolder)) {
         mkdir($tempFolder);
     }
     // list of sites
     $sites = array('porlalivre' => 'http://porlalivre.com');
     // proccess each site
     foreach ($sites as $prefix => $site) {
         $this->log("Starting mirror of {$site}, saving in {$tempFolder}/{$prefix}", 'WGET');
         // change dir to temp folder
         chdir($tempFolder);
         // create a mirror of the site (without page resources)
         shell_exec("wget --no-check-certificate -P {$prefix} -o {$logFile} -mk -A .html {$site}");
         // return to www root
         chdir($wwwroot);
         // get duration of wget
         $this->log("Finish " . (microtime(true) - $timeStart) . "secs", 'WGET');
         if (file_exists("{$tempFolder}/{$prefix}")) {
             // remove the last list
             if (file_exists($listFile)) {
                 unlink($listFile);
             }
             $this->log("Creating list of files that will be proccessed...");
             // change dir to downloaded folder
             chdir("{$tempFolder}/{$prefix}");
             // create list of downloaded files
             if (strncasecmp(PHP_OS, 'WIN', 3) == 0) {
                 // for local develop
                 shell_exec("dir /s /b /aa > {$listFile}");
             } else {
                 // for production
                 shell_exec("find . -type f > {$listFile}");
             }
             // return to www root
             chdir($wwwroot);
             // computing total of files
             $total = 0;
             $f = fopen($listFile, "r");
             while (!feof($f)) {
                 $filename = trim(fgets($f));
                 $total++;
             }
             fclose($f);
             $this->log("Proccessing {$total} files");
             // proccessing the mirror
             $i = 0;
             $f = fopen($listFile, "r");
             $lastPercent = 0;
             while (!feof($f)) {
                 $filename = trim(fgets($f));
                 $i++;
                 // computing progress
                 $percent = number_format($i / $total * 100, 0) * 1;
                 if ($percent > $lastPercent) {
                     $this->log("Proccessed {$i} / {$total} = {$percent} % ");
                     $lastPercent = $percent;
                 }
                 if ($filename != '') {
                     $fileFullName = "{$tempFolder}/{$prefix}/{$filename}";
                     // checking if filename is a full path (differents results from Windows/dir and Linux/find)
                     if (!file_exists($fileFullName) && file_exists($filename)) {
                         $fileFullName = $filename;
                     }
                     // checking if file exists
                     if (!file_exists($fileFullName)) {
                         continue;
                     }
                     // checking file size
                     $fileSize = filesize($fileFullName) / 1024 / 1024;
                     if ($fileSize > $memoryLimit && $memoryLimit > 0) {
                         $this->log("Ingoring big file: {$fileFullName} ({$fileSize}M)");
                         continue;
                     }
                     $f2 = fopen($fileFullName, "r");
                     while (!feof($f2)) {
                         $content = fgets($f2);
                         $addresses = $this->getAddressFrom($content);
                         $addressesCount += count($addresses);
                         foreach ($addresses as $a) {
                             $exists = $db->deepQuery("SELECT * FROM person WHERE email = '{$a}';");
                             if ($exists === false || empty($exists) || !isset($exists[0])) {
                                 $db->deepQuery("INSERT IGNORE INTO autoinvitations (email,source) VALUES ('{$a}','PORLALIVRE');");
                             }
                         }
                     }
                     fclose($f2);
                     // remove processed file
                     @unlink($fileFullName);
                 }
             }
             fclose($f);
         }
     }
     // save the status in the database
     $timeDiff = time() - $timeStart;
     $db->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}', `values`='{$addressesCount}' WHERE task='extractor'");
 }
예제 #18
0
 /**
  * Function executed when the subservice is called
  *
  * @param Request
  * @return Response
  * */
 public function _comprar(Request $request)
 {
     $code = $request->query;
     // get the payment details
     $connection = new Connection();
     $inventory = $connection->deepQuery("SELECT * FROM inventory WHERE code = '{$code}' && active = 1");
     // error if the code was not valid or the inventory item cannot be found or its not active
     if (empty($code) || empty($inventory)) {
         $article = empty($code) ? "" : ", {$code}, ";
         $response = new Response();
         $response->subject = "Articulo incorrecto o temporalmente agotado";
         $response->createFromText("El articulo que usted pidi&oacute; comprar{$article}no existe o se encuentra temporalmente agotado. Por favor compruebe el c&oacute;digo e intente nuevamente.");
         return $response;
     }
     // get the element from the inventory
     $inventory = $inventory[0];
     // start a new transfer
     $r = new Request();
     $r->subject = "PURCHASE";
     $r->name = $inventory->code;
     $r->body = $inventory->name;
     $r->email = $request->email;
     $r->query = $inventory->price . " " . $inventory->seller;
     return $this->_main($r);
 }
예제 #19
0
파일: service.php 프로젝트: Apretaste/nota
 /**
  * Return a list of notes between $email1 & $email2 
  * 
  * @param string $email1
  * @param string $email2
  * @return array
  */
 private function getConversation($email1, $email2, $limit = 20)
 {
     // SQL for retrieve conversation between users
     $sql = "SELECT *, \r\n\t\t\t\tdate_format(send_date,'%d/%m/%y %h:%i%p') as date, \r\n\t\t\t\t(SELECT username FROM person WHERE person.email = _note.from_user) as from_username \r\n\t\t\t\tFROM _note \r\n\t\t\t\tWHERE (from_user = '******' AND to_user = '******') \r\n\t\t\t\tOR (to_user = '******' AND from_user = '******') \r\n\t\t\t\tORDER BY send_date DESC\r\n\t\t\t\tLIMIT {$limit};";
     $db = new Connection();
     $find = $db->deepQuery($sql);
     return $find;
 }
예제 #20
0
파일: Utils.php 프로젝트: ChrisClement/Core
 /**
  * Return the current Raffle or false if no Raffle was found
  * 
  * @author salvipascual
  * @return Array or false
  * */
 public function getCurrentRaffle()
 {
     // get the raffle
     $connection = new Connection();
     $raffle = $connection->deepQuery("SELECT * FROM raffle WHERE CURRENT_TIMESTAMP BETWEEN start_date AND end_date");
     // return false if there is no open raffle
     if (count($raffle) == 0) {
         return false;
     } else {
         $raffle = $raffle[0];
     }
     // get number of tickets opened
     $openedTickets = $connection->deepQuery("SELECT count(*) as opened_tickets FROM ticket WHERE raffle_id is NULL");
     $openedTickets = $openedTickets[0]->opened_tickets;
     // get the image of the raffle
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     $wwwroot = $di->get('path')['root'];
     $raffleImage = "{$wwwroot}/public/raffle/" . md5($raffle->raffle_id) . ".png";
     // add elements to the response
     $raffle->tickets = $openedTickets;
     $raffle->image = $raffleImage;
     return $raffle;
 }
예제 #21
0
 /**
  * Add a new service to the filesystem, database and create the specific service tables
  *
  * @author salvipascual
  * @param Service
  * @param String , the key to deploy the service
  * @param String , the path to the location of the zip
  * @param String , the path to the location of the files
  * */
 public function addService($service, $deployKey, $pathToZip, $pathToService)
 {
     // get the path
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     $wwwroot = $di->get('path')['root'];
     // create a new connection
     $connection = new Connection();
     // save the new service in the database
     $insertUserQuery = "INSERT INTO service (name,description,usage_text,creator_email,category,deploy_key) VALUES ('{$service['serviceName']}','{$service['serviceDescription']}','{$service['serviceUsage']}','{$service['creatorEmail']}','{$service['serviceCategory']}','{$deployKey}')";
     $connection->deepQuery($insertUserQuery);
     // copy files to the service folder and remove temp files
     rename($pathToService, "{$wwwroot}/services/{$service['serviceName']}");
     unlink($pathToZip);
     // create the service specific tables
     $query = "";
     foreach ($service['database'] as $table) {
         $tname = "__{$service['serviceName']}_{$table['name']}";
         $query = "CREATE TABLE {$tname} (";
         foreach ($table['columns'] as $column) {
             $length = empty($column['length']) ? "" : "({$column['length']})";
             $query .= "{$column['name']} {$column['type']} {$length},";
         }
         $query = rtrim($query, ",") . ");";
         $connection->deepQuery($query);
     }
 }
예제 #22
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"}');
 }
예제 #23
0
 /**
  * Search in the database for the most similar results
  * 
  * */
 private function search($query, $limit)
 {
     // get the count and data
     $connection = new Connection();
     $words = array();
     foreach (explode(" ", $query) as $word) {
         // do not process ignored words
         $isNegativeWord = $connection->deepQuery("SELECT word FROM _search_ignored_words WHERE word='{$word}'");
         if (!empty($isNegativeWord)) {
             $words[] = "~{$word}";
             continue;
         }
         // calculate how many permutations are needed to be considered a typo
         $typoMargin = floor(strlen($word) / 5);
         if ($typoMargin == 0) {
             $typoMargin = 1;
         }
         // check if the word is a typo and add it to the list
         $correctWord = $connection->deepQuery("SELECT word FROM _search_words WHERE word<>'{$word}' AND levenshtein(word, '{$word}')<{$typoMargin} LIMIT 1");
         if (!empty($correctWord)) {
             $correctWord = $correctWord[0]->word;
             $connection->deepQuery("INSERT IGNORE INTO _search_variations VALUES ('{$correctWord}','{$word}','TYPO')");
             $word = $correctWord;
         }
         // save each word to the database, update the count if the word was already saved
         $words[] = $word;
         $connection->deepQuery("INSERT IGNORE INTO _search_words(word) VALUES ('{$word}');\r\n\t\t\t\tUPDATE _search_words SET count=count+1, last_usage=CURRENT_TIMESTAMP WHERE word='{$word}'");
         // add the list of all synonyms and typos to the expression
         $variations = $connection->deepQuery("SELECT variation FROM _search_variations WHERE word='{$word}'");
         foreach ($variations as $variation) {
             $words[] = $variation->variation;
         }
     }
     // create the new, enhanced phrase to search
     $enhancedQuery = implode(" ", $words);
     // search for all the results based on the query created
     $sql = "SELECT *, 0 as popularity\r\n\t\t\tFROM _tienda_post\r\n\t\t\tWHERE MATCH (ad_title) AGAINST ('{$enhancedQuery}' IN BOOLEAN MODE) > 0\r\n\t\t\tAND DATE(date_time_posted) > DATE_SUB(NOW(), INTERVAL 1 MONTH)\r\n\t\t\tGROUP BY ad_title \r\n\t\t\tHAVING COUNT(ad_title) = 1";
     $results = $connection->deepQuery($sql);
     // get every search term and its strength
     $sql = "SELECT * FROM _search_words WHERE word in ('" . implode("','", $words) . "')";
     $terms = $connection->deepQuery($sql);
     // assign popularity based on other factors
     foreach ($results as $result) {
         // restart populatiry
         $popularity = 0;
         // popularity based on the post's age
         $datediff = time() - strtotime($result->date_time_posted);
         $popularity = 100 - floor($datediff / (60 * 60 * 24));
         // popularity based on strong words in the title and body
         // ensures keywords with more searches show always first
         foreach ($terms as $term) {
             if (stripos($result->ad_title, $term->word) !== false) {
                 $popularity += 50 + ceil($term->count / 10);
             }
             if (stripos($result->ad_body, $term->word) !== false) {
                 $popularity += 25 + ceil($term->count / 10);
             }
         }
         // popularity based on image and contact info
         if ($result->number_of_pictures > 0) {
             $popularity += 50;
         }
         if ($result->contact_email_1) {
             $popularity += 20;
         }
         if ($result->contact_email_2) {
             $popularity += 20;
         }
         if ($result->contact_email_3) {
             $popularity += 20;
         }
         if ($result->contact_phone) {
             $popularity += 20;
         }
         if ($result->contact_cellphone) {
             $popularity += 20;
         }
         // popularity when the query fully match the the title or body
         if (strpos($result->ad_title, $query) !== false) {
             $popularity += 100;
         }
         if (strpos($result->ad_body, $query) !== false) {
             $popularity += 50;
         }
         // popularity when the query partially match the the title or body
         $words = explode(" ", $query);
         if (count($words) > 2) {
             for ($i = 0; $i < count($words) - 2; $i++) {
                 // read words from right to left
                 $phraseR = implode(" ", array_slice($words, 0, $i + 2)) . " ";
                 if (strpos($result->ad_title, $phraseR) !== false) {
                     $popularity += 20 * count($phraseR);
                 }
                 if (strpos($result->ad_body, $phraseR) !== false) {
                     $popularity += 10 * count($phraseR);
                 }
                 // read words from left to right
                 $phraseL = " " . implode(" ", array_slice($words, $i + 1, count($words)));
                 if (strpos($result->ad_title, $phraseL) !== false) {
                     $popularity += 20 * count($phraseL);
                 }
                 if (strpos($result->ad_body, $phraseL) !== false) {
                     $popularity += 10 * count($phraseL);
                 }
             }
         }
         // popularity based on location
         // TODO set popularity based on location
         // assign new popularity
         $result->popularity = $popularity;
     }
     // sort the results based on popularity
     usort($results, function ($a, $b) {
         if ($a->popularity == $b->popularity) {
             return 0;
         }
         return $a->popularity > $b->popularity ? -1 : 1;
     });
     // get only the first X elements depending $limit
     $resultsToDisplay = count($results) > $limit ? array_slice($results, 0, $limit) : $results;
     // return an array with the count and the data
     return array("count" => count($results), "items" => $resultsToDisplay);
 }
예제 #24
0
 /**
  * Automatically select two ads to be displayed
  * 
  * @author salvipascual
  * */
 private function getAdsToShow()
 {
     // get the array of ads from the database
     $connection = new Connection();
     $ads = $connection->deepQuery("SELECT * FROM ads WHERE active = '1' AND expiration_date > CURRENT_TIMESTAMP");
     // if there are not active ads stop processing here
     if (count($ads) == 0) {
         return array();
     }
     // get the ad counter
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     $wwwroot = $di->get('path')['root'];
     $adCounter = intval(file_get_contents("{$wwwroot}/temp/adsCounter.tmp"));
     // restart the counter in case of an error
     if (empty($adCounter) || !array_key_exists($adCounter, $ads)) {
         $adCounter = 0;
     }
     // get top ad
     $topAd = $ads[$adCounter];
     // move the ad counter
     $adCounter++;
     if (!array_key_exists($adCounter, $ads)) {
         $adCounter = 0;
     }
     // get bottom ad
     $bottomAd = $ads[$adCounter];
     // move the ad counter
     $adCounter++;
     if (!array_key_exists($adCounter, $ads)) {
         $adCounter = 0;
     }
     // save the ad counter
     file_put_contents("{$wwwroot}/temp/adsCounter.tmp", $adCounter);
     // get the md5 of the id the create the filename
     $topAdFileName = md5($topAd->ads_id);
     $bottomAdFileName = md5($bottomAd->ads_id);
     // return both ads
     return array("{$wwwroot}/public/ads/{$topAdFileName}.png", "{$wwwroot}/public/ads/{$bottomAdFileName}.png");
 }
예제 #25
0
파일: Render.php 프로젝트: Apretaste/Core
 /**
  * Get up to five services related and return an array with them
  *
  * @author salvipascual
  * @param String $serviceName, name of the service
  * @return Array
  */
 private function getServicesRelatedArray($serviceName)
 {
     // harcoded return for the sandbox
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     if ($di->get('environment') == "sandbox") {
         return array('ayuda', 'nota', 'tienda', 'traducir', 'publicidad');
     }
     // get last 5 services inserted with the same category
     $query = "SELECT name FROM service\n\t\t\tWHERE category = (SELECT category FROM service WHERE name='{$serviceName}')\n\t\t\tAND name <> '{$serviceName}'\n\t\t\tAND name <> 'excluyeme'\n\t\t\tAND listed = 1\n\t\t\tORDER BY insertion_date\n\t\t\tLIMIT 5";
     $connection = new Connection();
     $result = $connection->deepQuery($query);
     // create returning array
     $servicesRelates = array();
     foreach ($result as $res) {
         $servicesRelates[] = $res->name;
     }
     // return the array
     return $servicesRelates;
 }
예제 #26
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;
 }
예제 #27
0
파일: Response.php 프로젝트: Apretaste/Core
 /**
  * Automatically select two ads to be displayed
  * 
  * @author salvipascual
  * */
 private function getAdsToShow()
 {
     // get the array of ads from the database
     $connection = new Connection();
     $utils = new Utils();
     // get the person from the current email
     $person = $utils->getPerson($this->email);
     if ($person == false) {
         $person = new stdClass();
     }
     if (!isset($person->age)) {
         $person->age = null;
     }
     if (!isset($person->gender)) {
         $person->gender = null;
     }
     if (!isset($person->eyes)) {
         $person->eyes = null;
     }
     if (!isset($person->skin)) {
         $person->skin = null;
     }
     if (!isset($person->body_type)) {
         $person->body_type = null;
     }
     if (!isset($person->hair)) {
         $person->hair = null;
     }
     if (!isset($person->province)) {
         $person->province = null;
     }
     if (!isset($person->highest_school_level)) {
         $person->highest_school_level = null;
     }
     if (!isset($person->marital_status)) {
         $person->marital_status = null;
     }
     if (!isset($person->sexual_orientation)) {
         $person->sexual_orientation = null;
     }
     if (!isset($person->religion)) {
         $person->religion = null;
     }
     // select the ads to show
     $sql = "\n\t\t\tSELECT * FROM ads WHERE active=1 \n\t\t\tAND expiration_date > CURRENT_TIMESTAMP \n\t\t\tAND (SELECT credit FROM person WHERE person.email = ads.owner) >= ads.price\n\t\t\tAND ads.owner <> '{$this->email}' ";
     if (!empty($person->age)) {
         $sql .= " AND (from_age * 1 <= {$person->age} OR from_age = 'ALL') AND (to_age * 1 >= {$person->age} OR to_age = 'ALL') ";
     }
     if (!empty($person->gender)) {
         $sql .= " AND (gender = '{$person->gender}' OR gender = 'ALL') ";
     }
     if (!empty($person->eyes)) {
         $sql .= " AND (eyes = '{$person->eyes}' OR eyes = 'ALL') ";
     }
     if (!empty($person->skin)) {
         $sql .= " AND (skin = '{$person->skin}' OR skin = 'ALL') ";
     }
     if (!empty($person->body_type)) {
         $sql .= " AND (body_type = '{$person->body_type}' OR body_type = 'ALL') ";
     }
     if (!empty($person->hair)) {
         $sql .= " AND (hair = '{$person->hair}' OR hair = 'ALL') ";
     }
     if (!empty($person->province)) {
         $sql .= " AND (province = '{$person->province}' OR province = 'ALL') ";
     }
     if (!empty($person->highest_school_level)) {
         $sql .= " AND (highest_school_level = '{$person->highest_school_level}' OR highest_school_level = 'ALL') ";
     }
     if (!empty($person->marital_status)) {
         $sql .= " AND (marital_status = '{$person->marital_status}' OR marital_status = 'ALL') ";
     }
     if (!empty($person->sexual_orientation)) {
         $sql .= " AND (sexual_orientation = '{$person->sexual_orientation}' OR sexual_orientation = 'ALL') ";
     }
     if (!empty($person->religion)) {
         $sql .= " AND (religion = '{$person->religion}' OR religion = 'ALL') ";
     }
     $sql .= " ORDER BY last_usage LIMIT 2;";
     $ads = $connection->deepQuery($sql);
     // if there are not active ads stop processing here
     if (count($ads) == 0) {
         return array();
     }
     // get top and bottom ads
     $topAd = $ads[0];
     if (isset($ads[1])) {
         $bottomAd = $ads[1];
     } else {
         $bottomAd = $topAd;
     }
     // save last usage date for the selected ads in the database
     $connection->deepQuery("UPDATE ads SET last_usage = CURRENT_TIMESTAMP WHERE id = {$topAd->id};");
     $connection->deepQuery("UPDATE ads SET last_usage = CURRENT_TIMESTAMP WHERE id = {$bottomAd->id};");
     return array($topAd, $bottomAd);
 }
예제 #28
0
 /**
  * Toggle the status of the jumper
  * */
 public function jumperToggleActiveStatusAction()
 {
     $email = $this->request->get("email");
     if ($email) {
         $connection = new Connection();
         $query = "UPDATE jumper SET active = !active WHERE email = '{$email}'";
         $connection->deepQuery($query);
     }
     return $this->response->redirect('manage/jumper');
 }
예제 #29
0
 /**
  * Update a profile
  *
  * @param String $sqlset			
  * @param String $email			
  */
 private function update($sqlset, $email)
 {
     $query = "UPDATE person SET {$sqlset}, last_update_date=CURRENT_TIMESTAMP, updated_by_user=1\tWHERE email='{$email}'";
     $query = preg_replace("/\\s+/", " ", $query);
     $connection = new Connection();
     $connection->deepQuery($query);
 }
예제 #30
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;
 }