Exemplo n.º 1
0
 public function testWrite()
 {
     $this->log->err('123');
     $this->log->info('123');
     $count = $this->rediska->getListLength('log');
     $this->assertEquals(2, $count);
 }
Exemplo n.º 2
0
 /**
  * Obsługa rozpoczęcia kwerendy .
  * 
  * @param type $queryText
  * @param type $queryType
  * @return type 
  */
 public function queryStart($queryText, $queryType = null)
 {
     $queryId = parent::queryStart($queryText);
     if ($this->getEnabled()) {
         $message = "SQL({$queryId}): " . $queryText;
         // log the message as INFO message
         $this->_log->info($message);
     }
     return $queryId;
 }
Exemplo n.º 3
0
 /**
  *
  * @throws Opus_SolrSearch_Exception If connection to Solr server could not be established.
  */
 public function __construct()
 {
     $this->log = Zend_Registry::get('Zend_Log');
     $this->config = Zend_Registry::get('Zend_Config');
     $this->solr_server = $this->getSolrServer();
     if (false === $this->solr_server->ping()) {
         $this->log->err('Connection to Solr server ' . $this->solr_server_url . ' could not be established.');
         throw new Opus_SolrSearch_Exception('Solr server ' . $this->solr_server_url . ' is not responding.', Opus_SolrSearch_Exception::SERVER_UNREACHABLE);
     }
     $this->log->info('Connection to Solr server ' . $this->solr_server_url . ' was successfully established.');
 }
Exemplo n.º 4
0
 public static function addItem($message, $error = false)
 {
     global $s1b;
     if (self::getConfig()->getTracesEnabled() || self::getConfig()->getLogsEnabled()) {
         if (!strlen(trim($message))) {
             throw new \Exception('Cannot insert empty trace.');
         }
         // Ecriture du message dans le tableau des items en sessions si traces activées
         if (self::getConfig()->getTracesEnabled()) {
             self::initItems();
             self::$items[] = $message;
         }
         // Ecriture du log si activé
         if (self::getConfig()->getLogsEnabled()) {
             // vérification de l'existence du fichier et création si non existant
             $now = new \DateTime();
             $logFilePath = self::getContext()->getBaseDirectory() . sprintf("/var/log/%s-log.txt", $now->format("Ymd"));
             if (!file_exists($logFilePath)) {
                 $file = fopen($logFilePath, "w");
                 fclose($file);
             }
             // ecriture du log dans le fichier
             $writer = new \Zend_Log_Writer_Stream($logFilePath);
             $logger = new \Zend_Log($writer);
             if ($error) {
                 $logger->err($message);
             } else {
                 $logger->info($message);
             }
             $logger = null;
         }
     }
 }
Exemplo n.º 5
0
 /**
  * Intercept the query end and log the profiling data.
  *
  * @param  integer $queryId
  * @throws Zend_Db_Profiler_Exception
  * @return void
  */
 public function queryEnd($queryId)
 {
     $state = parent::queryEnd($queryId);
     if (!$this->getEnabled() || $state == self::IGNORED) {
         return;
     }
     // get profile of the current query
     $profile = $this->getQueryProfile($queryId);
     // update totalElapsedTime counter
     $this->_totalElapsedTime += $profile->getElapsedSecs();
     // create the message to be logged
     $message = "\nElapsed Secs: " . round($profile->getElapsedSecs(), 5) . "\n";
     $message .= "Query: " . $profile->getQuery() . "\n";
     // log the message as INFO message
     $this->_log->info($message);
 }
Exemplo n.º 6
0
 /**
  * Load a document from database and optional file(s) and index them,
  * or remove document from index (depending on job)
  *
  * @param Opus_Job $job Job description and attached data.
  * @return void
  */
 public function work(Opus_Job $job)
 {
     // make sure we have the right job
     if ($job->getLabel() != $this->getActivationLabel()) {
         throw new Opus_Job_Worker_InvalidJobException($job->getLabel() . " is not a suitable job for this worker.");
     }
     $this->_job = $job;
     $data = $job->getData();
     if (!(is_object($data) && isset($data->documentId) && isset($data->task))) {
         throw new Opus_Job_Worker_InvalidJobException("Incomplete or missing data.");
     }
     if (null !== $this->_logger) {
         $this->_logger->info('Indexing document with ID: ' . $data->documentId . '.');
     }
     // create index document or remove index, depending on task
     if ($data->task === 'index') {
         $document = new Opus_Document($data->documentId);
         $this->getIndex()->addDocumentToEntryIndex($document)->commit();
     } else {
         if ($data->task === 'remove') {
             $this->getIndex()->removeDocumentFromEntryIndexById($data->documentId)->commit();
         } else {
             throw new Opus_Job_Worker_InvalidJobException("unknown task '{$data->task}'.");
         }
     }
 }
Exemplo n.º 7
0
 /**
  * Execute a job and remove it from the jobs table on success.
  *
  * @param Opus_Job $job Job description model.
  * @return boolean Returns true if a job is consumend false if not
  */
 protected function consume(Opus_Job $job)
 {
     $label = $job->getLabel();
     if ($job->getState() !== null) {
         return false;
     }
     if (array_key_exists($label, $this->_workers)) {
         $worker = $this->_workers[$label];
         if (null !== $this->_logger) {
             $this->_logger->info('Processing ' . $label);
         }
         $job->setState(Opus_Job::STATE_PROCESSING);
         $job->store();
         try {
             $worker->setLogger($this->_logger);
             $worker->work($job);
             $job->delete();
             sleep($this->_delay);
         } catch (Exception $ex) {
             if (null !== $this->_logger) {
                 $msg = get_class($worker) . ': ' . $ex->getMessage();
                 $this->_logger->err($msg);
             }
             $job->setErrors(json_encode(array('exception' => get_class($ex), 'message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString())));
             $job->setState(Opus_Job::STATE_FAILED);
             $job->store();
             return false;
         }
         return true;
     }
     return false;
 }
Exemplo n.º 8
0
 public function init()
 {
     $writer = new Zend_Log_Writer_Firebug();
     $logger = new Zend_Log($writer);
     $logger->addPriority('LOGD', 8);
     $writer->setPriorityStyle(8, 'LOG');
     $logger->addPriority('ERROR', 9);
     $writer->setPriorityStyle(9, 'ERROR');
     $logger->addPriority('TRACE', 10);
     $writer->setPriorityStyle(10, 'TRACE');
     $logger->addPriority('EXCEPTION', 11);
     $writer->setPriorityStyle(11, 'EXCEPTION');
     $logger->addPriority('TABLE', 12);
     $writer->setPriorityStyle(12, 'TABLE');
     $logger->logd($_SERVER);
     $logger->info($_SERVER);
     $logger->warn($_SERVER);
     $logger->error($_SERVER);
     $logger->trace($_SERVER);
     try {
         throw new Exception('Test Exception');
     } catch (Exception $e) {
         $logger->exception($e);
     }
     $logger->table(array('2 SQL queries took 0.06 seconds', array(array('SQL Statement', 'Time', 'Result'), array('SELECT * FROM Foo', '0.02', array('row1', 'row2')), array('SELECT * FROM Bar', '0.04', array('row1', 'row2')))));
 }
Exemplo n.º 9
0
 protected function _error($message)
 {
     $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../data/log/cron_ERROR_' . $this->_name . '.log');
     $logger = new Zend_Log($writer);
     echo $message;
     $logger->info($message . "\n");
     return;
 }
Exemplo n.º 10
0
 /**
  * Send message to queue
  *
  * @param Oggetto_Messenger_Model_Message_Interface $message Message
  * @param string                                    $queue   Queue
  *
  * @return void
  */
 private function _sendMessage(Oggetto_Messenger_Model_Message_Interface $message, $queue)
 {
     $rabbitMessage = new AMQPMessage($message->toString(), array('delivery_mode' => 2));
     $this->_logger->info("Sending message to queue '{$queue}': {$rabbitMessage->body}");
     $transport = new Varien_Object();
     Mage::dispatchEvent('rabbitmq_publish_before', ['message' => $rabbitMessage, 'transport' => $transport]);
     $this->_getChannel()->basic_publish($rabbitMessage, '', $queue);
     Mage::dispatchEvent('rabbitmq_publish_after', ['message' => $rabbitMessage, 'transport' => $transport]);
 }
Exemplo n.º 11
0
 /**
  * Init the db metadata and paginator caches
  */
 protected function X_initDbCaches()
 {
     $this->_logger->info('Bootstrap ' . __METHOD__);
     if ('production' == $this->getEnvironment()) {
         // Metadata cache for Zend_Db_Table
         $frontendOptions = array('automatic_serialization' => true);
         $cache = Zend_Cache::factory('Core', 'Apc', $frontendOptions);
         Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
     }
 }
Exemplo n.º 12
0
 /**
  * lees de opties uit application.ini en maak een log-object aan dat in de
  * registry wordt gezet. Deze is vanuit de hele code te gebruiken voor debug-logging
  * @return Zend_Log
  */
 public function getLogger()
 {
     if (null === $this->_logger) {
         $options = $this->getOptions();
         if (!isset($options['debuglog'])) {
             throw new Exception("Debug log path undefined in application.ini");
         }
         try {
             $writer = new Zend_Log_Writer_Stream($options['debuglog']);
             $this->_logger = new Zend_Log($writer);
         } catch (Exception $e) {
             $this->_logger = null;
         }
         if (isset($options['firebug']) && "1" == $options['firebug']) {
             try {
                 $writer = new Zend_Log_Writer_Firebug();
                 if (null !== $this->_logger) {
                     $this->_logger->addWriter($writer);
                 } else {
                     $this->_logger = new Zend_Log($writer);
                 }
             } catch (Exception $e) {
                 $this->_logger = null;
             }
         }
         // voeg eventueel een uitvoer filter toe
         if (null !== $this->_logger && isset($options['loglevel'])) {
             try {
                 $loglevel = intVal($options['loglevel']);
                 $filter = new Zend_Log_Filter_Priority($loglevel);
                 $this->_logger->addFilter($filter);
             } catch (Exception $e) {
             }
         }
     }
     // voeg toe aan de registry zodat we deze later eenvoudig kunnen gebruiken
     if (null !== $this->_logger) {
         $this->_logger->info('==========================================================');
         Zend_Registry::set('logger', $this->_logger);
     }
     return $this->_logger;
 }
Exemplo n.º 13
0
 /**
  * Deletes all index documents that match the given query $query.  The
  * changes are not visible and a subsequent call to commit is required, to
  * make the changes visible.
  *
  * @param query
  * @throws Opus_SolrSearch_Index_Exception If delete by query $query failed.
  * @return void
  */
 public function deleteDocsByQuery($query)
 {
     try {
         $this->getSolrServer('index')->deleteByQuery($query);
         $this->log->info('deleted all docs that match ' . $query);
     } catch (Apache_Solr_Exception $e) {
         $msg = 'Error while deleting all documents that match query ' . $query;
         $this->log->err("{$msg} : " . $e->getMessage());
         throw new Opus_SolrSearch_Index_Exception($msg, 0, $e);
     }
 }
 public function saveCdrDedicatorias($resultado)
 {
     $name = date('YmdH');
     $datos = $this->registerCdr();
     $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../logs/cdr/' . $name . ".dedicatoria");
     $formatter = new Zend_Log_Formatter_Simple('%message%' . PHP_EOL);
     $writer->setFormatter($formatter);
     $log = new Zend_Log($writer);
     $mensaje = $datos['fecha'] . "," . $datos['hora'] . "," . $_SERVER['REMOTE_ADDR'] . "," . $datos['telefono'] . "," . 'perfil:' . $datos['perfil'] . "," . $resultado;
     $log->info($mensaje);
 }
Exemplo n.º 15
0
 private function saveCdrBanners($datos, $id, $name)
 {
     $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../logs/cdr/' . $name . ".banners");
     // $writer = new Zend_Log_Writer_Stream('/var/log/portalwap/'.$name.".banners");
     $formatter = new Zend_Log_Formatter_Simple('%message%' . PHP_EOL);
     $writer->setFormatter($formatter);
     $log = new Zend_Log($writer);
     $banners = 'banner1.' . $datos['url'][0] . "," . 'banner2.' . $datos['url'][1] . "," . 'banner3.' . $datos['url'][2] . "," . 'banner4.' . $datos['url'][3] . "," . 'banner5.' . $datos['url'][4];
     $mensaje = $datos['fecha'] . "," . $datos['hora'] . "," . $_SERVER['REMOTE_ADDR'] . "," . $datos['telefono'] . ",perfil:" . $datos['perfil'] . "," . $banners;
     $log->info($mensaje);
 }
Exemplo n.º 16
0
 public function saveCdrLog($url, $message, $portal)
 {
     $datos = $this->obtenerPerfilNumero();
     $name = date('YmdH');
     $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../data/cdr/' . $portal . '/' . $name . ".log");
     $formatter = new Zend_Log_Formatter_Simple('%message%' . PHP_EOL);
     $writer->setFormatter($formatter);
     $log = new Zend_Log($writer);
     $mensaje = $datos['fecha'] . "," . $datos['hora'] . "," . 'PERFIL:' . $datos['perfil'] . "," . $url . "," . $message . "," . $datos['telefono'];
     $log->info($mensaje);
 }
Exemplo n.º 17
0
 /**
  * syncs the ids in a sql dump file
  * 
  * @param array $mapping
  */
 protected function _syncIdsInDump($mapping)
 {
     // use mapping for str_replace
     if (!file_exists($this->_config->inputfile)) {
         die('file does not exist');
     }
     $this->_logger->info(__METHOD__ . '::' . __LINE__ . ' Reading input file: ' . $this->_config->inputfile);
     $input = file_get_contents($this->_config->inputfile);
     $this->_logger->info(__METHOD__ . '::' . __LINE__ . ' Replacing ids ...');
     $output = str_replace(array_keys($mapping), array_values($mapping), $input);
     $filename = $this->_config->outputfile ? $this->_config->outputfile : 'synced.sql';
     $this->_logger->info(__METHOD__ . '::' . __LINE__ . ' Writing to file: ' . $filename);
     file_put_contents($filename, $output);
 }
Exemplo n.º 18
0
 /**
  * @desc create Massmailer object and send mails
  */
 public function __construct()
 {
     $mail = new Enterprise_Massmailer('youtube');
     $result = self::_getUsers();
     if (is_array($result)) {
         $mail->sendAll($result);
     } else {
         # error log
         $result = date('Y-m-d H:i:s') . ';' . $result;
         $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../datas/logs/errorlog.csv');
         $logger = new Zend_Log($writer);
         $logger->info($result);
     }
 }
Exemplo n.º 19
0
 /**
  * @desc create Massmailer object and send mails
  */
 public function __construct($interval, $type)
 {
     $scriptName = 'semaine-' . Zend_Registry::get('week') . $type;
     $mail = new Enterprise_Massmailer($scriptName);
     $result = self::_getUsers($interval, $type);
     if (is_array($result)) {
         $mail->sendAll($result);
     } else {
         # error log
         $result = date('Y-m-d H:i:s') . ';' . $result;
         $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../datas/logs/errorlog.csv');
         $logger = new Zend_Log($writer);
         $logger->info($result);
     }
 }
Exemplo n.º 20
0
 private function _zendlog()
 {
     $write = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/log/log.txt');
     $format = new Zend_Log_Formatter_Simple('%message%');
     $write->setFormatter($format);
     $log = new Zend_Log($write);
     $log->info('thong bao', Zend_Log::INFO);
     $log->err('thong bao loi', Zend_Log::ERR);
     //        $write= new Zend_Log_Writer_Stream(APPLICATION_PATH.'/log/log.txt');
     //
     //        $log->info('thong bao', Zend_Log::INFO);
     //        $log->err('thong bao loi', Zend_Log::ERR);
     //
     //
     //
     //         $log = new Zend_Log($write);
 }
Exemplo n.º 21
0
 public function changeOrderStatus(Varien_Event_Observer $observer)
 {
     $orderlog = Mage::getBaseDir() . '/var/order/verified.log';
     $writer = new Zend_Log_Writer_Stream($orderlog);
     $logger = new Zend_Log($writer);
     $resource = Mage::getSingleton('core/resource');
     $readConnection = $resource->getConnection('core_read');
     $query = "SELECT customer_id FROM `sales_flat_order` WHERE status = 'complete' GROUP BY `customer_id` HAVING count( `customer_id` ) >=2";
     $result = $readConnection->fetchAll($query);
     foreach ($result as $result1) {
         $resultdata = $result1["customer_id"];
         $customers = Mage::getModel('customer/customer')->load($resultdata);
         $verify = $customers->getIsVerified();
         if ($verify != 335) {
             $customers->setData('is_verified', '335');
             $customers->save();
             $logger->info($resultdata . " - Customer is verified");
         }
     }
 }
Exemplo n.º 22
0
 /**
  * @desc prepare emailing for each user
  * @param object $users
  * @return void
  */
 public function sendAll($users)
 {
     $startCounter = count($users);
     $endCounter = 0;
     foreach ($users as $user) {
         $datas = $user;
         $this->_render($datas);
         ++$endCounter;
     }
     if ($startCounter == $endCounter) {
         $result = date('Y-m-d H:i:s') . ';all mails sent';
         $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../datas/logs/eventlog.csv');
         $logger = new Zend_Log($writer);
         $logger->info($result);
     } else {
         $result = date('Y-m-d H:i:s') . ';' . $endCounter . 'mails sent / ' . $startCounter;
         $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../datas/logs/errorlog.csv');
         $logger = new Zend_Log($writer);
         $logger->info($result);
     }
 }
    exit(255);
}
exec('php --version', $output, $status);
if ($status !== 0) {
    echo "ERROR: PHP interpreter isn't in your include path. Add it there before running the tool." . PHP_EOL;
    exit(255);
}
if (isset($argv[1]) && intval($argv[1]) > 0) {
    $threadCount = intval($argv[1]);
} else {
    $threadCount = 1;
}
$writer = new Zend_Log_Writer_Stream('php://output');
$writer->setFormatter(new Zend_Log_Formatter_Simple('[%priorityName%]: %message%' . PHP_EOL));
$logger = new Zend_Log($writer);
$logger->info('Initialization...');
error_reporting(-1);
ini_set('display_errors', 1);
ini_set('memory_limit', -1);
$response = new Mage_Core_Controller_Response_Http();
Mage::app()->setResponse($response);
$migration = new Mage_Migration();
$processedCategories = array();
$processedProducts = array();
Mage::getModel('enterprise_mview/client')->init('enterprise_url_rewrite_category')->execute('enterprise_catalog/index_action_url_rewrite_category_refresh');
Mage::getModel('enterprise_mview/client')->init('enterprise_url_rewrite_product')->execute('enterprise_catalog/index_action_url_rewrite_product_refresh');
Mage::getModel('enterprise_mview/client')->init('enterprise_url_rewrite_redirect')->execute('enterprise_urlrewrite/index_action_url_rewrite_redirect_refresh');
$tableProducts = $migration->getConnection()->newTable($migration->getEntityMigrationTable(Mage_Migration::ENTITY_TYPE_PRODUCT))->addColumn('id', Varien_Db_Ddl_Table::TYPE_CHAR, 512);
$tableCategories = $migration->getConnection()->newTable($migration->getEntityMigrationTable(Mage_Migration::ENTITY_TYPE_CATEGORY))->addColumn('id', Varien_Db_Ddl_Table::TYPE_CHAR, 512);
if ($migration->getConnection()->isTableExists($tableProducts->getName())) {
    $migration->getConnection()->dropTable($tableProducts->getName());
Exemplo n.º 24
0
require_once 'Zend/Registry.php';
require_once 'Zend/Http/Client.php';
require_once 'Zend/Log/Writer/Stream.php';
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
require_once 'application/models/Feeds.php';
require_once 'Zend/Db/Table/Abstract.php';
require_once 'Rss.php';
// Define some constants
define('APP_ROOT', realpath(dirname(dirname(__FILE__))));
define('CACHE_FOLDER', '../cache');
// Set up log
$filename = APP_ROOT . DIRECTORY_SEPARATOR . 'lucene' . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . 'crawler.log';
$writer = new Zend_Log_Writer_Stream($filename);
$log = new Zend_Log($writer);
$log->info('Crawler starting up');
// Open index
$indexpath = APP_ROOT . DIRECTORY_SEPARATOR . 'lucene' . DIRECTORY_SEPARATOR . 'index';
try {
    $index = Zend_Search_Lucene::create($indexpath);
    $log->info("Created new index in {$indexpath}");
    // If both fail, give up and show error message
} catch (Zend_Search_Lucene_Exception $e) {
    $log->info("Failed opening or creating index in {$indexpath}");
    $log->info($e->getMessage());
    echo "Unable to open or create index: {$e->getMessage()}";
    exit(1);
}
$log->info('Crawler loads db');
// load DB configuration
$config = new Zend_Config_Ini('../config/zportal.ini', 'database');
Exemplo n.º 25
0
    protected function processAction()
    {
        $writer = new Zend_Log_Writer_Stream('php://stdout');
        $logger = new Zend_Log($writer);
        $settings = Settings::getInstance();
        try {
            $view = $this->application->getBootstrap()->getResource('view');
            $view->setScriptPath(APPLICATION_PATH . '/views/scripts');
            $adapter = Zend_Db_Table::getDefaultAdapter();
            $stmt = $adapter->query(<<<SQL
        SELECT id,
            (CASE WHEN awaits_from is null THEN created_at
           ELSE awaits_from END)  "awaits_from",
               customer_considering, closing_time FROM negotiations.negotiation_step WHERE closing_time is null AND created_at > '2013-08-01'::date
SQL
);
            //
            $toProcess = $stmt->fetchAll();
            $logger->info('Found ' . count($toProcess) . ' ongoing negotiations.');
            $errs = 0;
            $to_exp = 0;
            $now = date('Y-m-d', time());
            $model = new NegotiationStep();
            $adapter->query(<<<SQL
              ALTER TABLE negotiations.negotiation_step DISABLE TRIGGER negotiation_step_last_update_refresh
SQL
);
            foreach ($toProcess as $nid) {
                if ($nid['customer_considering'] == 'true' || $nid['customer_considering'] == 'TRUE' || $nid['customer_considering'] == 't') {
                    switch ('working') {
                        case 'working':
                            $date = @Logic_DateUtils::getDateByWorkingDays(5, $nid['awaits_from']) . ' 23:59:59';
                            break;
                        case 'calendar':
                            $date = date('Y-m-d', strtotime($nid['awaits_from'] . ' +' . 5 . ' days')) . ' 23:59:59';
                            break;
                        default:
                            throw new Exception('Misconfiguration in negotiations.settings table');
                    }
                } else {
                    switch ('working') {
                        case 'working':
                            $date = @Logic_DateUtils::getDateByWorkingDays(5, $nid['awaits_from']) . ' 23:59:59';
                            break;
                        case 'calendar':
                            $date = date('Y-m-d', strtotime($nid['awaits_from'] . ' +' . 5 . ' days')) . ' 23:59:59';
                            break;
                        default:
                            throw new Exception('Misconfiguration in negotiations.settings table');
                    }
                }
                $to_exp++;
                try {
                    $model->update(array('closing_time' => $date), 'id = \'' . $nid['id'] . '\'');
                } catch (Exception $e) {
                    $errs++;
                }
                echo $to_exp . "\t" . $errs . "\n";
            }
            $adapter->query(<<<SQL
              ALTER TABLE negotiations.negotiation_step ENABLE TRIGGER negotiation_step_last_update_refresh
SQL
);
            if ($errs == 0) {
                $logger->info('Successfuly expired all qualifying negotiations (' . $to_exp . ')');
            } else {
                $logger->warn('Negotiations qualifying for expiration processed with errors. ' . $errs . '/' . count($to_exp) . ' failed. Check previous log messages for details.');
            }
        } catch (Exception $e) {
            $logger->crit($e->getMessage());
        }
        $logger->info('Script executed succesfully');
        exit(0);
    }
Exemplo n.º 26
0
 /**
  * @group ZF-8491
  */
 public function testLogAcceptsExtrasParameterAsScalarAndAddsAsInfoKeyToEvent()
 {
     $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock());
     $logger->info('foo', 'nonesuch');
     $event = array_shift($mock->events);
     $this->assertContains('info', array_keys($event));
     $info = $event['info'];
     $this->assertContains('nonesuch', $info);
 }
Exemplo n.º 27
0
 protected function saveLogBD($errors)
 {
     $config = new Zend_Config_Ini('application/configs/application.ini', APPLICATION_ENV);
     $params = array('host' => $config->resources->db->params->host, 'username' => $config->resources->db->params->username, 'password' => $config->resources->db->params->password, 'dbname' => "estatisticas", 'charset' => $config->resources->db->params->charset);
     $db = Zend_Db::factory('PDO_MYSQL', $params);
     $columnMapping = array('message' => 'message', 'file' => 'file', 'line' => 'line', 'url' => 'url', 'date' => 'date');
     $writer = new Zend_Log_Writer_Db($db, 'erro_log', $columnMapping);
     $logger = new Zend_Log($writer);
     $exception = $errors->exception;
     $exception->getTraceAsString();
     $logger->setEventItem('message', $exception->getMessage());
     $logger->setEventItem('file', $errors->getFile());
     $logger->setEventItem('line', $errors->getLine());
     $logger->setEventItem('url', $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
     $logger->setEventItem('date', new Zend_Db_Expr('NOW()'));
     $logger->info("Erros");
 }
Exemplo n.º 28
0
 public function paypalsave($status, $dataPaypal = array())
 {
     $tblOrder = new Pandamp_Modules_Payment_Order_Model_Order();
     $orderId = $dataPaypal['custom'];
     //$_SESSION['_orderIdNumber'];//$this->_orderIdNumber;//$data['custom'];
     //echo $orderId;
     //var_dump($dataPaypal);
     //print_r($data['custom']);
     $dataPrice = $tblOrder->fetchAll($tblOrder->select()->where('orderId = ' . $orderId));
     if ($dataPrice[0]->orderTotal == $dataPaypal['mc_gross']) {
         $payStatus = 3;
         //paid - completed
     } else {
         $payStatus = 7;
         //payment error
     }
     $tblPaypal = new Pandamp_Modules_Payment_Paypal_Model_Paypal();
     $data = $tblPaypal->fetchNew();
     $data->orderId = $orderId;
     $data->mcGross = $dataPaypal['mc_gross'];
     $data->addressStatus = $dataPaypal['address_status'];
     $data->payerId = $dataPaypal['payer_id'];
     $data->addressStreet = $dataPaypal['address_street'];
     $data->paymentDate = $dt = date('Y-m-d H:i:s', strtotime($dataPaypal['payment_date']));
     $data->paymentStatus = $status;
     $data->addressZip = $dataPaypal['address_zip'];
     $data->firstName = $dataPaypal['first_name'];
     $data->mcFee = $dataPaypal['mc_fee'];
     $data->addressName = $dataPaypal['address_name'];
     $data->notifyVersion = $dataPaypal['notify_version'];
     $data->payerStatus = $dataPaypal['payer_status'];
     $data->addressCountry = $dataPaypal['address_country'];
     $data->addresCity = $dataPaypal['address_city'];
     $data->payerEmail = $dataPaypal['payer_email'];
     $data->verifySign = $dataPaypal['verify_sign'];
     $data->paymentType = $dataPaypal['payment_type'];
     $data->txnId = $dataPaypal['txn_id'];
     $data->lastName = $dataPaypal['last_name'];
     $data->receiverEmail = $dataPaypal['receiver_email'];
     $data->addressState = $dataPaypal['address_state'];
     $data->receiverId = $dataPaypal['receiver_id'];
     $data->txnType = $dataPaypal['txn_type'];
     $data->mcCurrency = $dataPaypal['mc_currency'];
     $data->paymentGross = $dataPaypal['payment_gross'];
     $data->paymentFee = $dataPaypal['payment_fee'];
     $data->numCartItems = isset($dataPaypal['num_cart_items']) ? $dataPaypal['num_cart_items'] : '1';
     $data->business = $dataPaypal['business'];
     $data->parentTxnId = $dataPaypal['txn_id'];
     $data->lastModified = date('Y-m-d');
     $data->dateAdded = date('Y-m-d');
     try {
         $paypalIpnId = $data->save();
     } catch (Exception $e) {
         $writer = new Zend_Log_Writer_Stream(ROOT_PATH . '/app_log.txt');
         $logger = new Zend_Log($writer);
         $logger->info($e->getMessage());
     }
     //echo($tblPaypal->getLastInsertId());
     $paypalHistory = new Pandamp_Modules_Payment_Paypal_Model_Paypal();
     $row = $paypalHistory->fetchNew();
     $row->paypalIpnId = $paypalIpnId;
     $row->orderId = $orderId;
     $row->txnId = $this->_request->getParam('txn_id');
     $row->parentTxnId = $this->_request->getParam('txn_id');
     $row->paymentStatus = $this->_request->getParam('payment_status');
     $row->dateAdded = date('Y-m-d');
     $row->save();
     $this->updateInvoiceMethod($orderId, 'paypal', $payStatus, 0, 'paid with paypal method');
 }
Exemplo n.º 29
0
 public function getRowsToProcess($filesToProcess)
 {
     # Get some more detailed error information from libxml
     libxml_use_internal_errors(true);
     $log = null;
     try {
         # Logger for this processor
         $writer = new Zend_Log_Writer_Stream(Mage::getBaseDir('log') . DS . 'order_status_import_processor_xml.log');
         $log = new Zend_Log($writer);
     } catch (Exception $e) {
         # Do nothing.. :|
     }
     # Updates to process, later the result
     $updatesInFilesToProcess = array();
     # Get mapping model
     $this->mappingModel = Mage::getModel('orderstatusimport/processor_mapping_fields');
     $this->mappingModel->setDataPath('orderstatusimport/processor_xml/import_mapping');
     # Load mapping
     $this->mapping = $this->mappingModel->getMappingConfig();
     # Load configuration:
     $config = array('IMPORT_DATA_XPATH' => Mage::getStoreConfig('orderstatusimport/processor_xml/xpath_data'), 'IMPORT_SHIPPED_ONE_FIELD' => Mage::getStoreConfigFlag('orderstatusimport/processor_xml/shipped_one_field'), 'IMPORT_NESTED_ITEMS' => Mage::getStoreConfigFlag('orderstatusimport/processor_xml/node_nested_items'), 'IMPORT_NESTED_ITEM_XPATH' => Mage::getStoreConfig('orderstatusimport/processor_xml/node_nested_path'), 'IMPORT_NESTED_TRACKINGS' => Mage::getStoreConfigFlag('orderstatusimport/processor_xml/node_nested_trackings'), 'IMPORT_NESTED_TRACKING_XPATH' => Mage::getStoreConfig('orderstatusimport/processor_xml/node_nested_tracking_path'));
     if ($this->mapping->getOrderNumber() == null) {
         Mage::throwException('Please configure the XML processor in the configuration section of the Tracking Number Import Module. The order number field may not be empty and must be mapped.');
     }
     if ($config['IMPORT_DATA_XPATH'] == '') {
         Mage::throwException('Please configure the XML Processor in the configuration section of the Tracking Number Import Module. The Data XPath field may not be empty.');
     }
     foreach ($filesToProcess as $importFile) {
         $data = $importFile['data'];
         $filename = $importFile['filename'];
         $type = $importFile['type'];
         unset($importFile['data']);
         // Remove UTF8 BOM
         $bom = pack('H*', 'EFBBBF');
         $data = preg_replace("/^{$bom}/", '', $data);
         $updatesToProcess = array();
         // Prepare data - replace namespace
         $data = str_replace('xmlns=', 'ns=', $data);
         // http://www.php.net/manual/en/simplexmlelement.xpath.php#96153
         $data = str_replace('xmlns:', 'ns:', $data);
         // http://www.php.net/manual/en/simplexmlelement.xpath.php#96153
         try {
             $xmlDOM = new DOMDocument();
             $xmlDOM->loadXML($data);
         } catch (Exception $e) {
             $errors = "Could not load XML File '" . $filename . "' from '" . $type . "':\n" . $e->getMessage();
             foreach (libxml_get_errors() as $error) {
                 $errors .= "\t" . $error->message;
             }
             if ($log instanceof Zend_Log) {
                 $log->info($errors);
             }
             continue;
             # Process next file..
         }
         if (!$xmlDOM) {
             $errors = "Could not load XML File '" . $filename . "' from '" . $type . "':\n" . $e->getMessage();
             foreach (libxml_get_errors() as $error) {
                 $errors .= "\t" . $error->message;
             }
             if ($log instanceof Zend_Log) {
                 $log->info($errors);
             }
             continue;
             # Process next file..
         }
         $domXPath = new DOMXPath($xmlDOM);
         $updates = $domXPath->query($config['IMPORT_DATA_XPATH']);
         foreach ($updates as $update) {
             // Init "sub dom"
             $updateDOM = new DomDocument();
             $updateDOM->appendChild($updateDOM->importNode($update, true));
             $updateXPath = new DOMXPath($updateDOM);
             $this->update = $updateXPath;
             $orderNumber = $this->getFieldData('order_number');
             if (empty($orderNumber)) {
                 continue;
             }
             $carrierCode = $this->getFieldData('carrier_code');
             $carrierName = $this->getFieldData('carrier_name');
             $trackingNumber = $this->getFieldData('tracking_number');
             $status = $this->getFieldData('order_status');
             $orderComment = $this->getFieldData('order_status_history_comment');
             $skuToShip = strtolower($this->getFieldData('sku'));
             $qtyToShip = $this->getFieldData('qty');
             $customData1 = $this->getFieldData('custom1');
             $customData2 = $this->getFieldData('custom2');
             if (!isset($updatesToProcess[$orderNumber])) {
                 $updatesToProcess[$orderNumber] = array("STATUS" => $status, "ORDER_COMMENT" => $orderComment, "CUSTOM_DATA1" => $customData1, "CUSTOM_DATA2" => $customData2);
                 $updatesToProcess[$orderNumber]['tracks'] = array();
                 if ($config['IMPORT_NESTED_TRACKINGS']) {
                     // Tracking data is nested..
                     $tracks = $updateXPath->query($config['IMPORT_NESTED_TRACKING_XPATH']);
                     foreach ($tracks as $track) {
                         $this->track = $track;
                         $carrierCode = $this->getFieldData('carrier_code', 'track');
                         $carrierName = $this->getFieldData('carrier_name', 'track');
                         $trackingNumber = $this->getFieldData('tracking_number', 'track');
                         if ($trackingNumber !== '') {
                             $trackingNumber = str_replace(array("/", ",", "|"), ";", $trackingNumber);
                             $trackingNumbers = explode(";", $trackingNumber);
                             // Multiple tracking numbers in one field
                             foreach ($trackingNumbers as $trackingNumber) {
                                 $updatesToProcess[$orderNumber]['tracks'][$trackingNumber] = array("TRACKINGNUMBER" => $trackingNumber, "CARRIER_CODE" => $carrierCode, "CARRIER_NAME" => $carrierName);
                             }
                         }
                     }
                 } else {
                     if ($trackingNumber !== '') {
                         $trackingNumber = str_replace(array("/", ",", "|"), ";", $trackingNumber);
                         $trackingNumbers = explode(";", $trackingNumber);
                         // Multiple tracking numbers in one field
                         foreach ($trackingNumbers as $trackingNumber) {
                             $updatesToProcess[$orderNumber]['tracks'][$trackingNumber] = array("TRACKINGNUMBER" => $trackingNumber, "CARRIER_CODE" => $carrierCode, "CARRIER_NAME" => $carrierName);
                         }
                     }
                 }
                 $updatesToProcess[$orderNumber]['items'] = array();
                 $itemsToAdd = array();
                 if ($config['IMPORT_NESTED_ITEMS']) {
                     // Item data is nested..
                     $items = $updateXPath->query($config['IMPORT_NESTED_ITEM_XPATH']);
                     foreach ($items as $item) {
                         $this->item = $item;
                         $skuToShip = strtolower($this->getFieldData('sku', 'item'));
                         $qtyToShip = $this->getFieldData('qty', 'item');
                         if ($skuToShip !== '') {
                             $itemsToAdd[$skuToShip] = $qtyToShip;
                         }
                     }
                 } else {
                     if ($skuToShip !== '') {
                         $itemsToAdd[$skuToShip] = $qtyToShip;
                     }
                 }
                 foreach ($itemsToAdd as $skuToShip => $qtyToShip) {
                     if ($config['IMPORT_SHIPPED_ONE_FIELD'] == true) {
                         // We're supposed to import the SKU and Qtys all from one field. Each combination separated by a ; and sku/qty separated by :
                         $skuAndQtys = explode(";", $skuToShip);
                         foreach ($skuAndQtys as $skuAndQty) {
                             list($sku, $qty) = explode(":", $skuAndQty);
                             $sku = strtolower($sku);
                             if ($sku !== '') {
                                 $updatesToProcess[$orderNumber]['items'][$sku] = array("SKU" => $sku, "QTY" => $qty);
                             }
                         }
                     } else {
                         // One row per SKU and QTY
                         if ($skuToShip !== '') {
                             if (isset($updatesToProcess[$orderNumber]['items'][$skuToShip])) {
                                 $updatesToProcess[$orderNumber]['items'][$skuToShip] = array("SKU" => $skuToShip, "QTY" => $updatesToProcess[$orderNumber]['items'][$skuToShip]['QTY'] + $qtyToShip);
                             } else {
                                 $updatesToProcess[$orderNumber]['items'][$skuToShip] = array("SKU" => $skuToShip, "QTY" => $qtyToShip);
                             }
                         }
                     }
                 }
             } else {
                 /*$orderNumber .= "|" . uniqid();
                   $updatesToProcess[$orderNumber] = array(
                       "STATUS" => "",
                       "ORDER_COMMENT" => "",
                       "CUSTOM_DATA1" => "",
                       "CUSTOM_DATA2" => "",
                   );*/
                 // Add multiple tracking numbers and items to ship to $updates
                 if ($config['IMPORT_NESTED_TRACKINGS']) {
                     // Tracking data is nested..
                     $tracks = $updateXPath->query($config['IMPORT_NESTED_TRACKING_XPATH']);
                     foreach ($tracks as $track) {
                         // Init "sub dom"
                         $trackDOM = new DomDocument();
                         $trackDOM->appendChild($trackDOM->importNode($track, true));
                         $trackXPath = new DOMXPath($trackDOM);
                         $this->track = $trackXPath;
                         $carrierCode = $this->getFieldData('carrier_code', 'track');
                         $carrierName = $this->getFieldData('carrier_name', 'track');
                         $trackingNumber = $this->getFieldData('tracking_number', 'track');
                         if ($trackingNumber !== '') {
                             $trackingNumber = str_replace(array("/", ",", "|"), ";", $trackingNumber);
                             $trackingNumbers = explode(";", $trackingNumber);
                             // Multiple tracking numbers in one field
                             foreach ($trackingNumbers as $trackingNumber) {
                                 $updatesToProcess[$orderNumber]['tracks'][$trackingNumber] = array("TRACKINGNUMBER" => $trackingNumber, "CARRIER_CODE" => $carrierCode, "CARRIER_NAME" => $carrierName);
                             }
                         }
                     }
                 } else {
                     if ($trackingNumber !== '') {
                         $trackingNumber = str_replace(array("/", ",", "|"), ";", $trackingNumber);
                         $trackingNumbers = explode(";", $trackingNumber);
                         // Multiple tracking numbers in one field
                         foreach ($trackingNumbers as $trackingNumber) {
                             $updatesToProcess[$orderNumber]['tracks'][$trackingNumber] = array("TRACKINGNUMBER" => $trackingNumber, "CARRIER_CODE" => $carrierCode, "CARRIER_NAME" => $carrierName);
                         }
                     }
                 }
                 $itemsToAdd = array();
                 if ($config['IMPORT_NESTED_ITEMS']) {
                     // Item data is nested..
                     $items = $updateXPath->query($config['IMPORT_NESTED_ITEM_XPATH']);
                     foreach ($items as $item) {
                         $this->item = $item;
                         $skuToShip = strtolower($this->getFieldData('sku', 'item'));
                         $qtyToShip = $this->getFieldData('qty', 'item');
                         if ($skuToShip !== '') {
                             if (isset($itemsToAdd[$skuToShip])) {
                                 $itemsToAdd[$skuToShip] = $itemsToAdd[$skuToShip] + $qtyToShip;
                             } else {
                                 $itemsToAdd[$skuToShip] = $qtyToShip;
                             }
                         }
                     }
                 } else {
                     if ($skuToShip !== '') {
                         if (isset($itemsToAdd[$skuToShip])) {
                             $itemsToAdd[$skuToShip] = $itemsToAdd[$skuToShip] + $qtyToShip;
                         } else {
                             $itemsToAdd[$skuToShip] = $qtyToShip;
                         }
                     }
                 }
                 foreach ($itemsToAdd as $skuToShip => $qtyToShip) {
                     if ($skuToShip !== '') {
                         if (isset($updatesToProcess[$orderNumber]['items'][$skuToShip])) {
                             $updatesToProcess[$orderNumber]['items'][$skuToShip] = array("SKU" => $skuToShip, "QTY" => $updatesToProcess[$orderNumber]['items'][$skuToShip]['QTY'] + $qtyToShip);
                         } else {
                             $updatesToProcess[$orderNumber]['items'][$skuToShip] = array("SKU" => $skuToShip, "QTY" => $qtyToShip);
                         }
                     }
                 }
             }
         }
         // File processed
         $updatesInFilesToProcess[] = array("FILE_INFORMATION" => $importFile, "HAS_SKU_INFO" => $this->mapping->getSku() !== null ? true : false, "ORDERS" => $updatesToProcess);
     }
     #ini_set('xdebug.var_display_max_depth', 10);
     #Zend_Debug::dump($updatesToProcess);
     #die();
     return $updatesInFilesToProcess;
 }
Exemplo n.º 30
0
 public function processRequest($url, $xml)
 {
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     $response = curl_exec($ch);
     curl_close($ch);
     if ($this->getDebug()) {
         $writer = new Zend_Log_Writer_Stream($this->getLogPath());
         $logger = new Zend_Log($writer);
         $logger->info("XML Sent: {$xml}");
         $logger->info("XML Received: {$response}");
     }
     return $response;
 }