/** * Get Enum Column values * * @access public * @param {string} $columnName * @return {array} */ public function getEnumValues($columnName = null) { $di = PhDi::getDefault(); if ($columnName == null) { return array(); } $sql = "SHOW COLUMNS FROM `" . $this->getSource() . "` LIKE '{$columnName}'"; $resultSet = $di['db']->query($sql); $resultSet->setFetchMode(Phalcon\Db::FETCH_ASSOC); $result = $resultSet->fetchAll($resultSet); if (!empty($result)) { $types = null; if (isset($result[0]['Type'])) { $types = $result[0]['Type']; } else { return array(); } $values = explode("','", preg_replace("/(enum)\\('(.+?)'\\)/", "\\2", $types)); $assoc_values = array(); foreach ($values as $value) { $assoc_values[$value] = ucwords(str_replace('_', ' ', $value)); } return $assoc_values; } return false; }
/** * @param $name * @param $message * @param $type */ public static function log($name, $message, $type) { $typeName = self::getTypeString($type); $logger = FactoryDefault::getDefault()->get('logger'); $logger->name = $name; $logger->{$typeName}($message); }
/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_apretaste_support_email($params, $template) { // get the support email from the configs $di = \Phalcon\DI\FactoryDefault::getDefault(); $supportEmail = $di->get("config")["contact"]["support"]; return $supportEmail; }
/** * Render the template and return the HTML content * * @author salvipascual * @param Service $service, service to be rendered * @param Response $response, response object to render * @return String, template in HTML * @throw Exception */ public function renderHTML($service, $response) { // get the path $di = \Phalcon\DI\FactoryDefault::getDefault(); $wwwroot = $di->get('path')['root']; // select the right file to load if ($response->internal) { $userTemplateFile = "{$wwwroot}/app/templates/{$response->template}"; } else { $userTemplateFile = "{$wwwroot}/services/{$service->serviceName}/templates/{$response->template}"; } // creating and configuring a new Smarty object $smarty = new Smarty(); $smarty->addPluginsDir("{$wwwroot}/app/plugins/"); $smarty->setTemplateDir("{$wwwroot}/app/layouts/"); $smarty->setCompileDir("{$wwwroot}/temp/templates_c/"); $smarty->setCacheDir("{$wwwroot}/temp/cache/"); // disabling cache and debugging $smarty->force_compile = true; $smarty->debugging = false; $smarty->caching = false; // list the system variables $systemVariables = array("APRETASTE_USER_TEMPLATE" => $userTemplateFile, "APRETASTE_SERVICE_NAME" => strtoupper($service->serviceName), "APRETASTE_SERVICE_RELATED" => $this->getServicesRelatedArray($service->serviceName), "APRETASTE_SERVICE_CREATOR" => $service->creatorEmail, "APRETASTE_TOP_AD" => "", "APRETASTE_BOTTOM_AD" => ""); // merge all variable sets and assign them to Smarty $templateVariables = array_merge($systemVariables, $response->content); $smarty->assign($templateVariables); // renderig and removing tabs, double spaces and break lines $renderedTemplate = $smarty->fetch("email_default.tpl"); return preg_replace('/\\s+/S', " ", $renderedTemplate); }
/** * Sends an email using MailGun * @author salvipascual * @param String $to, email address of the receiver * @param String $subject, subject of the email * @param String $body, body of the email in HTML * @param Array $images, paths to the images to embeb * @param Array $attachments, paths to the files to attach * */ public function sendEmail($to, $subject, $body, $images = array(), $attachments = array()) { // do not email if there is an error $response = $this->deliveryStatus($to); if ($response != 'ok') { return; } // select the from email using the jumper $from = $this->nextEmail($to); $domain = explode("@", $from)[1]; // create the list of images if (!empty($images)) { $images = array('inline' => $images); } // crate the list of attachments // TODO add list of attachments // create the array send $message = array("from" => "Apretaste <{$from}>", "to" => $to, "subject" => $subject, "html" => $body, "o:tracking" => false, "o:tracking-clicks" => false, "o:tracking-opens" => false); // get the key from the config $di = \Phalcon\DI\FactoryDefault::getDefault(); $mailgunKey = $di->get('config')['mailgun']['key']; // send the email via MailGun $mgClient = new Mailgun($mailgunKey); $result = $mgClient->sendMessage($domain, $message, $images); }
/** * Write error to log * * @param $type * @param $message * @param $file * @param $line * @param string $trace * @throws \Phalcon\Exception */ protected static function logError($type, $message, $file, $line, $trace = '') { $di = Di::getDefault(); $template = "[%s] %s (File: %s Line: [%s])"; $logMessage = sprintf($template, $type, $message, $file, $line); if ($di->has('profiler')) { $profiler = $di->get('profiler'); if ($profiler) { $profiler->addError($logMessage, $trace); } } if ($trace) { $logMessage .= $trace . PHP_EOL; } else { $logMessage .= PHP_EOL; } if ($di->has('logger')) { $logger = $di->get('logger'); if ($logger) { $logger->error($logMessage); } else { throw new PhException($logMessage); } } else { throw new PhException($logMessage); } }
/** * Escape dangerous strings before passing it to mysql * * @author salvipascual * @param String $str, text to scape * @return String, scaped text ready to be sent to mysql * */ public function escape($str) { // get the scaped string $di = \Phalcon\DI\FactoryDefault::getDefault(); $safeStr = $di->get('db')->escapeString($str); // remove the ' at the beginning and end of the string return substr(substr($safeStr, 0, -1), 1); }
/** * Creates the profiler and starts the logging */ public function __construct() { $this->_profiler = new Profiler(); $di = Di::getDefault(); if ($di->has('loggerDb')) { $this->_logger = $di->get('loggerDb'); } }
public function countMediumtypeClippings($mediumtype) { $config = \Phalcon\DI\FactoryDefault::getDefault()->getShared('config'); $modelsManager = $this->getDi()->getShared('modelsManager'); $phql = 'SELECT COUNT(clippings.uid) as clippingscount, SUM(medium.reach) as mediumreach FROM reportingtool\\Models\\Clippings as clippings LEFT JOIN reportingtool\\Models\\Projects as projects ON projects.uid=clippings.pid LEFT JOIN reportingtool\\Models\\Medium as medium ON medium.uid=clippings.mediumuid ' . 'WHERE medium.deleted =0 AND medium.hidden=0 AND clippings.deleted=0 AND clippings.hidden =0 AND projects.deleted=0 AND projects.hidden = 0 AND medium.mediumtype = ?1'; $sQuery = $modelsManager->createQuery($phql); $rResults = $sQuery->execute(array(1 => $mediumtype)); return $rResults[0]; }
public function __construct() { $this->config = DI::getDefault()->get('config'); $this->searcher = new SphinxClient(); $this->searcher->SetServer($this->config->app_sphinx->host, $this->config->app_sphinx->port); $this->searcher->SetConnectTimeout(1); $this->searcher->SetArrayResult(true); $this->searcher->SetMatchMode(SPH_MATCH_EXTENDED2); $this->searcher->SetRankingMode(SPH_RANK_PROXIMITY_BM25); }
public function render($attributes = NULL) { // Konfiguration beziehen $config = FactoryDefault::getDefault()->getConfig(); // HTML-Code erzeugen $html = '<div class="g-recaptcha" data-sitekey="%1$s"></div>'; $html .= '<script src="//www.google.com/recaptcha/api.js?hl=%2$s"></script>'; // Platzhalter füllen und HTML zurückgeben return sprintf($html, $config->ReCaptcha->siteKey, $config->ReCaptcha->language); }
/** * Gets the dependency injector * @return DiInterface */ public function getDi() { if (is_null($this->di)) { $this->di = FactoryDefault::getDefault(); if (is_null($this->di)) { $this->di = new FactoryDefault(); } } return $this->di; }
public function beforeSave() { $path = dirname(__FILE__); $di = Di::getDefault(); foreach ($this->behaviors as $behavior => $active) { if ($active && $di->has($behavior)) { $di->get($behavior)->beforeSave($this); } } }
/** * Get the user that owns the subscription. */ public function user() { $di = FactoryDefault::getDefault(); $stripe = $di->getConfig()->stripe; $model = $stripe->model ?: getenv('STRIPE_MODEL'); if (!isset($model)) { throw new Exception('You need add config model for stripe!'); } $this->belongsTo('user_id', $model, 'id', ['alias' => 'user']); return $this->getRelated('user'); }
public function toFormat($data) { $callback = isset($_GET['callback']) && !empty($_GET['callback']) ? $_GET['callback'] . '(' : ''; $suffix = !empty($callback) ? ');' : ''; $data = $callback . json_encode($data) . $suffix; $error = json_last_error(); if (empty($data) && $error != JSON_ERROR_NONE) { $di = \Phalcon\DI\FactoryDefault::getDefault(); $di['response']->internalServerError('Unable to write format.'); } return $data; }
public function __construct($host, $port = 3306, $user, $password, $database, $charset, $params = null) { if (!isset($params)) { $params = array('debug' => false); } $this->_host = $host; $this->_port = $port; $this->_user = $user; $this->_password = $password; $this->_database = $database; $this->_charset = $charset; $this->_debug = $params['debug']; $this->_di = \Phalcon\DI\FactoryDefault::getDefault(); }
public function beforeDispatch(Event $event, Dispatcher $dispatcher) { $di = PhDi::getDefault(); // global config $config = $di['config']; // Take the active controller/action from the dispatcher $controller = $dispatcher->getControllerName(); $action = $dispatcher->getActionName(); // No ACL checks for AccessController if ($controller == 'access') { return true; } // Check whether the "auth" variable exists in session to define the active role $auth = $this->session->get('auth'); if (!$auth) { // user not logged in $dispatcher->forward(array('controller' => 'access', 'action' => 'signin')); return false; } else { $role = $auth['role']; } // Check whether acl data already exist $aclFileName = $config->application['securityDir'] . "acl.data"; if (!is_file($aclFileName)) { // Obtain the ACL list $acl = $this->getAcl(); // Store serialized list into plain file file_put_contents($aclFileName, serialize($acl)); } else { //Restore acl object from serialized file $acl = unserialize(file_get_contents($aclFileName)); } // Check if the Role have access to the controller (resource) $allowed = $acl->isAllowed($role, $controller, $action); if ($allowed != Acl::ALLOW) { // If user doesn't have access forward to the index controller $flashMessage = <<<EOT <div class="alert alert-block alert-danger"> <a class="close" data-dismiss="alert" href="#">×</a> <h4 class="alert-heading">Error!</h4> You don't have access to this module. </div> EOT; $this->flashSession->warning($flashMessage); $dispatcher->forward(array('controller' => 'index', 'action' => 'index')); // Returning "false" will tell to the dispatcher to stop the current operation return false; } }
public function createTransaction($params = array()) { $di = \Phalcon\DI\FactoryDefault::getDefault(); $class = $this->type . 'Transactions'; if (substr($class, 0, 1) !== '/') { $class = '\\PhashionBaker\\Payments\\' . $class; } $instance = new $class($params); if ($instance instanceof I_Transactions) { $instance->authenticate($this); return $instance; } else { throw new Phalcon\Exception('Your transaction must implement I_Transactions.'); } }
public function toFormat($data) { try { if (!is_int(key($data))) { Array2XML::init('1.0', 'UTF-8', false); $xml = Array2XML::createXML($this->options['root'], $data); return $xml->saveXML(); } else { Array2XML::init('1.0', 'UTF-8', false); $xml = Array2XML::createXML($this->options['list'], array($this->options['root'] => $data)); return $xml->saveXML(); } } catch (\Exception $e) { $di = \Phalcon\DI\FactoryDefault::getDefault(); $di['response']->internalServerError('Unable to write format.'); } }
public function initialize() { $di = PhDi::getDefault(); // initiate filter object $this->filter = new \Phalcon\Filter(); // global response $this->response = new \Phalcon\Http\Response(); // global config $this->config = $di['config']; // get current controller and action names $currentControllerName = $di['router']->getControllerName(); $currentActionName = $di['router']->getActionName(); // navigation $this->view->setVar('selLeftNav', null); if ($currentControllerName == 'index' && $currentActionName == 'index') { $this->view->setVar('selLeftNav', 'Dashboard'); } else { $this->view->setVar('selLeftNav', $currentControllerName); } // shortcut selection $this->view->setVar('selShortcutNav', null); switch ($currentControllerName) { case 'user': $this->view->setVar('selShortcutNav', $currentActionName); break; } // user name $userSession = $this->session->get('auth'); if (!empty($userSession)) { $this->userSession = $userSession; $this->view->setVar('sessionUserName', $userSession['first_name'] . ' ' . $userSession['last_name']); $this->view->setVar('sessionUserRole', $userSession['role']); } else { $this->view->setVar('sessionUserName', 'john.doe'); $this->view->setVar('sessionUserRole', 'user'); } // default page title icon $this->view->pageTitleIcon = '<i class="fa-fw fa fa-home"></i>'; // application name $this->view->appTitle = $this->config->application['appTitle']; // setting environment for view $this->view->setVar('env', $this->config->application['env']); }
public function toFormat($data) { $limit = count($data); if ($limit >= 1) { $fields = array_keys($data[0]); if (!empty($fields)) { $fp = fopen('php://output', 'w'); fputcsv($fp, $fields, $this->options['delimiter'], $this->options['enclosure']); for ($i = 0; $i < $limit; $i++) { fputcsv($fp, $data[$i], $this->options['delimiter'], $this->options['enclosure']); } fclose($fp); } else { $di = \Phalcon\DI\FactoryDefault::getDefault(); $di['response']->internalServerError('Unable to write format.'); } } return ''; }
/** * 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; }
public function validate(Validation $validator, $attributes) { // Konfiguration und Request-Objekt beziehen $di = FactoryDefault::getDefault(); $config = $di->getConfig(); $request = $di->getRequest(); // Googles ReCaptcha-Klasse instanzieren $recaptcha = new ReCaptcha($config->ReCaptcha->secret); // Antwort von ReCaptcha-API beziehen $response = $recaptcha->verify($request->getPost('g-recaptcha-response'), $request->getClientAddress()); // Antwort überprüfen if (!$response->isSuccess()) { // Nachricht dem Validator hinzufügen $validator->appendMessage(new Message($this->getOption('message') ?: 'Bitte ReCaptcha ausfüllen', $attributes, 'ReCaptcha')); // Prüfung fehlgeschlagen return FALSE; } // Erfolgreich return TRUE; }
/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_img($params, $template) { // get params $href = $params["src"]; $alt = isset($params["alt"]) ? $params["alt"] : ""; $width = isset($params["width"]) ? "width='{$params["width"]}'" : ""; $height = isset($params["height"]) ? "height='{$params["height"]}'" : ""; $file = basename($href); $di = \Phalcon\DI\FactoryDefault::getDefault(); if ($di->get('environment') == "sandbox") { $wwwroot = $di->get('path')['root']; $wwwhttp = $di->get('path')['http']; copy($href, "{$wwwroot}/public/temp/{$file}"); $destination = "{$wwwhttp}/temp/{$file}"; } else { $destination = "cid:{$file}"; } // create and return image return "<img src='{$destination}' alt='{$alt}' {$width} {$height} />"; }
public function deepQuery($sql) { // get the database connection $di = \Phalcon\DI\FactoryDefault::getDefault(); // only fetch for selects if (stripos($sql, "select") === 0) { // query the database $result = $di->get('db')->query($sql); $result->setFetchMode(Phalcon\Db::FETCH_OBJ); // convert to array of objects $rows = array(); while ($data = $result->fetch()) { $rows[] = $data; } // return the array of objects return $rows; } else { // execute statement in the database return $di->get('db')->execute($sql); } }
/** * Sends an email using MailGun * * @author salvipascual * @param String $to, email address of the receiver * @param String $subject, subject of the email * @param String $body, body of the email in HTML * @param Array $images, paths to the images to embeb * @param Array $attachments, paths to the files to attach * */ public function sendEmail($to, $subject, $body, $images = array(), $attachments = array()) { // do not email if there is an error $utils = new Utils(); $status = $utils->deliveryStatus($to); if ($status != 'ok') { return false; } // select the right email to use as From $from = $this->nextEmail($to); // create the list of images and attachments $embedded = array(); if (!empty($images)) { $embedded['inline'] = $images; } if (!empty($attachments)) { $embedded['attachment'] = $attachments; } // create the array send $message = array("from" => "Apretaste <{$from}>", "to" => $to, "subject" => $subject, "html" => $body, "o:tracking" => false, "o:tracking-clicks" => false, "o:tracking-opens" => false, "h:X-service" => "Apretaste"); // adding In-Reply-To header (creating conversation with the user) if ($this->messageid) { $message["h:In-Reply-To"] = $this->messageid; } // send the email via MailGun. Never send emails from the sandbox $di = \Phalcon\DI\FactoryDefault::getDefault(); if ($di->get('environment') != "sandbox") { $mailgunKey = $di->get('config')['mailgun']['key']; $mgClient = new Mailgun($mailgunKey); $result = $mgClient->sendMessage($this->domain, $message, $embedded); // @TODO return false when negative $result } // save a trace that the email was sent $haveImages = empty($images) ? 0 : 1; $haveAttachments = empty($attachments) ? 0 : 1; $this->conn->deepQuery("INSERT INTO delivery_sent(mailbox,user,subject,images,attachments,domain) VALUES ('{$from}','{$to}','{$subject}','{$haveImages}','{$haveAttachments}','{$this->domain}')"); return true; }
/** * 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) { // do not allow blank searches if (empty($request->query)) { $response = new Response(); $response->setResponseSubject("De donde sacamos el mapa?"); $response->createFromText("Usted no ha insertado ninguna dirección, coordenadas o lugar famoso a buscar. Inserte el texto en el asunto del email, justo después de la palabra MAPA.<br/><br/>Por ejemplo: Asunto: <b>MAPA capitolio, cuba</b>"); return $response; } // include google maps library require_once "{$this->pathToService}/lib/GoogleStaticMap.php"; require_once "{$this->pathToService}/lib/GoogleStaticMapFeature.php"; require_once "{$this->pathToService}/lib/GoogleStaticMapFeatureStyling.php"; require_once "{$this->pathToService}/lib/GoogleStaticMapMarker.php"; require_once "{$this->pathToService}/lib/GoogleStaticMapPath.php"; require_once "{$this->pathToService}/lib/GoogleStaticMapPathPoint.php"; // get and clean the argument $argument = $request->query; $argument = str_replace("\n", " ", $argument); $argument = str_replace("\r", "", $argument); $argument = trim(strtolower($argument)); // detecting type $type = 'hibrido'; $internalType = "hybrid"; if (stripos($argument, 'fisico') !== false) { $type = 'fisico'; $internalType = "satellite"; } elseif (stripos($argument, 'politico') !== false) { $type = 'politico'; $internalType = "roadmap"; } elseif (stripos($argument, 'terreno') !== false) { $type = 'terreno'; $internalType = "terrain"; } // remove the type from the query to display on the template $argument = str_ireplace($type, '', $argument); // detecting zoom $zoom = null; for ($i = 22; $i >= 1; $i--) { if (stripos($argument, $i . 'x') !== false) { $zoom = $i; $argument = str_ireplace("{$i}x", '', $argument); } } // remove bad starting arguments if (substr($argument, 0, 3) == 'de ') { $argument = substr($argument, 3); } if (substr($argument, 0, 4) == 'del ') { $argument = substr($argument, 4); } // create the map $oStaticMap = new GoogleStaticMap(); $oStaticMap->setScale(1); $oStaticMap->setHeight(400); $oStaticMap->setWidth(400); $oStaticMap->setLanguage("es"); $oStaticMap->setHttps(true); $oStaticMap->setMapType($internalType); if (!is_null($zoom)) { $oStaticMap->setZoom($zoom); } $oStaticMap->setCenter($argument); // get path to the www folder $di = \Phalcon\DI\FactoryDefault::getDefault(); $wwwroot = $di->get('path')['root']; // save the image as a temp file $mapImagePath = "{$wwwroot}/temp/" . $this->utils->generateRandomHash() . ".jpg"; $content = file_get_contents($oStaticMap); file_put_contents($mapImagePath, $content); // optimize the image $this->utils->optimizeImage($mapImagePath); // create the response variables $responseContent = array("type" => $type, "request" => $argument, "zoom" => $zoom, "image" => $mapImagePath); // create the response $response = new Response(); $response->setResponseSubject("Mapa para " . $request->query); $response->createFromTemplate("basic.tpl", $responseContent, array($mapImagePath)); return $response; }
/** * Registers the module auto-loader */ public function registerAutoloaders() { $loader = FactoryDefault::getDefault()->get('loader'); $loader->registerNamespaces(['Site\\Controllers' => APP_URL . 'modules/site/controllers/', 'Plugins' => APP_URL . 'plugins/', 'Models' => APP_URL . 'models/'], true); }
<?php namespace Silar\Misc; $path = \Phalcon\DI\FactoryDefault::getDefault()->get('path'); require_once "{$path->path}app/library/phpexcel/PHPExcel.php"; class PHPExcelConnector { public $data; public $logger; public $account; public $report; public $reportData; public $path; public $filter; public $phpExcelObj; public function __construct() { $this->logger = \Phalcon\DI::getDefault()->get('logger'); $this->path = \Phalcon\DI::getDefault()->get('path'); } public function setAccount(\Account $account) { $this->account = $account; } public function setReport($report) { $this->report = $report; } public function setData($data) {