Exemplo n.º 1
0
 /**
  * Constructor
  *
  * @param HTTP\Request $request
  * @param HTTP\Response $response
  * @param string $format one of png, jpeg, gif
  */
 public function __construct(HTTP\Request $request, HTTP\Response $response, $format = 'png')
 {
     parent::__construct($request, $response);
     // to enabled jpgraphs graphical exception handler
     restore_exception_handler();
     if ($this->request->getParameter('width')) {
         $this->width = $this->request->getParameter('width');
     }
     if ($this->request->getParameter('height')) {
         $this->height = $this->request->getParameter('height');
     }
     $this->colors = Util\Configuration::read('colors');
     $this->graph = new \Graph($this->width, $this->height);
     $this->graph->img->SetImgFormat($format);
     // Specify what scale we want to use,
     $this->graph->SetScale('datlin');
     $this->graph->legend->SetPos(0.03, 0.06);
     $this->graph->legend->SetShadow(FALSE);
     $this->graph->legend->SetFrameWeight(1);
     $this->graph->SetMarginColor('white');
     $this->graph->SetYDeltaDist(65);
     $this->graph->yaxis->SetTitlemargin(36);
     $this->graph->SetTickDensity(TICKD_DENSE, TICKD_SPARSE);
     $this->graph->xaxis->SetFont(FF_ARIAL);
     $this->graph->xaxis->SetLabelAngle(45);
     $this->graph->xaxis->SetLabelFormatCallback(function ($label) {
         return date('j.n.y G:i', $label);
     });
     $this->graph->img->SetAntiAliasing(function_exists('imageantialias'));
 }
Exemplo n.º 2
0
 /**
  * Add debugging information include queries and messages to output queue
  *
  * @param Util\Debug $debug
  */
 protected function addDebug(Util\Debug $debug)
 {
     echo '# level:' . CSV::DELIMITER . $debug->getLevel() . PHP_EOL;
     echo '# database:' . CSV::DELIMITER . Util\Configuration::read('db.driver') . PHP_EOL;
     echo '# time:' . CSV::DELIMITER . $debug->getExecutionTime() . PHP_EOL;
     if ($uptime = Util\Debug::getUptime()) {
         echo '# uptime:' . CSV::DELIMITER . $uptime * 1000;
     }
     if ($load = Util\Debug::getLoadAvg()) {
         echo '# load:' . CSV::DELIMITER . implode(', ', $load) . PHP_EOL;
     }
     if ($commit = Util\Debug::getCurrentCommit()) {
         echo '# commit-hash:' . CSV::DELIMITER . $commit;
     }
     if ($version = phpversion()) {
         echo '# php-version:' . CSV::DELIMITER . $version;
     }
     foreach ($debug->getMessages() as $message) {
         echo '# message:' . CSV::DELIMITER . $message['message'] . PHP_EOL;
         // TODO add more information
     }
     foreach ($debug->getQueries() as $query) {
         echo '# query:' . CSV::DELIMITER . $query['sql'] . PHP_EOL;
         if (isset($query['parameters'])) {
             echo "# \tparameters:" . CSV::DELIMITER . implode(', ', $query['parameters']) . PHP_EOL;
         }
     }
 }
 /**
  * Factory method
  *
  * @param  InterpreterInterpreter $interpreter
  * @param  ModelChannel           $channel
  * @param  DBALConnection         $conn
  * @return SQL\SQLOptimizer 	  instantiated class or false
  */
 public static function factory()
 {
     // optimizer defined in config file
     if (null !== ($class = Util\Configuration::read('db.optimizer'))) {
         return $class;
     }
     switch (Util\Configuration::read('db.driver')) {
         case 'pdo_mysql':
             if (Util\Configuration::read('aggregation')) {
                 $class = __NAMESPACE__ . '\\MySQLAggregateOptimizer';
             } else {
                 $class = __NAMESPACE__ . '\\MySQLOptimizer';
             }
             break;
         case 'pdo_sqlite':
             $class = __NAMESPACE__ . '\\SQLiteOptimizer';
             break;
         case 'pdo_pgsql':
             $class = __NAMESPACE__ . '\\PostgreSQLOptimizer';
             break;
         default:
             $class = __CLASS__;
     }
     return $class;
 }
 /**
  * @todo
  * @param string $capabilities
  * @param string $sub
  */
 public function get($section = NULL)
 {
     $capabilities = array();
     if (is_null($section) || $section == 'configuration') {
         $configuration = array('precision' => View\View::PRECISION, 'database' => Util\Configuration::read('db.driver'), 'debug' => Util\Configuration::read('debug'), 'devmode' => Util\Configuration::read('devmode'));
         $capabilities['configuration'] = $configuration;
     }
     if (is_null($section) || $section == 'formats') {
         $capabilities['formats'] = array_keys(\Volkszaehler\Router::$viewMapping);
     }
     if (is_null($section) || $section == 'contexts') {
         $capabilities['contexts'] = array_keys(\Volkszaehler\Router::$controllerMapping);
     }
     if (is_null($section) || $section == 'definitions') {
         if (!is_null($section)) {
             // only caching when we doesn't request dynamic informations
             $this->view->setCaching('expires', time() + 2 * 7 * 24 * 60 * 60);
             // cache for 2 weeks
         }
         $capabilities['definitions']['entities'] = Definition\EntityDefinition::get();
         $capabilities['definitions']['properties'] = Definition\PropertyDefinition::get();
     }
     if (count($capabilities) == 0) {
         throw new \Exception('Invalid capability identifier: \'' . $section . '\'');
     }
     return array('capabilities' => $capabilities);
 }
Exemplo n.º 5
0
 /**
  * Add debugging information include queries and messages to output queue
  *
  * @param Util\Debug $debug
  */
 protected function addDebug(Util\Debug $debug)
 {
     echo "level:\t" . $debug->getLevel() . PHP_EOL;
     echo "database:\t" . Util\Configuration::read('db.driver') . PHP_EOL;
     echo "time:\t" . $debug->getExecutionTime() . PHP_EOL;
     if ($uptime = Util\Debug::getUptime()) {
         echo "uptime:\t" . $uptime * 1000;
     }
     if ($load = Util\Debug::getLoadAvg()) {
         echo "load:\t" . implode(', ', $load) . PHP_EOL;
     }
     if ($commit = Util\Debug::getCurrentCommit()) {
         echo "commit-hash:\t" . $commit . PHP_EOL;
     }
     if ($version = phpversion()) {
         echo "php-version:\t" . $version . PHP_EOL;
     }
     foreach ($debug->getMessages() as $message) {
         echo "message:\t" . $message['message'] . PHP_EOL;
         // TODO add more information
     }
     foreach ($debug->getQueries() as $query) {
         echo "query:\t" . $query['sql'] . PHP_EOL;
         if (isset($query['parameters'])) {
             echo "\tparameters:\t" . implode(', ', $query['parameters']) . PHP_EOL;
         }
     }
 }
Exemplo n.º 6
0
 public function __construct($config = array())
 {
     $this->config = array_replace(array('compressscheme' => array('default' => array(7 * 24 * 60 * 60 => 1 * 60, 30 * 24 * 60 * 60 => 5 * 60, 6 * 30 * 24 * 60 * 60 => 15 * 60, 365 * 24 * 60 * 60 => 30 * 60)), 'verbose' => true, 'caching' => false, 'sleep' => 0), $config);
     $this->cache_init();
     $this->conn = DBAL\DriverManager::getConnection(Util\Configuration::read('db'));
     // SELECT * FROM entities WHERE class = 'channel' plus title property
     $this->channels = $this->sql_query("SELECT entities.*, properties.value AS name FROM entities INNER JOIN properties ON properties.entity_id = entities.id WHERE properties.pkey = ? AND class = ?", array('title', 'channel'));
 }
 /**
  * @todo
  * @param string $capabilities
  * @param string $sub
  */
 public function get($section = NULL)
 {
     $capabilities = array();
     if (is_null($section) || $section == 'configuration') {
         $configuration = array('precision' => View\View::PRECISION, 'database' => Util\Configuration::read('db.driver'), 'debug' => Util\Configuration::read('debug'), 'devmode' => Util\Configuration::read('devmode'));
         if ($commit = Util\Debug::getCurrentCommit()) {
             $configuration['commit'] = $commit;
         }
         $capabilities['configuration'] = $configuration;
     }
     // db statistics - only if specifically requested
     if ($section == 'database') {
         $conn = $this->em->getConnection();
         // get DBAL connection from EntityManager
         // estimate InnoDB tables to avoid performance penalty
         $rows = $conn->fetchAssoc('EXPLAIN SELECT COUNT(id) FROM data USE INDEX (PRIMARY)');
         if (isset($rows['rows'])) {
             $rows = $rows['rows'];
         } else {
             // get correct values for MyISAM
             $rows = $conn->fetchColumn('SELECT COUNT(1) FROM data');
         }
         // database disc space consumption
         $sql = 'SELECT SUM(data_length + index_length) ' . 'FROM information_schema.tables ' . 'WHERE table_schema = ?';
         $size = $conn->fetchColumn($sql, array(Util\Configuration::read('db.dbname')));
         $aggregation = Util\Configuration::read('aggregation');
         $database = array('data_rows' => $rows, 'data_size' => $size, 'aggregation_enabled' => $aggregation ? 1 : 0);
         // aggregation table size
         if ($aggregation) {
             $agg_rows = $conn->fetchColumn('SELECT COUNT(1) FROM aggregate');
             $database['aggregation_rows'] = $agg_rows;
             $database['aggregation_ratio'] = $agg_rows ? $rows / $agg_rows : 0;
         }
         $capabilities['database'] = $database;
     }
     if (is_null($section) || $section == 'formats') {
         $capabilities['formats'] = array_keys(Router::$viewMapping);
     }
     if (is_null($section) || $section == 'contexts') {
         $capabilities['contexts'] = array_keys(Router::$controllerMapping);
     }
     if (is_null($section) || $section == 'definitions') {
         // unresolved artifact from Symfony migration
         // if (!is_null($section)) { // only caching when we don't request dynamic informations
         // 	$this->view->setCaching('expires', time()+2*7*24*60*60); // cache for 2 weeks
         // }
         $capabilities['definitions']['entities'] = Definition\EntityDefinition::get();
         $capabilities['definitions']['properties'] = Definition\PropertyDefinition::get();
     }
     if (count($capabilities) == 0) {
         throw new \Exception('Invalid capability identifier: \'' . $section . '\'');
     }
     return array('capabilities' => $capabilities);
 }
Exemplo n.º 8
0
 /**
  * Purge data
  *
  * prevents doctrine of using single delete statements
  * @todo filter from & to
  */
 public function clearData(\Doctrine\ORM\EntityManager $em)
 {
     $em->getConnection()->beginTransaction();
     $sql = 'DELETE FROM data WHERE channel_id = ?';
     $res = $em->getConnection()->executeQuery($sql, array($this->id));
     // clean aggregation table as well
     if (Util\Configuration::read('aggregation')) {
         $sql = 'DELETE FROM aggregate WHERE channel_id = ?';
         $em->getConnection()->executeQuery($sql, array($this->id));
     }
     $em->getConnection()->commit();
     return $res;
 }
Exemplo n.º 9
0
 /**
  * @group pushserver
  */
 function testPushMessage()
 {
     $this->assertTrue(Util\Configuration::read('push.enabled'), 'Push server disabled');
     $exitCode = null;
     $port = Util\Configuration::read('push.server');
     $curl = "curl %s -s -m 3 -X POST -d '{\"data\":[{\"uuid\":\"%s\",\"tuples\":[[1,1,1]]}]}' localhost:%d 2>&1";
     // run and test for failure
     $cmd = sprintf($curl, '-f', self::$uuid, $port);
     passthru($cmd, $exitCode);
     // run to get output
     if ($exitCode !== 0) {
         $cmd = sprintf($curl, '-i', self::$uuid, $port);
         passthru($cmd);
     }
     $this->assertTrue($exitCode === 0, sprintf('Curl failed with exit code %d', $exitCode));
 }
Exemplo n.º 10
0
 /**
  * @depends testAddTupleGet
  */
 function testDuplicate()
 {
     // INSERT IGNORE syntax not portable
     if (($db = \Volkszaehler\Util\Configuration::read('db.driver')) !== 'pdo_mysql') {
         $this->markTestSkipped('not implemented for ' . $db);
     }
     $url = '/data/' . static::$uuid . '.json';
     // insert duplicate value
     $data = array(array(self::$ts, self::$value));
     // encode query parameters in url for https://github.com/symfony/symfony/issues/14400
     $request = Request::create($url . '?' . http_build_query(array('options' => 'skipduplicates')), 'POST', array(), array(), array(), array(), json_encode($data));
     $request->headers->set('Content-type', 'application/json');
     // 0 rows added, no failure
     $this->assertEquals(0, $this->getJson($request)->rows);
     // insert duplicate value: UniqueConstraintViolationException - currently this will close the EntityManager
     $this->assertEquals('UniqueConstraintViolationException', $this->getJson($url, array('operation' => 'add', 'ts' => self::$ts, 'value' => self::$value), 'GET', true)->exception->type);
 }
Exemplo n.º 11
0
 /**
  * @dataProvider channelDataProvider
  */
 function testAddAndGetRawTuples($type, $resolution)
 {
     // PHP_MAX_INT to float not portable
     if (($db = \Volkszaehler\Util\Configuration::read('db.driver')) === 'pdo_pgsql') {
         $this->markTestSkipped('not implemented for ' . $db);
     }
     self::$uuid = self::createChannel('Test', $type, $resolution);
     $data = array(array('ts' => 1000, 'value' => 1), array('ts' => 2000, 'value' => 2), array('ts' => 3000, 'value' => 3));
     foreach ($data as $tuple) {
         $this->addTuple($tuple['ts'], $tuple['value'], self::$uuid);
     }
     $url = '/data/' . self::$uuid . '.json?options=raw';
     $this->assertTrue(isset($this->getTuplesByUrl($url, 0, PHP_INT_MAX)->data));
     $this->assertEquals(count($data) - 1, count($this->json->data->tuples));
     for ($i = 1; $i < count($data); $i++) {
         $tuple = array_slice($this->json->data->tuples[$i - 1], 0, 2);
         $this->assertEquals(array_values($data[$i]), $tuple);
     }
     self::deleteChannel(self::$uuid);
 }
Exemplo n.º 12
0
 /**
  * Add single or multiple tuples
  *
  * @todo deduplicate Model\Channel code
  * @param string|array uuid
  */
 public function add($uuid)
 {
     $channel = EntityController::factory($this->em, $uuid, true);
     try {
         /* to parse new submission protocol */
         $rawPost = $this->request->getContent();
         // file_get_contents('php://input')
         // check maximum size allowed
         if ($maxSize = Util\Configuration::read('security.maxbodysize')) {
             if (strlen($rawPost) > $maxSize) {
                 throw new \Exception('Maximum message size exceeded');
             }
         }
         $json = Util\JSON::decode($rawPost);
         if (isset($json['data'])) {
             throw new \Exception('Can only add data for a single channel at a time');
             /* backed out b111cfa2 */
         }
         // convert nested ArrayObject to plain array with flattened tuples
         $data = array_reduce($json, function ($carry, $tuple) {
             return array_merge($carry, $tuple);
         }, array());
     } catch (\RuntimeException $e) {
         /* fallback to old method */
         $timestamp = $this->getParameters()->get('ts');
         $value = $this->getParameters()->get('value');
         if (is_null($timestamp)) {
             $timestamp = (double) round(microtime(TRUE) * 1000);
         } else {
             $timestamp = Interpreter::parseDateTimeString($timestamp);
         }
         if (is_null($value)) {
             $value = 1;
         }
         // same structure as JSON request result
         $data = array($timestamp, $value);
     }
     $sql = 'INSERT ' . (in_array(self::OPT_SKIP_DUPLICATES, $this->options) ? 'IGNORE ' : '') . 'INTO data (channel_id, timestamp, value) ' . 'VALUES ' . implode(', ', array_fill(0, count($data) >> 1, '(' . $channel->getId() . ',?,?)'));
     $rows = $this->em->getConnection()->executeUpdate($sql, $data);
     return array('rows' => $rows);
 }
Exemplo n.º 13
0
 /**
  * Constructor
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  * @param string $format one of png, jpeg, gif
  */
 public function __construct(Request $request, $format = 'png')
 {
     parent::__construct($request);
     $this->response->headers->set('Content-Type', 'image/' . $format);
     // load JpGraph
     // NOTE: JpGraph installs its own graphical error handler
     \JpGraph\JpGraph::load();
     \JpGraph\JpGraph::module('date');
     \JpGraph\JpGraph::module('line');
     if ($this->request->query->has('width')) {
         $this->width = $this->request->query->get('width');
     }
     if ($this->request->query->has('height')) {
         $this->height = $this->request->query->get('height');
     }
     $this->colors = Util\Configuration::read('colors');
     $this->graph = new \Graph($this->width, $this->height);
     // disable JpGraph default handler
     restore_exception_handler();
     $this->graph->img->SetImgFormat($format);
     // Specify what scale we want to use,
     $this->graph->SetScale('datlin');
     $this->graph->legend->SetPos(0.03, 0.06);
     $this->graph->legend->SetShadow(FALSE);
     $this->graph->legend->SetFrameWeight(1);
     $this->graph->SetMarginColor('white');
     $this->graph->SetYDeltaDist(65);
     $this->graph->yaxis->SetTitlemargin(36);
     $this->graph->SetTickDensity(TICKD_DENSE, TICKD_SPARSE);
     $this->graph->xaxis->SetFont(FF_ARIAL);
     $this->graph->xaxis->SetLabelAngle(45);
     $this->graph->xaxis->SetLabelFormatCallback(function ($label) {
         return date('j.n.y G:i', $label);
     });
     if (function_exists('imageantialias')) {
         $this->graph->img->SetAntiAliasing(true);
     }
 }
    public function getSingleEntity($uuid, $allowCache = false)
    {
        if (!Util\UUID::validate($uuid)) {
            throw new \Exception('Invalid UUID: \'' . $uuid . '\'');
        }
        if ($allowCache && $this->cache && $this->cache->contains($uuid)) {
            // used hydrated cache result
            return $this->cache->fetch($uuid);
        }
        $dql = 'SELECT a, p
			FROM Volkszaehler\\Model\\Entity a
			LEFT JOIN a.properties p
			WHERE a.uuid = :uuid';
        $q = $this->em->createQuery($dql)->setParameter('uuid', $uuid);
        try {
            $entity = $q->getSingleResult();
            if ($allowCache && $this->cache) {
                $this->cache->save($uuid, $entity, Util\Configuration::read('cache.ttl'));
            }
            return $entity;
        } catch (\Doctrine\ORM\NoResultException $e) {
            throw new \Exception('No entity found with UUID: \'' . $uuid . '\'', 404);
        }
    }
Exemplo n.º 15
0
 * along with volkszaehler.org. If not, see <http://www.gnu.org/licenses/>.
 */
namespace Volkszaehler;

use Volkszaehler\Util;
use Volkszaehler\Controller;
// enable strict error reporting
error_reporting(E_ALL | E_STRICT);
define('VZ_DIR', realpath(__DIR__ . '/..'));
define('VZ_VERSION', '0.2');
// class autoloading
require_once VZ_DIR . '/lib/Util/ClassLoader.php';
require_once VZ_DIR . '/lib/Util/Configuration.php';
// load configuration
Util\Configuration::load(VZ_DIR . '/etc/volkszaehler.conf');
// set timezone
$tz = Util\Configuration::read('timezone') ? Util\Configuration::read('timezone') : @date_default_timezone_get();
date_default_timezone_set($tz);
// set locale
setlocale(LC_ALL, Util\Configuration::read('locale'));
// define include dirs for vendor libs
define('DOCTRINE_DIR', Util\Configuration::read('lib.doctrine') ? Util\Configuration::read('lib.doctrine') : 'Doctrine');
define('JPGRAPH_DIR', Util\Configuration::read('lib.jpgraph') ? Util\Configuration::read('lib.jpgraph') : 'JpGraph');
$classLoaders = array(new Util\ClassLoader('Doctrine', DOCTRINE_DIR), new Util\ClassLoader('Volkszaehler', VZ_DIR . '/lib'));
foreach ($classLoaders as $loader) {
    $loader->register();
    // register on SPL autoload stack
}
$r = new Router();
$r->run();
$r->view->send();
Exemplo n.º 16
0
 /**
  * Add debugging information include queries and messages to output queue
  *
  * @param Util\Debug $debug
  */
 protected function addDebug(Util\Debug $debug)
 {
     $jsonDebug['level'] = $debug->getLevel();
     if ($dbDriver = Util\Configuration::read('db.driver')) {
         $jsonDebug['database'] = $dbDriver;
     }
     $jsonDebug['time'] = $debug->getExecutionTime();
     if ($uptime = Util\Debug::getUptime()) {
         $jsonDebug['uptime'] = $uptime * 1000;
     }
     if ($load = Util\Debug::getLoadAvg()) {
         $jsonDebug['load'] = $load;
     }
     if ($commit = Util\Debug::getCurrentCommit()) {
         $jsonDebug['commit-hash'] = $commit;
     }
     if ($version = phpversion()) {
         $jsonDebug['php-version'] = $version;
     }
     $jsonDebug['messages'] = $debug->getMessages();
     // SQL statements
     $this->getSQLTimes($debug->getQueries());
     $jsonDebug['sql'] = array('totalTime' => $this->sqlTotalTime, 'worstTime' => $this->sqlWorstTime, 'queries' => array_values($debug->getQueries()));
     $this->json['debug'] = $jsonDebug;
 }
Exemplo n.º 17
0
 /**
  * @depends testMultipleGroupByHour
  */
 function testMultipleGroupByHour2()
 {
     // requires weighed average calculation - currently not portable across DBMSes
     if (($db = \Volkszaehler\Util\Configuration::read('db.driver')) !== 'pdo_mysql') {
         $this->markTestSkipped('not implemented for ' . $db);
     }
     $this->addTuple($this->ts4, $this->value4);
     $this->addTuple($this->ts5, $this->value5);
     // get data
     $this->getTuples($this->ts1, $this->ts5, "hour");
     $this->assertFromTo($this->ts1, $this->ts5);
     $consumption = $this->getConsumption($this->ts1, $this->ts2, $this->value2) + $this->getConsumption($this->ts2, $this->ts3, $this->value3) + $this->getConsumption($this->ts3, $this->ts4, $this->value4) + $this->getConsumption($this->ts4, $this->ts5, $this->value5);
     $average = $this->getAverage($this->ts1, $this->ts5, $consumption);
     $this->assertHeader($consumption, $average, 3);
     // tuples
     $this->assertCount(2, $this->json->data->tuples);
     // avg power of last 2 tuples
     $periodValue = $this->getAverage($this->ts2, $this->ts5, $this->getConsumption($this->ts2, $this->ts3, $this->value3) + $this->getConsumption($this->ts3, $this->ts4, $this->value4) + $this->getConsumption($this->ts4, $this->ts5, $this->value5));
     // correct periodValue to raw value
     $this->assertTuple(0, $this->makeTuple($this->ts1, $this->ts2, $this->value2));
     // hour 2
     $this->assertTuple(1, $this->makeTuple($this->ts2, $this->ts5, $periodValue * self::$resolution));
     // hour 3
 }
 /**
  * @param string $section select specific sub section for output
  */
 public function get($section = NULL)
 {
     $capabilities = array();
     if (is_null($section) || $section == 'configuration') {
         $configuration = array('precision' => View\View::PRECISION, 'database' => Util\Configuration::read('db.driver'), 'debug' => Util\Configuration::read('debug'), 'devmode' => Util\Configuration::read('devmode'));
         if ($commit = Util\Debug::getCurrentCommit()) {
             $configuration['commit'] = $commit;
         }
         $capabilities['configuration'] = $configuration;
     }
     // db statistics - only if specifically requested
     if ($section == 'database') {
         $conn = $this->em->getConnection();
         // get DBAL connection from EntityManager
         // estimate InnoDB tables to avoid performance penalty
         $rows = $this->sqlCount($conn, 'data');
         $size = $this->dbSize($conn, 'data');
         $aggregation = Util\Configuration::read('aggregation');
         $database = array('data_rows' => $rows, 'data_size' => $size, 'aggregation_enabled' => $aggregation ? 1 : 0);
         // aggregation table size
         if ($aggregation) {
             $agg_rows = $this->sqlCount($conn, 'aggregate');
             $agg_size = $this->dbSize($conn, 'aggregate');
             $database['aggregation_rows'] = $agg_rows;
             $database['aggregation_size'] = $agg_size;
             $database['aggregation_ratio'] = $agg_rows ? $rows / $agg_rows : 0;
         }
         $capabilities['database'] = $database;
     }
     if (is_null($section) || $section == 'formats') {
         $capabilities['formats'] = array_keys(Router::$viewMapping);
     }
     if (is_null($section) || $section == 'contexts') {
         $capabilities['contexts'] = array_keys(Router::$controllerMapping);
     }
     if (is_null($section) || $section == 'definitions') {
         // unresolved artifact from Symfony migration
         if (!is_null($section)) {
             // only caching when we don't request dynamic informations
             $this->view->setCaching('expires', time() + 2 * 7 * 24 * 60 * 60);
             // cache for 2 weeks
         }
         $capabilities['definitions']['entities'] = Definition\EntityDefinition::get();
         $capabilities['definitions']['properties'] = Definition\PropertyDefinition::get();
     }
     if (count($capabilities) == 0) {
         throw new \Exception('Invalid capability identifier: \'' . $section . '\'');
     }
     return array('capabilities' => $capabilities);
 }
Exemplo n.º 19
0
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with volkszaehler.org. If not, see <http://www.gnu.org/licenses/>.
 */
use Volkszaehler\Util;
// enable strict error reporting
error_reporting(E_ALL | E_STRICT);
// api version
define('VZ_VERSION', '0.3');
// Note: users of bootstrap.php can set VZ_DIR before calling bootstrap
if (!defined('VZ_DIR')) {
    define('VZ_DIR', realpath(__DIR__ . '/..'));
}
if (!file_exists(VZ_DIR . '/vendor/autoload.php')) {
    die('Could not find autoloader. Check that dependencies have been installed via `composer install`.');
}
if (!file_exists(VZ_DIR . '/etc/volkszaehler.conf.php')) {
    die('Could not find config file. Check that etc/volkszaehler.conf.php exists.');
}
require_once VZ_DIR . '/vendor/autoload.php';
// load configuration
Util\Configuration::load(VZ_DIR . '/etc/volkszaehler.conf');
// set timezone
$tz = Util\Configuration::read('timezone') ? Util\Configuration::read('timezone') : @date_default_timezone_get();
date_default_timezone_set($tz);
// set locale
setlocale(LC_ALL, Util\Configuration::read('locale'));
// force numeric output to C convention (issue #121)
setlocale(LC_NUMERIC, 'C');
Exemplo n.º 20
0
 /**
  * Load JSON definitions from file (via lazy loading from get())
  *
  * @todo add caching
  */
 protected static function load()
 {
     static::$definitions = array();
     $cache_id = static::CACHE_KEY . static::FILE;
     if (Util\Configuration::read('devmode') == FALSE && extension_loaded('apc') && apc_exists($cache_id) && time() - filemtime(__DIR__ . '/' . static::FILE) > Util\Configuration::read('cache.ttl')) {
         static::$definitions = apc_fetch($cache_id);
     } else {
         // expensive - cache results
         $json = Util\JSON::decode(file_get_contents(__DIR__ . '/' . static::FILE));
         foreach ($json as $property) {
             static::$definitions[$property->name] = new static($property);
         }
         if (extension_loaded('apc')) {
             apc_store($cache_id, static::$definitions, Util\Configuration::read('cache.ttl'));
         }
     }
 }
Exemplo n.º 21
0
 /**
  * Factory method for Doctrine EntityManager
  *
  * @todo add other caching drivers (memcache, xcache)
  * @todo put into static class? singleton? function or state class?
  */
 public static function createEntityManager($admin = FALSE)
 {
     $config = new ORM\Configuration();
     if (Util\Configuration::read('devmode') == FALSE) {
         $cache = null;
         if (extension_loaded('apcu')) {
             $cache = new Cache\ApcuCache();
         }
         if ($cache) {
             $config->setMetadataCacheImpl($cache);
             $config->setQueryCacheImpl($cache);
         }
     } else {
         if (extension_loaded('apcu')) {
             // clear cache
             apcu_clear_cache('user');
         }
     }
     $driverImpl = $config->newDefaultAnnotationDriver(VZ_DIR . '/lib/Model');
     $config->setMetadataDriverImpl($driverImpl);
     $config->setProxyDir(VZ_DIR . '/lib/Model/Proxy');
     $config->setProxyNamespace('Volkszaehler\\Model\\Proxy');
     $config->setAutoGenerateProxyClasses(Util\Configuration::read('devmode'));
     $dbConfig = Util\Configuration::read('db');
     if ($admin && isset($dbConfig['admin'])) {
         $dbConfig = array_merge($dbConfig, $dbConfig['admin']);
     }
     return ORM\EntityManager::create($dbConfig, $config);
 }
Exemplo n.º 22
0
 /**
  * Add debugging information include queries and messages to output queue
  *
  * @param Util\Debug $debug
  */
 protected function convertDebug(Util\Debug $debug)
 {
     $jsonDebug['level'] = $debug->getLevel();
     if ($dbDriver = Util\Configuration::read('db.driver')) {
         $jsonDebug['database'] = $dbDriver;
     }
     $jsonDebug['time'] = $debug->getExecutionTime();
     if ($uptime = Util\Debug::getUptime()) {
         $jsonDebug['uptime'] = $uptime * 1000;
     }
     if ($load = Util\Debug::getLoadAvg()) {
         $jsonDebug['load'] = $load;
     }
     if ($commit = Util\Debug::getCurrentCommit()) {
         $jsonDebug['commit-hash'] = $commit;
     }
     if ($version = phpversion()) {
         $jsonDebug['php-version'] = $version;
     }
     $jsonDebug['messages'] = $debug->getMessages();
     // SQL statements
     if (count($statements = $debug->getQueries())) {
         $this->getSQLTimes($statements);
         $jsonDebug['sql'] = array('totalTime' => $this->sqlTotalTime, 'worstTime' => $this->sqlWorstTime, 'queries' => array_map(function ($q) {
             return array('sql' => Util\Debug::getParametrizedQuery($q['sql'], $q['params']), 'execTime' => $q['executionMS']);
         }, array_values($debug->getQueries())));
     }
     return $jsonDebug;
 }
Exemplo n.º 23
0
$routes = new RouteCollection();
$router = new Router(new UrlMatcher($routes, new RequestContext()));
// WAMP adapter
$wampRoutes = Util\Configuration::read('push.routes.wamp');
if (is_array($wampRoutes) && count($wampRoutes)) {
    $wampAdapter = new WampClientAdapter();
    $wampServer = new WsServer(new WampServer($wampAdapter));
    foreach ($wampRoutes as $path) {
        addRoute($path, $wampServer);
    }
    $middleware->addAdapter($wampAdapter);
} else {
    $output->writeln("<info>No routes configured for WAMP protocol. Disabling WAMP.</info>");
}
// WebSocket adapter
$wsRoutes = Util\Configuration::read('push.routes.websocket');
if (is_array($wsRoutes) && count($wsRoutes)) {
    $wsAdapter = new WsClientAdapter();
    $wsServer = new WsServer($wsAdapter);
    foreach ($wsRoutes as $path) {
        addRoute($path, $wsServer);
    }
    $middleware->addAdapter($wsAdapter);
} else {
    $output->writeln("<info>No routes configured for WebSocket protocol. Disabling websockets.</info>");
}
// configure remote interface
$remoteSocket = new SocketServer($loop);
$remoteServer = new IoServer(new HttpServer($router), $remoteSocket);
$remoteSocket->listen($remotePort, '0.0.0.0');
// remote clients can connect
Exemplo n.º 24
0
 *
 * volkzaehler.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * volkzaehler.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with volkszaehler.org. If not, see <http://www.gnu.org/licenses/>.
 */
use Volkszaehler\Util;
define('VZ_DIR', realpath(__DIR__ . '/../..'));
// class autoloading
require_once VZ_DIR . '/lib/Util/ClassLoader.php';
require_once VZ_DIR . '/lib/Util/Configuration.php';
// load configuration
Util\Configuration::load(VZ_DIR . '/etc/volkszaehler.conf');
define('DOCTRINE_DIR', Util\Configuration::read('lib.doctrine') ? Util\Configuration::read('lib.doctrine') : 'Doctrine');
$classLoaders = array(new Util\ClassLoader('Doctrine', DOCTRINE_DIR), new Util\ClassLoader('Symfony', DOCTRINE_DIR . '/Symfony'), new Util\ClassLoader('Volkszaehler', VZ_DIR . '/lib'));
foreach ($classLoaders as $loader) {
    $loader->register();
    // register on SPL autoload stack
}
$em = Volkszaehler\Router::createEntityManager(TRUE);
// get admin credentials
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array('db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)));
\Doctrine\ORM\Tools\Console\ConsoleRunner::run($helperSet);
Exemplo n.º 25
0
 /**
  * All tests depend on aggreation being enabled
  * @group aggregation
  */
 function testConfiguration()
 {
     $this->assertTrue(Util\Configuration::read('aggregation'), 'data aggregation not enabled in config file, set $config[\'aggregation\'] = true');
 }
Exemplo n.º 26
0
/**
 * A test for our Configuration class
 *
 * @package tests
 * @copyright Copyright (c) 2011, The volkszaehler.org project
 * @license http://www.gnu.org/licenses/gpl.txt GNU Public License
 * @author Steffen Vogel <*****@*****.**>
 */
/*
 * This file is part of volkzaehler.org
 *
 * volkzaehler.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * volkzaehler.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with volkszaehler.org. If not, see <http://www.gnu.org/licenses/>.
 */
use Volkszaehler\Util;
include '../lib/Util/Configuration.php';
echo '<pre>';
Util\Configuration::load('test.conf');
var_dump(Util\Configuration::read());
Util\Configuration::store('test.conf');
echo '</pre>';