Esempio n. 1
0
 /**
  * Query the database and returs an array of objects
  * Please use escape() for all texts before creating the $sql
  *
  * @author salvipascual
  * @param String $sql, valid sql query
  * @return Array, list of rows or NULL if it is not a select
  */
 public function deepQuery($sql)
 {
     // get the database connection
     $di = \Phalcon\DI\FactoryDefault::getDefault();
     try {
         // only fetch for selects
         if (stripos(trim($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);
         }
     } catch (PDOException $e) {
         $message = $e->getMessage();
         $query = isset($e->getTrace()[0]['args'][0]) ? $e->getTrace()[0]['args'][0] : "Query not available";
         $wwwroot = $di->get('path')['root'];
         $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/badqueries.log");
         $logger->log("{$message}\nQUERY: {$query}\n");
         $logger->close();
         throw $e;
     }
 }
Esempio n. 2
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();
 }
Esempio n. 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 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'");
 }
Esempio n. 4
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'");
 }
Esempio n. 5
0
 public function testIssues2262()
 {
     $logfile = "unit-tests/logs/file.log";
     @unlink($logfile);
     $logger = new \Phalcon\Logger\Adapter\File($logfile);
     $logger->setFormatter(new \Phalcon\Logger\Formatter\Json());
     $logger->log('This is a message');
     $logger->log("This is an error", \Phalcon\Logger::ERROR);
     $logger->error("This is another error");
     $lines = file($logfile);
     $this->assertEquals(count($lines), 3);
 }
Esempio n. 6
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'");
 }
Esempio n. 7
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'");
 }
Esempio n. 8
0
 /**
  * Initializes the logger
  */
 public function init()
 {
     $di = $this->getDi();
     $eventsManager = $this->getEventsManager();
     $config = $this->_config;
     if ($config->application->logger->enabled) {
         // && $config->installed) {
         $di->set('logger', function () use($config) {
             $logger = new \Phalcon\Logger\Adapter\File($config->application->logger->path . "main.log");
             $formatter = new \Phalcon\Logger\Formatter\Line($config->application->logger->format);
             $logger->setFormatter($formatter);
             return $logger;
         });
     } else {
         $di->set('logger', function () use($config) {
             $logger = new \Phalcon\Logger\Adapter\Syslog($config->application->logger->project, ['option' => LOG_NDELAY, 'facility' => LOG_DAEMON]);
             return $logger;
         });
     }
 }
Esempio n. 9
0
 /**
  * @param $type
  * @param $message
  * @param array $context
  * action
  */
 public function log($type, $message, array $context = NULL)
 {
     $logger = new Logger();
     if ($this->_usebeanstalk) {
         //check beanstalk connect
         try {
             $this->_dependencyInjector['beanstalk']->connect();
         } catch (Exception $err) {
             $this->_usebeanstalk = 0;
         }
     }
     if ($this->_usebeanstalk) {
         //USE BEANSTALK QUEUE
         $logcontext = array('controll' => $context['controll'], 'action' => $context['action'] . 'manager', 'username' => $context['username'], 'deltype' => isset($context['deltype']) ? $context['deltype'] : 0, 'results' => isset($context['results']) ? $context['results'] : 0, 'updatetime' => date('Y-m-d H:i:s'));
         $arr = array('username' => $context['username'], 'msg' => $message, 'loggerlist' => $logcontext);
         $json_arr = json_encode($arr);
         $this->_dependencyInjector['beanstalk']->putInTube('addLogger', $json_arr, array('delay' => 2));
         return true;
     } else {
         $logger->controll = $context['controll'];
         $logger->action = $context['action'];
         $logger->results = isset($context['results']) ? $context['results'] : 0;
         $logger->username = $context['username'];
         $logger->deltype = isset($context['deltype']) ? $context['deltype'] : 0;
         $logger->updatetime = date('Y-m-d H:i:s');
         $logger->msg = $message;
         if (!$logger->save()) {
             $message = ' add log error:' . $message . '|' . join('|', $context);
             $logger = new \Phalcon\Logger\Adapter\File("../app/logs/error.log");
             $logger->log($message);
             return false;
         } else {
             return true;
         }
     }
 }
Esempio n. 10
0
 $di["url"] = function () use($di) {
     $url = new \Phalcon\Mvc\Url();
     $url->setBaseUri($di->get("config")->get("common")["baseuri"]);
     return $url;
 };
 $di["session"] = function () {
     $session = new \Phalcon\Session\Adapter\Files();
     $session->start();
     return $session;
 };
 $di["db"] = function () use($di) {
     $config = $di->get("config")->get("common")["db"];
     $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config["host"], "username" => $config["username"], "password" => $config["password"], "dbname" => $config["dbname"], "charset" => $config["charset"]));
     $eventsManager = new \Phalcon\Events\Manager();
     $dblog = $di->get("config")->get("common")["dblog"];
     $logger = new \Phalcon\Logger\Adapter\File(__DIR__ . $dblog);
     $eventsManager->attach('db:beforeQuery', function ($event, $connection) use($logger) {
         $sqlVariables = $connection->getSQLVariables();
         if (count($sqlVariables)) {
             $logger->log($connection->getSQLStatement() . ' ' . join(', ', $sqlVariables), \Phalcon\Logger::INFO);
         } else {
             $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
         }
     });
     $connection->setEventsManager($eventsManager);
     return $connection;
 };
 $di["dbBackupTool"] = function () use($di) {
     $config = $di->get("config")->get("common")["db"];
     return new \Phalcon_wifi\Common\Ext\DBManager($config["username"], $config["password"], $config["host"], $config["dbname"]);
 };
Esempio n. 11
0
 /**
  * Log message into file, notify the admin on stagging/production
  *
  * @param mixed $messages messages to log
  */
 public static function log($messages)
 {
     $config = \Phalcon\DI::getDefault()->getShared('config');
     $dump = new Dump();
     if ($config->app->env == "development") {
         foreach ($messages as $key => $message) {
             echo $dump->one($message, $key);
         }
         exit;
     } else {
         $logger = new \Phalcon\Logger\Adapter\File(APP_PATH . '/app/common/logs/' . date('Ymd') . '.log', array('mode' => 'a+'));
         $log = '';
         if (is_array($messages) || $messages instanceof \Countable) {
             foreach ($messages as $key => $message) {
                 if (in_array($key, array('alert', 'debug', 'error', 'info', 'notice', 'warning'))) {
                     $logger->{$key}($message);
                 } else {
                     $logger->log($message);
                 }
                 $log .= $dump->one($message, $key);
             }
         } else {
             $logger->log($messages);
             $log .= $dump->one($messages);
         }
         if ($config->app->env != "testing") {
             $email = new Email();
             $email->prepare(__('Something is wrong!'), $config->app->admin, 'error', array('log' => $log));
             if ($email->Send() !== true) {
                 $logger->log($email->ErrorInfo);
             }
         }
         $logger->close();
     }
 }
Esempio n. 12
0
 public static function connect($nodeName)
 {
     $configs = getDI()->get('config');
     $nodes = $configs->database->{$nodeName}->toArray();
     $totalNodes = $configs->database->{$nodeName}->nodes;
     $nodeIds = range(1, intval($totalNodes));
     $nodeId = array_rand($nodeIds);
     $descriptor = array("host" => $nodes['host'][$nodeId], "port" => $nodes['port'][$nodeId], "username" => $nodes['username'][$nodeId], "password" => $nodes['password'][$nodeId], "dbname" => $nodes['dbname'][$nodeId], "options" => array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $nodes['charset'], \PDO::ATTR_TIMEOUT => 3, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION));
     $connection = null;
     $try = 1;
     RECONNECT:
     try {
         $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($descriptor);
     } catch (\Exception $e) {
         error_log("PHP Fatal error:  BullSoft::Db::connect() failed to connect to MySQL in " . __FILE__ . " on line " . __LINE__ . '. Detail: ' . json_encode($descriptor));
         while (!is_object($connection)) {
             // wait for 100ms
             usleep(100000);
             error_log('PHP Notice: BullSoft::Db::connnect() retry to connect to MySQL for the ' . $try . ' time ... ');
             if ($try++ >= 10) {
                 break;
             }
             goto RECONNECT;
         }
         error_log("PHP Fatal error:  BullSoft::Db::connect() finally failed to connect to MySQL in " . __FILE__ . " on line " . __LINE__);
         throw $e;
     }
     $connection->start = time();
     $waitTimeout = $connection->fetchOne("SHOW VARIABLES LIKE 'wait_timeout'", \Phalcon\Db::FETCH_ASSOC);
     $connection->timeout = intval($waitTimeout['Value']);
     // begin debug mode
     $debug = false;
     $logger = null;
     if ((bool) $configs->application->debug && isset($configs->database->{$nodeName}->logger)) {
         if (!file_exists($configs->database->{$nodeName}->logger)) {
             if (mkdir($configs->database->{$nodeName}->logger, 0777, true)) {
                 $debug = true;
                 $logger = new \Phalcon\Logger\Adapter\File($configs->database->{$nodeName}->logger . date("Ymd"));
             } else {
                 error_log("PHP Notice:  BullSoft::Db::connect() permission denied for creating directory " . $configs->database->{$nodeName}->logger);
             }
         } else {
             $debug = true;
             $logger = new \Phalcon\Logger\Adapter\File($configs->database->{$nodeName}->logger . date("Ymd"));
         }
     }
     // end debug mode
     try {
         // event manager
         $evtManager = new \Phalcon\Events\Manager();
         $evtManager->attach('db', function ($event, $connection) use($logger, $debug) {
             if ($event->getType() == 'beforeQuery') {
                 // check timeout to reconnect
                 $idle = time() - $connection->start;
                 if ($idle >= $connection->timeout) {
                     $connection->connect();
                     $connection->start = time();
                 }
                 $sql = $connection->getSQLStatement();
                 // begin debug mode
                 if ($debug == true) {
                     $variables = $connection->getSqlVariables();
                     if (count($variables)) {
                         $query = preg_replace("/('.*?')/", "", $sql);
                         $query = preg_replace('/(\\?)|(:[0-9a-z_]+)/is', "'%s'", $query);
                         $query = vsprintf($query, $variables);
                         $logger->log($query, \Phalcon\Logger::INFO);
                     } else {
                         $logger->log($sql, \Phalcon\Logger::INFO);
                     }
                 }
                 // end debug mode
             }
         });
         $connection->setEventsManager($evtManager);
     } catch (\Exception $e) {
         // can not throw
         error_log("PHP Notice: BullSoft::Db:connect event attach failed");
     }
     return $connection;
 }
Esempio n. 13
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 = "";
     /*
      * FIRST REMINDER
      * */
     // people missed for the last 30 days and with no remarketing emails unopened
     $firstReminderPeople = $connection->deepQuery("\n\t\t\tSELECT email, last_access \n\t\t\tFROM person \n\t\t\tWHERE active=1 \n\t\t\tAND IFNULL(DATEDIFF(CURRENT_DATE, last_access),99) > 30 \n\t\t\tAND email not in (SELECT DISTINCT email FROM remarketing WHERE opened IS NULL)\n\t\t\tORDER BY insertion_date ASC\n\t\t\tLIMIT 200");
     // send the remarketing
     $log .= "\nFIRST REMINDER (" . count($firstReminderPeople) . ")\n";
     foreach ($firstReminderPeople as $person) {
         // check number of days since the email was last checked
         $datediff = time() - strtotime($person->last_access);
         $daysSinceLastChecked = floor($datediff / (60 * 60 * 24));
         // validate old emails to avoid bounces
         if ($daysSinceLastChecked > 60) {
             // re-validate the email
             $res = $utils->deepValidateEmail($person->email);
             // keep it for later if it was temporal
             if ($res[0] == "temporal") {
                 $log .= "\t --skiping {$person->email}\n";
                 continue;
             }
             // for other than ok, unsubscribe and do not email
             if ($res[0] != "ok") {
                 $utils->unsubscribeFromEmailList($person->email);
                 $connection->deepQuery("UPDATE person SET active=0 WHERE email='{$person->email}'");
                 $log .= "\t --skiping {$person->email}\n";
                 continue;
             }
         }
         // get services that changed since last time
         $sql = "SELECT * FROM service WHERE insertion_date BETWEEN '{$person->last_access}' AND CURRENT_TIMESTAMP AND listed=1";
         $services = $connection->deepQuery($sql);
         // create the variabels to pass to the template
         $content = array("services" => $services);
         $images = array("{$wwwroot}/public/images/missyou.jpg");
         // create html response
         $response->createFromTemplate('remindme1.tpl', $content, $images);
         $response->internal = true;
         $html = $render->renderHTML($service, $response);
         // move remarketing to the next state and add $1 to his/her account
         $email->sendEmail($person->email, "Se le extranna por Apretaste", $html, $images);
         // move remarketing to the next state and add +1 credits
         $connection->deepQuery("\n\t\t\t\tSTART TRANSACTION;\n\t\t\t\tUPDATE person SET credit=credit+1 WHERE email='{$person->email}';\r\n\t\t\t\tINSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'REMINDER1');\n\t\t\t\tCOMMIT;");
         // display notifications
         $log .= "\t{$person->email}\n";
     }
     /*
      * SECOND REMINDER
      * */
     // people with REMINDER1 unaswered for the last 30 days, and without REMINDER2 created
     $secondReminderPeople = $connection->deepQuery("\n\t\t\tSELECT email\n\t\t\tFROM remarketing A\n\t\t\tWHERE type='REMINDER1'\n\t\t\tAND opened IS NULL\n\t\t\tAND DATEDIFF(CURRENT_DATE, sent) > 30\n\t\t\tAND (SELECT COUNT(email) FROM remarketing WHERE type='REMINDER2' AND opened IS NULL AND email=A.email)=0");
     // send the remarketing
     $log .= "SECOND REMINDER (" . count($secondReminderPeople) . ")\n";
     foreach ($secondReminderPeople as $person) {
         // create html response
         $response->createFromTemplate('remindme2.tpl', array());
         $response->internal = true;
         $html = $render->renderHTML($service, $response);
         // send email to the $person->email
         $email->sendEmail($person->email, "Hace rato no le veo", $html);
         // move remarketing to the next state and add +1 credits
         $connection->deepQuery("\r\n\t\t\t\tSTART TRANSACTION;\r\n\t\t\t\tUPDATE person SET credit=credit+1 WHERE email='{$person->email}';\n\t\t\t\tINSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'REMINDER2');\r\n\t\t\t\tCOMMIT;");
         // display notifications
         $log .= "\t{$person->email}\n";
     }
     /*
      * EXCLUDE
      * */
     // people with REMINDER2 unaswered, sent 30 days ago and not EXCLUDED
     $thirdReminderPeople = $connection->deepQuery("\n\t\t\tSELECT email\n\t\t\tFROM remarketing A\n\t\t\tWHERE type='REMINDER2'\n\t\t\tAND opened IS NULL\n\t\t\tAND DATEDIFF(CURRENT_DATE, sent) > 30\n\t\t\tAND (SELECT COUNT(email) from remarketing WHERE type='EXCLUDED' AND opened IS NULL AND email=A.email)=0");
     // unsubcribe people
     $log .= "UNSUSCRIBING (" . count($thirdReminderPeople) . ")\n";
     foreach ($thirdReminderPeople as $person) {
         // unsubscribe person
         $utils->unsubscribeFromEmailList($person->email);
         // move remarketing to the next state and unsubscribe
         $connection->deepQuery("\r\n\t\t\t\tSTART TRANSACTION;\r\n\t\t\t\tUPDATE person SET active=0 WHERE email='{$person->email}';\n\t\t\t\tINSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'EXCLUDED');\r\n\t\t\t\tCOMMIT;");
         // display notifications
         $log .= "\t{$person->email}\n";
     }
     // get final delay
     $timeEnd = time();
     $timeDiff = $timeEnd - $timeStart;
     // printing log
     $log .= "EXECUTION TIME: {$timeDiff} seconds\n\n";
     echo $log;
     // saving the log
     $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/remarketing.log");
     $logger->log($log);
     $logger->close();
     // save the status in the database
     $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='remarketing'");
 }
Esempio n. 14
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 = "";
     // list and total of services
     $services = $connection->deepQuery("SELECT name, description FROM service WHERE name <> 'ayuda' AND name <> 'terminos' AND name <> 'excluyeme' AND listed = 1;");
     $arr = array();
     foreach ($services as $servicex) {
         $arr[$servicex->name] = $servicex;
     }
     $services = $arr;
     $total_services = count($services);
     // users by service
     $sql_users_by_service = "SELECT requestor, service FROM utilization WHERE service <> 'rememberme' GROUP BY requestor, service";
     // usage of services
     $sql_usage = "SELECT requestor, count(service) as part, {$total_services} as total FROM ({$sql_users_by_service}) subq1 GROUP BY requestor, total";
     // filtering by less usage
     $sql_less_usage = "SELECT requestor as email, (SELECT sent FROM remarketing WHERE remarketing.email = subq2.requestor ORDER BY sent DESC LIMIT 1) as last_remarketing FROM ({$sql_usage}) subq2 WHERE part/total <= 0.2 ";
     // filtering by last remarketing (one by month)
     $sql = "SELECT email FROM ({$sql_less_usage}) subq3 WHERE datediff(CURRENT_DATE, last_remarketing) > 30 or datediff(CURRENT_DATE, last_remarketing) is null group by email";
     $users = $connection->deepQuery("{$sql};");
     // send the remarketing
     $log .= "\nLESS USAGE REMARKETING (" . count($users) . ")\n";
     foreach ($users as $person) {
         // all services
         $his_services = $services;
         // getting services used by user
         $services_of_user = $connection->deepQuery("SELECT service as name FROM ({$sql_users_by_service}) subq1 WHERE requestor = '{$person->email}';");
         // remove services used by user from the list
         foreach ($services_of_user as $servicex) {
             if (isset($his_services[$servicex->name])) {
                 unset($his_services[$servicex->name]);
             }
         }
         // create the variabels to pass to the template
         $content = array("services" => $his_services);
         // create html response
         $response->createFromTemplate('lessusage.tpl', $content);
         $response->internal = true;
         $html = $render->renderHTML($service, $response);
         // move remarketing to the next state and add $1 to his/her account
         $email->sendEmail($person->email, "Lo que te estas perdiendo en Apretaste", $html);
         // move remarketing to the next state and add +1 credits
         $connection->deepQuery("INSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'LESSUSAGE');");
         // display notifications
         $log .= "\t{$person->email}\n";
     }
     // get final delay
     $timeEnd = time();
     $timeDiff = $timeEnd - $timeStart;
     // printing log
     $log .= "EXECUTION TIME: {$timeDiff} seconds\n\n";
     echo $log;
     // saving the log
     $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/lessusage.log");
     $logger->log($log);
     $logger->close();
     // save the status in the database
     $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='lessusage'");
 }
Esempio n. 15
0
 /**
  * Handle webhook requests
  * @author salvipascual
  * */
 public function webhookAction()
 {
     // get the mandrill json structure from the post
     $mandrill_events = $_POST['mandrill_events'];
     // get values from the json
     $event = json_decode($mandrill_events);
     $fromEmail = $event[0]->msg->from_email;
     $fromName = isset($event[0]->msg->from_name) ? $event[0]->msg->from_name : "";
     $toEmail = $event[0]->msg->email;
     $subject = $event[0]->msg->headers->Subject;
     $body = isset($event[0]->msg->text) ? $event[0]->msg->text : "";
     $filesAttached = empty($event[0]->msg->attachments) ? array() : $event[0]->msg->attachments;
     $attachments = array();
     // create a new connection to the database
     $connection = new Connection();
     // do not email if there is an error
     $email = new Email();
     $status = $email->deliveryStatus($fromEmail);
     if ($status != 'ok') {
         $connection->deepQuery("INSERT INTO delivery_error(incoming_email,apretaste_email,reason) VALUES ('{$fromEmail}','{$toEmail}','{$status}')");
         return;
     }
     // if there are attachments, download them all and create the files in the temp folder
     if (count($filesAttached) > 0) {
         // save the attached files and create the response array
         $utils = new Utils();
         $wwwroot = $this->di->get('path')['root'];
         foreach ($filesAttached as $key => $values) {
             $mimeType = $values->type;
             $content = $values->content;
             $mimeTypePieces = explode("/", $mimeType);
             $fileType = $mimeTypePieces[0];
             $extension = $mimeTypePieces[1];
             $fileNameNoExtension = $utils->generateRandomHash();
             // convert images to png and save it to temporal
             if ($fileType == "image") {
                 // save image as a png file
                 $mimeType = image_type_to_mime_type(IMAGETYPE_PNG);
                 $filePath = "{$wwwroot}/temp/{$fileNameNoExtension}.png";
                 imagepng(imagecreatefromstring(base64_decode($content)), $filePath);
             } else {
                 $filePath = "{$wwwroot}/temp/{$fileNameNoExtension}.{$extension}";
                 $ifp = fopen($filePath, "wb");
                 fwrite($ifp, base64_decode($content));
                 fclose($ifp);
             }
             // create new object
             $object = new stdClass();
             $object->path = $filePath;
             $object->type = $mimeType;
             $attachments[] = $object;
         }
     }
     // update the counter of emails received from that mailbox
     $today = date("Y-m-d H:i:s");
     $connection->deepQuery("UPDATE jumper SET received_count=received_count+1, last_usage='{$today}' WHERE email='{$toEmail}'");
     // save the webhook log
     $wwwroot = $this->di->get('path')['root'];
     $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/webhook.log");
     $logger->log("From: {$fromEmail}, Subject: {$subject}\n{$mandrill_events}\n\n");
     $logger->close();
     // execute the query
     $this->renderResponse($fromEmail, $subject, $fromName, $body, $attachments, "email");
 }
        return $connect;
    } catch (PDOException $e) {
        throw new Exception('Could not connect to database');
    }
});
// Component Session. Starting a Session
$di->setShared('session', function () {
    $session = new Phalcon\Session\Adapter\Memcache(['host' => $this->_config->cache->memcached->host, 'port' => $this->_config->cache->memcached->port, 'lifetime' => $this->_config->cache->lifetime, 'prefix' => $this->_config->cache->prefix, 'persistent' => false]);
    $session->start();
    return $session;
});
// Component Logger. $this->di->get('logger')->log('.....',Logger::ERROR);
$di->setShared('logger', function () {
    if ($this->_config->logger->enable == true) {
        $formatter = new \Phalcon\Logger\Formatter\Line($this->_config->logger->format);
        $logger = new \Phalcon\Logger\Adapter\File($this->_config->logger->file);
        $logger->setFormatter($formatter);
        return $logger;
    }
    return false;
});
/**
 * Component flashSession (Session keep flash messages).
 */
$di->setShared('flash', function () {
    $flash = new Phalcon\Flash\Session(['error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info']);
    return $flash;
});
$di->setShared('cookies', function () {
    $cookies = new \Phalcon\Http\Response\Cookies();
    $cookies->useEncryption(true);
Esempio n. 17
0
<?php

$di->set('db', function () {
    $eventsManager = new \Phalcon\Events\Manager();
    $logger = new \Phalcon\Logger\Adapter\File("app/logs/debug.log");
    //Listen all the database events
    $eventsManager->attach('db', function ($event, $connection) use($logger) {
        if ($event->getType() == 'beforeQuery') {
            $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
        }
    });
    $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => "localhost", "username" => "root", "password" => "secret", "dbname" => "invo"));
    //Assign the eventsManager to the db adapter instance
    $connection->setEventsManager($eventsManager);
    return $connection;
});
Esempio n. 18
0
include 'lib/XmlStringStreamer/ParserInterface.php';
include 'lib/XmlStringStreamer/StreamInterface.php';
include 'lib/XmlStringStreamer/Parser/StringWalker.php';
include 'lib/XmlStringStreamer/Parser/UniqueNode.php';
include 'lib/XmlStringStreamer/Stream/File.php';
include 'lib/XmlStringStreamer/Stream/Stdin.php';
include 'lib/xml2json.php';
require 'lib/mailer/swift_required.php';
require 'lib/Utils.php';
//Config
include "config.php";
//Bootstrap app
$di = new \Phalcon\Di\FactoryDefault();
$app = new \Phalcon\Mvc\Micro($di);
//Set logger
$logger = new \Phalcon\Logger\Adapter\File(LOG_FILE);
//Set error handler
set_error_handler(function ($errno, $errstr, $errfile, $errline) use($app, $logger) {
    $logger->error("{$errno}, {$errstr}, {$errfile}, {$errline}");
});
//Set falar error logging
register_shutdown_function(function () use($logger) {
    $error = error_get_last();
    if (isset($error['type'])) {
        $logger->error("{$error['type']} {$error['message']} {$error['file']} {$error['line']}");
    }
});
//Set mailer
$transport = Swift_SmtpTransport::newInstance(MAIL_SMTP_SERVER, 465, 'ssl');
$transport->setUsername(MAIL_USER);
$transport->setPassword(MAIL_PWD);
Esempio n. 19
0
$di->setShared('db', function () use($config) {
    $dbConfig = $config->database->toArray();
    $adapter = $dbConfig['adapter'];
    unset($dbConfig['adapter']);
    $class = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter;
    return new $class($dbConfig);
});
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->setShared('modelsMetadata', function () {
    return new MetaDataAdapter();
});
$di->setShared('logger', function () use($config) {
    $formatter = new \Phalcon\Logger\Formatter\Line('%date% %type%  %message%');
    $logger = new \Phalcon\Logger\Adapter\File('../phalcon.log');
    $logger->setLogLevel(\Phalcon\Logger::DEBUG);
    $logger->setFormatter($formatter);
    return $logger;
});
/**
 * Start the session the first time some component request the session service
 */
$di->setShared('session', function () {
    $session = new Phalcon\Session\Adapter\Libmemcached(array('servers' => array(array('host' => 'localhost', 'port' => 11211, 'weight' => 1)), 'client' => array(Memcached::OPT_HASH => Memcached::HASH_MD5, Memcached::OPT_PREFIX_KEY => 'prefix.'), 'lifetime' => 3600, 'prefix' => 'my_'));
    $session->start();
    return $session;
});
$di->set('security', function () {
    $security = new \Phalcon\Security();
    $security->setWorkFactor(12);
Esempio n. 20
0
        }
        $volt->setOptions($voltOptions);
        //load function php
        $compiler = $volt->getCompiler();
        //define variable translate
        $compiler->addFunction('t', '_');
        return $volt;
    }));
    return $view;
}, true);
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function () use($config) {
    $eventsManager = new EventsManager();
    $logger = new Phalcon\Logger\Adapter\File(APP_PATH . "/app/log/debug.log");
    //Listen all the database events
    $eventsManager->attach('db', function ($event, $connection) use($logger) {
        if ($event->getType() == 'beforeQuery') {
            $logger->log($connection->getSQLStatement(), Phalcon\Logger::ERROR);
        }
    });
    $connection = new DbAdapter(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname, 'charset' => 'utf8'));
    //Assign the eventsManager to the db adapter instance
    $connection->setEventsManager($eventsManager);
    return $connection;
});
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
/*$di->set('modelsMetadata', function () use ($config) {
Esempio n. 21
0
 /**
  * Process the requests coming by email, usually from webhooks
  *
  * @author salvipascual
  * @param String Email
  * @param String
  * @param String Email
  * @param String
  * @param String
  * @param Array
  * @param Enum mandrill,mailgun
  * @param String
  * @param String $messageID
  * */
 private function processEmail($fromEmail, $fromName, $toEmail, $subject, $body, $attachments, $webhook, $messageID = null)
 {
     $connection = new Connection();
     $utils = new Utils();
     // check if the user is blocked
     $blocked = $connection->deepQuery("SELECT email FROM person WHERE email='{$fromEmail}' AND blocked=1");
     if (count($blocked) > 0) {
         // create the response for blocked email
         $response = new Response();
         $response->setEmailLayout("email_simple.tpl");
         $subject = "Su cuenta de Apretaste ha sido bloqueada";
         $response->setResponseSubject($subject);
         $response->createFromTemplate("blocked.tpl", array());
         $response->internal = true;
         // render the template as html
         $render = new Render();
         $body = $render->renderHTML(new Service(), $response);
         // let the user know that the account is blocked and stop the execution
         $emailSender = new Email();
         $emailSender->setRespondEmailID($messageID);
         $emailSender->sendEmail($fromEmail, $subject, $body);
         exit;
     }
     // if the email comes as part of a campaign, mark it as opened
     $campaign = $utils->getCampaignTracking($toEmail);
     if ($campaign) {
         $connection->deepQuery("\r\n\t\t\t\tUPDATE campaign SET opened=opened+1 WHERE id='{$campaign}';\r\n\t\t\t\tUPDATE campaign_sent SET status='OPENED', date_opened=CURRENT_TIMESTAMP WHERE campaign='{$campaign}' AND email='{$fromEmail}'");
     }
     // do not continue procesing the email if the sender is not valid
     $status = $utils->deliveryStatus($fromEmail, 'in');
     if ($status != 'ok') {
         return;
     }
     // remove double spaces and apostrophes from the subject
     // sorry apostrophes break the SQL code :-(
     $subject = trim(preg_replace('/\\s{2,}/', " ", preg_replace('/\'|`/', "", $subject)));
     // save the email as received
     $connection->deepQuery("INSERT INTO delivery_received(user,mailbox,subject,attachments_count,webhook) VALUES ('{$fromEmail}','{$toEmail}','{$subject}','" . count($attachments) . "','{$webhook}')");
     // save to the webhook last usage, to alert if the web
     $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP WHERE task='{$webhook}'");
     // if there are attachments, download them all and create the files in the temp folder
     $wwwroot = $this->di->get('path')['root'];
     foreach ($attachments as $attach) {
         $mimeTypePieces = explode("/", $attach->type);
         $fileType = $mimeTypePieces[0];
         $fileNameNoExtension = $utils->generateRandomHash();
         // convert images to jpg and save it to temporal
         if ($fileType == "image") {
             $attach->type = image_type_to_mime_type(IMAGETYPE_JPEG);
             $filePath = "{$wwwroot}/temp/{$fileNameNoExtension}.jpg";
             imagejpeg(imagecreatefromstring(base64_decode($attach->content)), $filePath);
             $utils->optimizeImage($filePath);
         } else {
             $extension = $mimeTypePieces[1];
             $filePath = "{$wwwroot}/temp/{$fileNameNoExtension}.{$extension}";
             $ifp = fopen($filePath, "wb");
             fwrite($ifp, $attach->content);
             fclose($ifp);
         }
         // grant full access to the file
         chmod($filePath, 0777);
         $attach->path = $filePath;
     }
     // save the webhook log
     $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/webhook.log");
     $logger->log("Webhook:{$webhook}, From:{$fromEmail}, To:{$toEmail}, Subject:{$subject}, Attachments:" . count($attachments));
     $logger->close();
     // execute the query
     $this->renderResponse($fromEmail, $toEmail, $subject, $fromName, $body, $attachments, "email", $messageID);
 }
Esempio n. 22
0
<?php

$logger = new Phalcon\Logger\Adapter\File("app/logs/test.log");
$logger->log("This is a message");
$logger->log("This is an error", Phalcon\Logger::ERROR);
$logger->error("This is another error");
Esempio n. 23
0
#!/usr/bin/env php
<?php 
//Send email by Gearman queue
require __DIR__ . '/../init_autoloader.php';
$appName = isset($argv[1]) ? $argv[1] : null;
$engine = new \Eva\EvaEngine\Engine(__DIR__ . '/..');
if ($appName) {
    $engine->setAppName($appName);
}
$engine->loadModules(include __DIR__ . '/../config/modules.' . $engine->getAppName() . '.php')->bootstrap();
$worker = $engine->getDI()->getWorker();
$worker->addFunction('sendmailAsync', 'sendmailAsync');
$logger = new Phalcon\Logger\Adapter\File($engine->getDI()->getConfig()->logger->path . 'worker_sendmail.log');
$logger->info(sprintf("Sendmail worker started by appname %s", $engine->getAppName()));
//MySQL interactive_timeout after 8 hours
function refreshDbConnect()
{
    global $engine;
    $di = $engine->getDI();
    $di->getDbMaster()->connect();
    $di->getDbSlave()->connect();
}
function sendmailAsync($job)
{
    global $engine;
    global $logger;
    $jobString = $job->workload();
    $logger->info(sprintf("Start sending mail by %s", $jobString));
    echo sprintf("Start sending mail by %s \n", $jobString);
    try {
        $work = json_decode($jobString, true);
Esempio n. 24
0
 /**
  * Initializes the database and metadata adapter
  */
 public function init()
 {
     $di = $this->getDi();
     $eventsManager = $this->getEventsManager();
     $config = $this->_config;
     $adapter = $this->_getDatabaseAdapter($config->database->adapter);
     if (!$adapter) {
         throw new \Engine\Exception("Database adapter '{$config->database->adapter}' not exists!");
     }
     $connection = new $adapter(["host" => $this->_config->database->host, "username" => $this->_config->database->username, "password" => $this->_config->database->password, "dbname" => $this->_config->database->dbname, "options" => [\PDO::ATTR_EMULATE_PREPARES => false]]);
     if (!$config->application->debug && $config->database->useCache) {
         if ($di->offsetExists('modelsCache')) {
             //$connection->setCache($di->get('modelsCache'));
         }
     }
     if ($config->application->debug) {
         // Attach logger & profiler
         $logger = new \Phalcon\Logger\Adapter\File($config->application->logger->path . "db.log");
         $profiler = new \Phalcon\Db\Profiler();
         $eventsManager->attach('db', function ($event, $connection) use($logger, $profiler) {
             if ($event->getType() == 'beforeQuery') {
                 $statement = $connection->getSQLStatement();
                 $logger->log($statement, \Phalcon\Logger::INFO);
                 $profiler->startProfile($statement);
             }
             if ($event->getType() == 'afterQuery') {
                 //Stop the active profile
                 $profiler->stopProfile();
             }
         });
         if ($this->_config->application->profiler && $di->has('profiler')) {
             $di->get('profiler')->setDbProfiler($profiler);
         }
         $connection->setEventsManager($eventsManager);
     }
     $di->set('db', $connection);
     if (isset($config->database->useAnnotations) && $config->database->useAnnotations) {
         $di->set('modelsManager', function () use($config, $eventsManager) {
             $modelsManager = new \Phalcon\Mvc\Model\Manager();
             $modelsManager->setEventsManager($eventsManager);
             //Attach a listener to models-manager
             $eventsManager->attach('modelsManager', new \Engine\Model\AnnotationsInitializer());
             return $modelsManager;
         }, true);
     }
     /**
      * If the configuration specify the use of metadata adapter use it or use memory otherwise
      */
     $service = $this;
     $di->set('modelsMetadata', function () use($config, $service) {
         if ((!$config->application->debug || $config->application->useCachingInDebugMode) && isset($config->metadata)) {
             $metaDataConfig = $config->metadata;
             $metadataAdapter = $service->_getMetaDataAdapter($metaDataConfig->adapter);
             if (!$metadataAdapter) {
                 throw new \Engine\Exception("MetaData adapter '{$metaDataConfig->adapter}' not exists!");
             }
             $metaData = new $metadataAdapter($config->metadata->toArray());
         } else {
             $metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
         }
         if (isset($config->database->useAnnotations) && $config->database->useAnnotations) {
             $metaData->setStrategy(new \Engine\Model\AnnotationsMetaDataInitializer());
         }
         return $metaData;
     }, true);
 }
Esempio n. 25
0
 public static function log(Exception $e)
 {
     //错误日志记录
     if (\Phalcon\DI::getDefault()->getShared('config')->log->file) {
         $logger = new \Phalcon\Logger\Adapter\File(APP_PATH . '/common/logs/' . date('Ymd') . '.log', array('mode' => 'a+'));
         $logger->error(get_class($e) . '[' . $e->getCode() . ']: ' . $e->getMessage());
         $logger->info($e->getFile() . '[' . $e->getLine() . ']');
         $logger->debug("Trace: \n" . $e->getTraceAsString() . "\n");
         $logger->close();
     }
     if (\Phalcon\DI::getDefault()->getShared('config')->log->debug) {
         \App\Controllers\ControllerCommon::instance()->exception($e);
     } else {
         \App\Controllers\ControllerCommon::instance()->exception('系统发生了错误,请联系管理员进行修复,错误代码:' . $e->getCode());
     }
 }