/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_apretaste_email($params, $template) { // get a valid apretaste email address $utils = new Utils(); $validEmailAddress = $utils->getValidEmailAddress(); return $validEmailAddress; }
/** * 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; }
/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_link($params, $template) { // get params $href = $params["href"]; $caption = $params["caption"]; // get the body if exist if (isset($params["body"])) { $body = $params["body"]; } else { $body = "Envie+el+correo+tal+y+como+esta,+ya+esta+preparado+para+usted"; } // get a valid apretaste email address $utils = new Utils(); $validEmailAddress = $utils->getValidEmailAddress(); // create and return button return "<a href='mailto:{$validEmailAddress}?subject={$href}&body={$body}' target='_blank'>{$caption}</a>"; }
/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_button($params, $template) { // get params $href = $params["href"]; $caption = $params["caption"]; // get the body if exist if (isset($params["body"])) { $body = $params["body"]; } else { $body = "Envie+el+correo+tal+y+como+esta,+ya+esta+preparado+para+usted"; } // get a valid apretaste email address $utils = new Utils(); $validEmailAddress = $utils->getValidEmailAddress(); // create and return button return "<!--[if mso]>\r\n\t\t<v:roundrect xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w='urn:schemas-microsoft-com:office:word' href='mailto:{$validEmailAddress}?subject={$href}&body={$body}' style='height:36px;v-text-anchor:middle;width:150px;' arcsize='5%' strokecolor='#5dbd00' fillcolor='#5EBB47'>\r\n\t\t<w:anchorlock/>\r\n\t\t<center style='color:#ffffff;font-family:Helvetica, Arial,sans-serif;font-size:16px;'>{$caption}</center>\r\n\t\t</v:roundrect>\r\n\t<![endif]-->\r\n\t<a href='mailto:{$validEmailAddress}?subject={$href}&body={$body}' style='background-color:#5EBB47;border:1px solid #5dbd00;border-radius:3px;color:#ffffff;display:inline-block;font-family:sans-serif;font-size:16px;line-height:44px;text-align:center;text-decoration:none;width:150px;-webkit-text-size-adjust:none;mso-hide:all;'>{$caption}</a>"; }
/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_emailbox($params, $template) { // get params $title = $params["title"]; $from = $params["from"]; $subject = $params["subject"]; // get the body and width if exist $body = isset($params["body"]) ? $params["body"] : ""; $width = isset($params["width"]) ? $params["width"] : "250"; // get a valid apretaste email address $utils = new Utils(); $to = $utils->getValidEmailAddress(); // construct params for the emailbox $leftColWidth = $width * 50 / 397; $rightColWidth = $width * 315 / 397; $titleWidth = $width * 315 / 397; return "\n\t<table style='font-size: 12px;font-family: Verdana; border: 1px solid gray; background:#eeeeee; width:{$width}px;margin-left: 8px;' cellspacing='0' cellpadding='0' width='{$width}'>\n\t\t<tr style='background: #4c9ed9;'>\n\t\t\t<td style='padding: 5px;' align='left' colspan='2'>\n\t\t\t\t<table width='{$width}' cellspacing='0' cellpadding='0' style='margin: 0px;'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td style='font-family: Verdana; color: white; font-weight: bold;font-size: 12px;' width='{$titleWidth}'>{$title}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td style='padding: 5px;' align='right' width='{$leftColWidth}'>De:</td>\n\t\t\t<td align='left'>\n\t\t\t\t<table cellspacing='0' cellpadding='0' style='font-size: 12px;font-family: Lucida console; margin: 5px;background: white; color:black; padding: 5px; border: 1px solid gray; width:{$rightColWidth}px;'>\n\t\t\t\t<tr><td>{$from}</td></tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td style='padding: 5px;' align='right' width='{$leftColWidth}'>Para:</td>\n\t\t\t<td align='left'>\n\t\t\t\t<table cellspacing='0' cellpadding='0' style='font-size: 12px;font-family: Lucida console; margin: 5px;background: white; color:black; width:350px; padding: 5px; border: 1px solid gray;width:{$rightColWidth}px;'>\n\t\t\t\t<tr><td>{$to}</td></tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td style='padding: 5px;' align='right' width='{$leftColWidth}'>Asunto:</td>\n\t\t\t<td align='left'>\n\t\t\t\t<table cellspacing='0' cellpadding='0' style='font-size: 12px;font-family: Lucida console; margin: 5px; background: white; color:black; padding: 5px; border: 1px solid gray;width:{$rightColWidth}px;' type='text'>\n\t\t\t\t<tr><td>{$subject}</td></tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td valign='top' style='font-size: 12px;padding: 5px; background: white; border-top: 1px solid gray; height:100px; text-align: justify;' colspan='2'>{$body}</td>\n\t\t</tr>\n\t</table>"; }
/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_link($params, $template) { // get params $href = $params["href"]; $caption = $params["caption"]; // get the body if exist if (isset($params["body"])) { $body = $params["body"]; } else { $body = "Envie+el+correo+tal+y+como+esta,+ya+esta+preparado+para+usted"; } // create direct link for the sandbox $di = \Phalcon\DI\FactoryDefault::getDefault(); if ($di->get('environment') == "sandbox") { $wwwhttp = $di->get('path')['http']; $linkto = "{$wwwhttp}/run/display?subject={$href}&body={$body}"; } else { $utils = new Utils(); $validEmailAddress = $utils->getValidEmailAddress(); $linkto = "mailto:{$validEmailAddress}?subject={$href}&body={$body}"; } // create and return button return "<a href='{$linkto}'>{$caption}</a>"; }
/** * Function executed when the service is called * * @param Request * @return Response * */ public function _main(Request $request) { $utils = new Utils(); $amount = false; $receiver = false; // get the email and the amount to send foreach (explode(" ", $request->query) as $value) { // check if it is a valid email if (filter_var($value, FILTER_VALIDATE_EMAIL)) { $receiver = $value; } // check if it is a valid money amount $number = str_replace(",", ".", $value); if (preg_match("/^-?[0-9]+(?:\\.[0-9]{1,2})?\$/", $number)) { $amount = $number; } } // return error response if the receiver or the amount are wrong if (empty($amount) || empty($receiver)) { if (empty($receiver)) { $message = "El email de la persona a recibir no es correcto. Puede que usted halla escrito el email mal por error."; } else { $message = "La cantidad insertada no es correcta, parece que usted inserto un número que no es válido."; } // update the valid email on the usage text $validEmailAddress = $utils->getValidEmailAddress(); $usage = str_replace('{APRETASTE_EMAIL}', $validEmailAddress, $this->serviceUsage); // send response to the user $responseContent = array("message" => $message, "query" => $request->query, "help" => nl2br($usage)); $response = new Response(); $response->subject = "El email o la cantidad a transferir son incorrectas"; $response->createFromTemplate("invalid.tpl", $responseContent); return $response; } // check if the person exist. If not, message the requestor if (!$utils->personExist($receiver)) { $responseContent = array("email" => $receiver); $response = new Response(); $response->subject = "El email del destinatario no existe"; $response->createFromTemplate("inexistent.tpl", $responseContent); return $response; } // check if you have enough credit to transfer $profile = $utils->getPerson($request->email); if ($profile->credit < $amount) { // send response to the user $responseContent = array("amount" => $amount, "credit" => $profile->credit, "email" => $receiver); $template = "nocredit.tpl"; if ($request->subject == "PURCHASE") { $template = "nocreditPurchase.tpl"; $responseContent = array_merge($responseContent, array("nameOfItemToPurchase" => $request->body)); } $response = new Response(); $response->subject = "Usted no tiene suficiente credito"; $response->createFromTemplate($template, $responseContent); return $response; } // save the transfer intention in the database $confirmationHash = $utils->generateRandomHash(); $inventory_code = $request->subject == "PURCHASE" ? $request->name : "NULL"; $query = "INSERT INTO transfer(sender,receiver,amount,confirmation_hash,inventory_code) VALUES ('{$request->email}', '{$receiver}', '{$amount}', '{$confirmationHash}', '{$inventory_code}')"; $connection = new Connection(); $connection->deepQuery($query); // create the variables for the view $template = "confirmation.tpl"; $responseContent = array("amount" => $amount, "receiver" => $receiver, "hash" => $confirmationHash); if ($request->subject == "PURCHASE") { $template = "confirmPurchase.tpl"; $responseContent = array_merge($responseContent, array("nameOfItemToPurchase" => $request->body)); } // email the confirmation to transfer the credits $response = new Response(); $response->subject = "Necesitamos su confirmacion para continuar"; $response->createFromTemplate($template, $responseContent); 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; }
/** * Respond to a request based on the parameters passed * @author salvipascual * */ private function renderResponse($email, $subject, $sender = "", $body = "", $attachments = array(), $format = "html") { // get the name of the service based on the subject line $subjectPieces = explode(" ", $subject); $serviceName = strtolower($subjectPieces[0]); unset($subjectPieces[0]); // get path to the service $utils = new Utils(); $servicePath = $utils->getPathToService($serviceName); // check the service requested exists in the services folder if (!$servicePath) { return "<p>No service \"{$serviceName}\" was found</p>"; } // include the service code include_once "{$servicePath}/service.php"; // check if a subservice is been invoked $subServiceName = ""; if (isset($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 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); $serviceInsertionDate = date("Y/m/d H:m:s"); // check if the email is valid if (!filter_var($serviceCreatorEmail, FILTER_VALIDATE_EMAIL)) { die("Invalid email {$serviceCreatorEmail}"); } // check if the category is valid $categories = array('negocios', 'ocio', 'academico', 'social', 'comunicaciones', 'informativo', 'adulto', 'otros'); if (!in_array($serviceCategory, $categories)) { die("Invalid category {$serviceCategory}"); } // 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->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); // clean the empty fields in the response foreach ($responses as $rs) { $rs->email = empty($rs->email) ? $email : $rs->email; $rs->subject = empty($rs->subject) ? "Respuesta del servicio {$serviceName}" : $rs->subject; } // 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>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); } // false if no action could be taken return false; }
/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_button($params, $template) { // get params $href = $params["href"]; $caption = $params["caption"]; $color = isset($params["color"]) ? $params["color"] : "green"; $size = isset($params["size"]) ? $params["size"] : "medium"; // get the body if exist if (isset($params["body"])) { $body = $params["body"]; } else { $body = "Envie+el+correo+tal+y+como+esta,+ya+esta+preparado+para+usted"; } // select the color scheema switch ($color) { case "grey": $stroke = '#CCCCCC'; $fill = '#E6E6E6'; $text = '#000000'; break; case "blue": $stroke = '#2E6DA4'; $fill = '#337AB7'; $text = '#FFFFFF'; break; case "red": $stroke = '#D43F3A'; $fill = '#D9534F'; $text = '#FFFFFF'; break; default: $stroke = '#5dbd00'; $fill = '#5EBB47'; $text = '#FFFFFF'; } // get the size of the button switch ($size) { case "small": $width = 80; $fontsize = 12; $height = 20; break; case "medium": $width = 150; $fontsize = 16; $height = 44; break; case "large": $width = 220; $fontsize = 24; $height = 48; break; } // create direct link for the sandbox $di = \Phalcon\DI\FactoryDefault::getDefault(); if ($di->get('environment') == "sandbox") { $wwwhttp = $di->get('path')['http']; $linkto = "{$wwwhttp}/run/display?subject={$href}&body={$body}"; } else { $utils = new Utils(); $validEmailAddress = $utils->getValidEmailAddress(); $linkto = "mailto:{$validEmailAddress}?subject={$href}&body={$body}"; } // create and return button return "<!--[if mso]>\n\t\t<v:roundrect xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w='urn:schemas-microsoft-com:office:word' href='{$linkto}' style='height:{$height}px;v-text-anchor:middle;width:{$width}px;' arcsize='5%' strokecolor='{$stroke}' fillcolor='{$fill}'>\n\t\t<w:anchorlock/>\n\t\t<center style='color:{$text};font-family:Helvetica, Arial,sans-serif;font-size:{$fontsize}px;'>{$caption}</center>\n\t\t</v:roundrect>\n\t<![endif]-->\n\t<a href='{$linkto}' style='background-color:{$fill};border:1px solid {$stroke};border-radius:3px;color:{$text};display:inline-block;font-family:sans-serif;font-size:{$fontsize}px;line-height:{$height}px;text-align:center;text-decoration:none;width:{$width}px;-webkit-text-size-adjust:none;mso-hide:all;'>{$caption}</a>"; }
/** * Get an article from wikipedia * * @author salvipascual * @param String: text to search * @return Mixed */ private function get($query) { $utils = new Utils(); // get path to the www folder $di = \Phalcon\DI\FactoryDefault::getDefault(); $wwwroot = $di->get('path')['root']; // get the url $url = "http://es.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects=1&titles={$query}&rvparse"; $page = file_get_contents($url); // if data was found ... if (strpos($page, 'missing=""') === false) { // decode the text from UTF8 and convert to ISO, which supports Spanish if (mb_check_encoding($page, 'UTF8')) { $page = utf8_decode($page); } $page = html_entity_decode($page, ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); // remove everything between the index and external links $mark = '<rev xml:space="preserve">'; $page = substr($page, strpos($page, $mark) + strlen($mark)); $page = str_replace('</rev></revisions></page></pages></query></api>', '', $page); $page = strip_tags($page, '<a><!--><!DOCTYPE><abbr><acronym><address><area><article><aside><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><command><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><head><header><h1> - <h6><hr><html><i><iframe><img><input><ins><kbd><keygen><label><legend><li><link><map><mark><menu><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><table><tbody><td><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><wbr><h2><h3>'); $page = str_replace('oding="UTF-8"?>', '', $page); // removing the brackets [] $page = preg_replace('/\\[([^\\[\\]]++|(?R))*+\\]/', '', $page); // remove the table of contents $mark = '<div id="toc" class="toc">'; $p1 = strpos($page, $mark); if ($p1 !== false) { $p2 = strpos($page, '</div>', $p1); if ($p2 !== false) { $p2 = strpos($page, '</div>', $p2 + 1); $page = substr($page, 0, $p1) . substr($page, $p2 + 6); } } // remove external links $mark = '<span class="mw-headline" id="Enlaces_externos'; $p = strpos($page, $mark); if ($p !== false) { $page = substr($page, 0, $p - 4); } // remove other stuff $page = str_replace("</api>", "", $page); $page = str_replace("<api>", "", $page); // remove references links $p = strpos($page, '<h2><span class="mw-headline" id="Referencias">'); if ($p !== false) { $part = substr($page, $p); $part = strip_tags($part, '<li><ul><span><h2><h3>'); $page = substr($page, 0, $p) . $part; } // clean the page $page = str_replace('>?</span>', '></span>', $page); $page = trim($page); if (!empty($page)) { // Build our DOMDocument, and load our HTML $doc = new DOMDocument(); @$doc->loadHTML($page); // New-up an instance of our DOMXPath class $xpath = new DOMXPath($doc); // Find all elements whose class attribute has test2 $elements = $xpath->query("//*[contains(@class,'thumb')]"); // Cycle over each, remove attribute 'class' foreach ($elements as $element) { // Empty out the class attribute value $element->parentNode->removeChild($element); } // get the title from the response $nodes = $xpath->query("//th[contains(@class, 'cabecera')]"); if ($nodes->length > 0) { $title = htmlentities(trim($nodes->item(0)->textContent), ENT_COMPAT, 'UTF-8'); } else { $title = urldecode(ucwords($query)); } // make the suggestion smaller and separate it from the table $nodes = $xpath->query("//div[contains(@class, 'rellink')]"); if ($nodes->length > 0) { $nodes->item(0)->setAttribute("style", "font-size:small;"); $nodes->item(0)->appendChild($doc->createElement("br")); $nodes->item(0)->appendChild($doc->createElement("br")); } // make the table centered $nodes = $xpath->query("//table[contains(@class, 'infobox')]"); if ($nodes->length > 0) { $nodes->item(0)->setAttribute("border", "1"); $nodes->item(0)->setAttribute("width", "100%"); $nodes->item(0)->setAttribute('style', 'width:100%;'); } // make the quotes takes the whole screen $nodes = $xpath->query("//table[contains(@class, 'wikitable')]"); for ($i = 0; $i < $nodes->length; $i++) { $nodes->item($i)->setAttribute("width", "100%"); $nodes->item($i)->setAttribute("style", "table-layout:fixed; width:100%;"); } // remove all the noresize resources that makes the page wider $nodes = $xpath->query("//*[contains(@class, 'noresize')]"); for ($i = 0; $i < $nodes->length; $i++) { $nodes->item($i)->parentNode->removeChild($nodes->item($i)); } // Load images $imagestags = $doc->getElementsByTagName("img"); $images = array(); if ($imagestags->length > 0) { foreach ($imagestags as $imgtag) { // get the full path to the image $imgsrc = $imgtag->getAttribute('src'); if (substr($imgsrc, 0, 2) == '//') { $imgsrc = 'https:' . $imgsrc; } // ignore all images but the main image if (stripos($imgsrc, '/static/') !== false || stripos($imgsrc, 'increase') !== false || stripos($imgsrc, 'check') !== false || stripos($imgsrc, 'mark') !== false || stripos($imgsrc, 'emblem') !== false || stripos($imgsrc, 'symbol_comment') !== false || stripos($imgsrc, '.svg') !== false) { continue; } // save image as a png file $filePath = "{$wwwroot}/temp/" . $utils->generateRandomHash() . ".png"; $content = file_get_contents($imgsrc); imagepng(imagecreatefromstring($content), $filePath); // optimize the png image $utils->optimizeImage($filePath); // save the image in the array for the template $images[] = $filePath; break; // we need an array containing only the first, valid image } } // remove all the <a> linking images $nodes = $xpath->query("//a[contains(@class, 'image')]"); for ($i = 0; $i < $nodes->length; $i++) { $nodes->item($i)->parentNode->removeChild($nodes->item($i)); } // Output the HTML of our container $page = $doc->saveHTML(); // cleanning the text to look better in the email $page = str_replace("<br>", "<br>\n", $page); $page = str_replace("<br/>", "<br/>\n", $page); $page = str_replace("</p>", "</p>\n", $page); $page = str_replace("</h2>", "</h2>\n", $page); $page = str_replace("</span>", "</span>\n", $page); $page = str_replace("/>", "/>\n", $page); $page = str_replace("<p", "<p style=\"text-align:justify;\" align=\"justify\"", $page); $page = wordwrap($page, 200, "\n"); // convert the links to emails $apretasteValidEmailAddress = $utils->getValidEmailAddress(); $page = str_replace("href=\"/wiki/", 'href="mailto:' . $apretasteValidEmailAddress . '?subject=WIKIPEDIA ', $page); // strip unnecessary, dangerous tags $page = strip_tags($page, '<a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><br><button><canvas><caption><center><cite><code><col><colgroup><command><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><head><header><h1> - <h6><hr><i><iframe><input><ins><kbd><keygen><label><legend><li><link><map><mark><menu><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><table><tbody><td><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video><wbr><h2><h3>'); // compress the returning code $page = preg_replace('/\\s+/S', " ", $page); // if the result is too big, hide images and shorten text $limit = 1024 * 450; $isLarge = false; if (strlen($page) > $limit) { $isLarge = true; $images = array(); $page = substr($page, 0, $limit); } // save content into pages that will go to the view return array("title" => $title, "body" => $page, "images" => $images, "isLarge" => $isLarge); } } return false; }