예제 #1
0
function dwInitTwigEnvironment(Twig_Environment $twig)
{
    $twig->setCache(ROOT_PATH . '/tmp/twig');
    $twig->enableAutoReload();
    $twig->addExtension(new Twig_I18n_Extension());
    $twig->addFilter(new Twig_SimpleFilter('purify', function ($dirty) {
        return dwGetHTMLPurifier()->purify($dirty);
    }));
    $twig->addFilter(new Twig_SimpleFilter('json', function ($arr) {
        $mask = 0;
        if (!empty($opts)) {
            if (!empty($opts['pretty'])) {
                $mask = $mask | JSON_PRETTY_PRINT;
            }
        }
        return json_encode($arr, $mask);
    }));
    $twig->addFilter(new Twig_SimpleFilter('css', function ($arr) {
        $css = '';
        foreach ($arr as $prop => $val) {
            $css .= $prop . ':' . $val . ';';
        }
        return $css;
    }));
    $twig->addFunction(new Twig_SimpleFunction('hook', function () {
        call_user_func_array(array(DatawrapperHooks::getInstance(), 'execute'), func_get_args());
    }));
    $twig->addFunction(new Twig_SimpleFunction('has_hook', function ($hook) {
        return DatawrapperHooks::getInstance()->hookRegistered($hook);
    }));
    $twig->addFunction(new Twig_SimpleFunction('has_plugin', function ($plugin) {
        return DatawrapperPluginManager::loaded($plugin);
    }));
    $twig->addFilter(new Twig_SimpleFilter('lettering', function ($text) {
        $out = '';
        foreach (str_split($text) as $i => $char) {
            $out .= '<span class="char' . $i . '">' . $char . '</span>';
        }
        return $out;
    }, array('is_safe' => array('html'))));
    $loc = DatawrapperSession::getLanguage();
    if ($loc == 'en') {
        $loc = 'en-US';
    }
    \Moment\Moment::setLocale(str_replace('-', '_', $loc));
    $twig->addFilter(new Twig_SimpleFilter('reltime', function ($time) {
        // return $time;
        return (new \Moment\Moment($time))->fromNow()->getRelative();
    }));
    if (!empty($GLOBALS['dw_config']['debug'])) {
        $twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
    }
    return $twig;
}
예제 #2
0
function number_format2($number, $decimals = 0)
{
    switch (substr(DatawrapperSession::getLanguage(), 0, 2)) {
        case 'de':
            $k = '.';
            $d = ',';
            break;
        case 'fr':
            $k = ' ';
            $d = ',';
            break;
        default:
            $k = ',';
            $d = '.';
    }
    return number_format($number, $decimals, $d, $k);
}
예제 #3
0
 public function nbChartsByType()
 {
     $con = Propel::getConnection();
     $sql = "SELECT type, COUNT(*) c FROM chart WHERE show_in_gallery = 1 AND last_edit_step >= 4 and deleted = 0 GROUP BY type ORDER BY c DESC ;";
     $rs = $con->query($sql);
     $res = array();
     $max = 0;
     foreach ($rs as $r) {
         $vis = DatawrapperVisualization::get($r['type']);
         $lang = substr(DatawrapperSession::getLanguage(), 0, 2);
         $res[] = array('count' => $r['c'], 'id' => $r['type'], 'name' => $vis['title']);
         $max = max($max, $r['c']);
     }
     foreach ($res as $c => $r) {
         $res[$c]['bar'] = round($r['count'] / $max * 80);
     }
     return $res;
 }
예제 #4
0
function nbChartsByType($user)
{
    $con = Propel::getConnection();
    $sql = "SELECT type, COUNT(*) c FROM chart WHERE author_id = " . $user->getId() . " AND deleted = 0 AND last_edit_step >= 2 GROUP BY type ORDER BY c DESC ;";
    $rs = $con->query($sql);
    $res = array();
    foreach ($rs as $r) {
        $vis = DatawrapperVisualization::get($r['type']);
        $lang = substr(DatawrapperSession::getLanguage(), 0, 2);
        if (!isset($vis['title'])) {
            continue;
        }
        if (empty($vis['title'][$lang])) {
            $lang = 'en';
        }
        $res[] = array('count' => $r['c'], 'id' => $r['type'], 'name' => $vis['title']);
    }
    return $res;
}
예제 #5
0
<?php

/* get session info */
$app->get('/account', function () {
    try {
        $r = DatawrapperSession::toArray();
        ok($r);
    } catch (Exception $e) {
        error('exception', $e->getMessage());
    }
});
/* get current language */
$app->get('/account/lang', function () use($app) {
    ok(DatawrapperSession::getLanguage());
});
/* set a new language */
$app->put('/account/lang', function () use($app) {
    $data = json_decode($app->request()->getBody());
    DatawrapperSession::setLanguage($data->lang);
    ok();
});
/* login user */
$app->post('/auth/login', function () use($app) {
    $payload = json_decode($app->request()->getBody());
    //  v-- don't expire login anymore
    $user = UserQuery::create()->findOneByEmail($payload->email);
    if (!empty($user) && $user->getDeleted() == false) {
        if ($user->getPwd() === secure_password($payload->pwhash)) {
            DatawrapperSession::login($user, $payload->keeplogin == true);
            ok();
        } else {
예제 #6
0
function add_header_vars(&$page, $active = null, $page_css = null)
{
    if (!function_exists('header_nav_hook')) {
        function header_nav_hook(&$headlinks, $part)
        {
            $links = DatawrapperHooks::execute('header_nav_' . $part);
            if (!empty($links)) {
                foreach ($links as $link) {
                    $headlinks[] = $link;
                }
            }
        }
    }
    // define the header links
    global $app;
    $config = $GLOBALS['dw_config'];
    if (!isset($active)) {
        $active = explode('/', $app->request()->getResourceUri());
        $active = $active[1];
    }
    if (!isset($config['prevent_guest_charts'])) {
        $config['prevent_guest_charts'] = false;
    }
    if (!isset($config['prevent_guest_access'])) {
        $config['prevent_guest_access'] = false;
    }
    $user = DatawrapperSession::getUser();
    $headlinks = array();
    if ($user->isLoggedIn()) {
        $headlinks[] = array('url' => '/chart/create', 'id' => 'chart', 'title' => __('New Chart'), 'icon' => 'fa fa-plus');
    }
    header_nav_hook($headlinks, 'create');
    if (isset($config['navigation'])) {
        foreach ($config['navigation'] as $item) {
            $link = array('url' => str_replace('%lang%', substr(DatawrapperSession::getLanguage(), 0, 2), $item['url']), 'id' => $item['id'], 'title' => __($item['title']));
            if (!empty($item['icon'])) {
                $link['icon'] = $item['icon'];
            }
            $headlinks[] = $link;
        }
    }
    if (!$user->isLoggedIn()) {
        header_nav_hook($headlinks, 'logged_out_nav');
    }
    header_nav_hook($headlinks, 'custom_nav');
    // language dropdown
    if (!empty($config['languages'])) {
        $langDropdown = array('url' => '', 'id' => 'lang', 'dropdown' => array(), 'title' => strtoupper(substr(DatawrapperSession::getLanguage(), 0, 2)), 'icon' => false, 'tooltip' => __('Switch language'));
        foreach ($config['languages'] as $lang) {
            $langDropdown['dropdown'][] = array('url' => '#lang-' . $lang['id'], 'title' => $lang['title']);
        }
        if (count($langDropdown['dropdown']) > 1) {
            $headlinks[] = $langDropdown;
        }
    }
    header_nav_hook($headlinks, 'languages');
    if ($user->isLoggedIn()) {
        $headlinks[] = 'divider';
        $username = $user->guessName();
        if ($username == $user->getEmail()) {
            $username = strlen($username) > 18 ? substr($username, 0, 9) . '…' . substr($username, strlen($username) - 9) : $username;
        } else {
            if (strlen($username) > 18) {
                $username = substr($username, 0, 16) . '…';
            }
        }
        $headlinks[] = array('url' => '/account/profile', 'id' => 'account', 'title' => '<img style="height:22px;position:relative;top:-2px;border-radius:7px;margin-right:7px" src="//www.gravatar.com/avatar/' . md5(strtolower(trim($user->getEmail()))) . '?s=44&amp;d=mm" /><b>' . htmlspecialchars($username, ENT_QUOTES, 'UTF-8') . '</b>');
        if ($user->hasCharts()) {
            // mycharts
            $mycharts = array('url' => '/mycharts/', 'id' => 'mycharts', 'title' => __('My Charts'), 'icon' => 'fa fa-bar-chart-o', 'dropdown' => array());
            foreach ($user->getRecentCharts(9) as $chart) {
                $mycharts['dropdown'][] = array('url' => '/chart/' . $chart->getId() . '/visualize#tell-the-story', 'title' => '<img width="30" src="' . ($chart->hasPreview() ? $chart->thumbUrl(true) : '') . '" class="icon" /> ' . '<span>' . strip_tags($chart->getTitle()) . '</span>');
            }
            $mycharts['dropdown'][] = 'divider';
            $mycharts['dropdown'][] = array('url' => '/mycharts/', 'title' => __('All charts'));
            $headlinks[] = $mycharts;
        }
        header_nav_hook($headlinks, 'mycharts');
        // the place where settings used to be
        header_nav_hook($headlinks, 'settings');
    } else {
        $headlinks[] = array('url' => '#login', 'id' => 'login', 'title' => $config['prevent_guest_access'] ? __('Login') : __('Login / Sign Up'), 'icon' => 'fa fa-sign-in');
    }
    if ($user->isLoggedIn()) {
        $headlinks[] = array('url' => '#logout', 'id' => 'signout', 'icon' => 'fa fa-sign-out', 'justicon' => true, 'tooltip' => __('Sign out'));
    }
    header_nav_hook($headlinks, 'user');
    // admin link
    if ($user->isLoggedIn() && $user->isAdmin() && DatawrapperHooks::hookRegistered(DatawrapperHooks::GET_ADMIN_PAGES)) {
        $headlinks[] = 'divider';
        $headlinks[] = array('url' => '/admin', 'id' => 'admin', 'icon' => 'fa fa-gears', 'justicon' => true, 'tooltip' => __('Admin'));
    }
    header_nav_hook($headlinks, 'admin');
    if (DatawrapperHooks::hookRegistered(DatawrapperHooks::CUSTOM_LOGO)) {
        $logos = DatawrapperHooks::execute(DatawrapperHooks::CUSTOM_LOGO);
        $page['custom_logo'] = $logos[0];
    }
    foreach ($headlinks as $i => $link) {
        if ($link == 'divider') {
            continue;
        }
        $headlinks[$i]['active'] = $headlinks[$i]['id'] == $active;
    }
    $page['headlinks'] = $headlinks;
    $page['user'] = DatawrapperSession::getUser();
    $page['language'] = substr(DatawrapperSession::getLanguage(), 0, 2);
    $page['locale'] = DatawrapperSession::getLanguage();
    $page['DW_DOMAIN'] = $config['domain'];
    $page['DW_VERSION'] = DATAWRAPPER_VERSION;
    $page['ASSET_DOMAIN'] = $config['asset_domain'];
    $page['DW_CHART_CACHE_DOMAIN'] = $config['chart_domain'];
    $page['SUPPORT_EMAIL'] = $config['email']['support'];
    $page['config'] = $config;
    $page['page_css'] = $page_css;
    $page['invert_navbar'] = isset($config['invert_header']) && $config['invert_header'] || substr($config['domain'], -4) == '.pro';
    $page['noSignup'] = $config['prevent_guest_access'];
    $page['alternative_signins'] = DatawrapperHooks::execute(DatawrapperHooks::ALTERNATIVE_SIGNIN);
    $page['footer'] = DatawrapperHooks::execute(DatawrapperHooks::GET_FOOTER);
    $uri = $app->request()->getResourceUri();
    $plugin_assets = DatawrapperHooks::execute(DatawrapperHooks::GET_PLUGIN_ASSETS, $uri);
    if (!empty($plugin_assets)) {
        $plugin_js_files = array();
        $plugin_css_files = array();
        foreach ($plugin_assets as $assets) {
            if (!is_array($assets)) {
                $assets = array($assets);
            }
            foreach ($assets as $asset) {
                $file = $asset[0];
                $plugin = $asset[1];
                if (substr($file, -3) == '.js') {
                    $plugin_js_files[] = $file . '?v=' . $plugin->getVersion();
                }
                if (substr($file, -4) == '.css') {
                    $plugin_css_files[] = $file . '?v=' . $plugin->getVersion();
                }
            }
        }
        $page['plugin_js'] = $plugin_js_files;
        $page['plugin_css'] = $plugin_css_files;
    }
    if (isset($config['piwik'])) {
        $page['PIWIK_URL'] = $config['piwik']['url'];
        $page['PIWIK_IDSITE'] = $config['piwik']['idSite'];
        if (isset($config['piwik']['idSiteNoCharts'])) {
            $page['PIWIK_IDSITE_NO_CHARTS'] = $config['piwik']['idSiteNoCharts'];
        }
    }
    if ($config['debug']) {
        if (file_exists('../.git')) {
            // parse git branch
            $head = file_get_contents('../.git/HEAD');
            $parts = explode("/", $head);
            $branch = trim($parts[count($parts) - 1]);
            $output = array();
            exec('git rev-parse HEAD', $output);
            $commit = $output[0];
            $page['BRANCH'] = ' (<a href="https://github.com/datawrapper/datawrapper/tree/' . $commit . '">' . $branch . '</a>)';
        }
    }
}
예제 #7
0
});
//GET route
$app->get('/setup', function () use($app) {
    disable_cache($app);
    if (DatawrapperSession::getUser()->isLoggedIn() || UserQuery::create()->filterByRole(array('admin', 'sysadmin'))->count() > 0) {
        $app->redirect('/');
    }
    $page = array('title' => 'Datawrapper', 'pageClass' => 'setup', 'noHeader' => true, 'noFooter' => true, 'noSignup' => true, 'auth_salt' => DW_AUTH_SALT);
    add_header_vars($page, '');
    $app->render('setup.twig', $page);
});
/*
 * endpoint for final setup script
 */
$app->post('/setup', function () use($app) {
    $data = json_decode($app->request()->getBody());
    // check that there is no admin user yet (only true right after setup)
    if (UserQuery::create()->count() == 0) {
        $user = new User();
        $user->setCreatedAt(time());
        $user->setEmail($data->email);
        $user->setRole('admin');
        $user->setPwd(secure_password($data->pwd));
        $user->setLanguage(DatawrapperSession::getLanguage());
        $user->save();
        DatawrapperSession::login($user);
        $app->redirect('/');
    } else {
        print json_encode(array('status' => 'fail'));
    }
});
예제 #8
0
function get_chart_content($chart, $user, $published = false, $debug = false)
{
    if (!function_exists('unique_scripts')) {
        function unique_scripts($scripts)
        {
            $exist = array();
            $out = array();
            foreach ($scripts as $s) {
                $src = is_array($s) ? $s['src'] : $s;
                if (isset($exist[$src])) {
                    continue;
                }
                $exist[$src] = true;
                $out[] = is_array($s) ? $s : array('src' => $s);
            }
            return $out;
        }
    }
    $theme_css = array();
    $theme_js = array();
    $protocol = get_current_protocol();
    $next_theme_id = $chart->getTheme();
    $locale = DatawrapperSession::getLanguage();
    if ($chart->getLanguage() != '') {
        $locale = $chart->getLanguage();
    }
    $static_path = $GLOBALS['dw_config']['static_path'];
    $abs = $protocol . '://' . $GLOBALS['dw_config']['domain'];
    if ($static_path == 'static/') {
        $static_path = $abs . $static_path;
    }
    while (!empty($next_theme_id)) {
        $theme = DatawrapperTheme::get($next_theme_id);
        // $theme_static_path = str_replace('/static/', $static_path . '/', $theme['__static_path']);
        $theme_static_path = $theme['__static_path'];
        $theme_js[] = $theme_static_path . $next_theme_id . '.js';
        if ($theme['hasStyles']) {
            $theme_css[] = $theme_static_path . $next_theme_id . '.css';
        }
        $next_theme_id = $theme['extends'];
    }
    $abs = $protocol . '://' . $GLOBALS['dw_config']['domain'];
    $debug = $GLOBALS['dw_config']['debug'] == true || $debug;
    $culture = str_replace('_', '-', $locale);
    if ($published && !empty($GLOBALS['dw_config']['asset_domain'])) {
        $base_js = array('//' . $GLOBALS['dw_config']['asset_domain'] . '/globalize.min.js', '//' . $GLOBALS['dw_config']['asset_domain'] . '/cultures/globalize.culture.' . $culture . '.js', '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js', '//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js');
    } else {
        // use "local" assets
        $base_js = array($abs . '/static/vendor/globalize/globalize.min.js', $abs . '/static/vendor/globalize/cultures/globalize.culture.' . $culture . '.js', $abs . '/static/vendor/underscore/underscore-min.js', $abs . '/static/vendor/jquery/jquery.min.js');
    }
    $vis_js = array();
    $vis_css = array();
    $next_vis_id = $chart->getType();
    $vis_libs = array();
    $vis_libs_cdn = array();
    $vis_libs_local = array();
    $vis_locale = array();
    // visualizations may define localized strings, e.g. "other"
    while (!empty($next_vis_id)) {
        $vis = DatawrapperVisualization::get($next_vis_id);
        // $vis_static_path = str_replace('/static/', $static_path . '/', $vis['__static_path']);
        $vis_static_path = $vis['__static_path'];
        $vjs = array();
        if (!empty($vis['libraries'])) {
            foreach (array_reverse($vis['libraries']) as $script) {
                if (!is_array($script)) {
                    $script = array("local" => $script, "cdn" => false);
                }
                if (!empty($script['cdn'])) {
                    $script['src'] = $script['cdn'];
                    $vis_libs_cdn[] = $script;
                }
                // at first we check if the library lives in ./lib of the vis module
                if (file_exists(ROOT_PATH . 'www' . $vis['__static_path'] . $script['local'])) {
                    $u = $vis_static_path . $script['local'];
                } else {
                    if (file_exists(ROOT_PATH . 'www/static/vendor/' . $script['local'])) {
                        $u = '/static/vendor/' . $script['local'];
                    } else {
                        print ROOT_PATH . 'www' . $vis['__static_path'] . $script['local'];
                        die("could not find required library " . $script["local"]);
                    }
                }
                $script['src'] = $u;
                $vis_libs[] = $script;
                if (empty($url['cdn'])) {
                    $vis_libs_local[] = $script;
                }
            }
        }
        if (!empty($vis['locale']) && is_array($vis['locale'])) {
            foreach ($vis['locale'] as $term => $translations) {
                if (!isset($vis_locale[$term])) {
                    $vis_locale[$term] = $translations;
                }
            }
        }
        $vjs[] = $vis_static_path . $vis['id'] . '.js';
        $vis_js = array_merge($vis_js, array_reverse($vjs));
        if ($vis['hasCSS']) {
            $vis_css[] = $vis_static_path . $vis['id'] . '.css';
        }
        $next_vis_id = !empty($vis['extends']) ? $vis['extends'] : null;
    }
    $stylesheets = array_merge(array('/static/css/chart.base.css'), $vis_css, array_reverse($theme_css));
    $the_vis = DatawrapperVisualization::get($chart->getType());
    $the_vis['locale'] = $vis_locale;
    $the_theme = DatawrapperTheme::get($chart->getTheme());
    $l10n__domain = $the_theme['__static_path'];
    $the_vis_js = get_vis_js($the_vis, array_merge(array_reverse($vis_js), $vis_libs_local));
    $the_theme_js = get_theme_js($the_theme, array_reverse($theme_js));
    $the_chart_js = get_chart_js();
    if ($published) {
        $scripts = array_merge($base_js, $vis_libs_cdn, array('/lib/' . $the_vis_js[0], '/lib/' . $the_theme_js[0], '/lib/' . $the_chart_js[0]));
        $stylesheets = array($chart->getID() . '.all.css');
        // NOTE: replace `/static/` by `assets/` in the `__static_path` value,
        //       since vis assets are handle by DatawrapperVisualization
        $replace_in = $the_vis['__static_path'];
        $replace_by = 'assets/';
        $replace = '/static/';
        $the_vis['__static_path'] = substr_replace($replace_in, $replace_by, strrpos($replace_in, $replace), strlen($replace));
        // length
        $the_theme['__static_path'] = '';
    } else {
        $scripts = unique_scripts(array_merge($base_js, array($static_path . '/js/dw-2.0' . ($debug ? '' : '.min') . '.js'), array_reverse($theme_js), array_reverse($vis_js), array_reverse($vis_libs), array($static_path . '/js/dw/chart.base.js')));
    }
    $cfg = $GLOBALS['dw_config'];
    $published_urls = DatawrapperHooks::execute(DatawrapperHooks::GET_PUBLISHED_URL, $chart);
    if (empty($published_urls)) {
        $chart_url = $protocol . '://' . $cfg['chart_domain'] . '/' . $chart->getID() . '/';
    } else {
        $chart_url = $published_urls[0];
        // ignore urls except from the first one
    }
    $page = array('chartData' => $chart->loadData(), 'chart' => $chart, 'lang' => strtolower(substr($locale, 0, 2)), 'metricPrefix' => get_metric_prefix($locale), 'l10n__domain' => $l10n__domain, 'origin' => !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '', 'DW_DOMAIN' => $protocol . '://' . $cfg['domain'] . '/', 'DW_CHART_DATA' => $protocol . '://' . $cfg['domain'] . '/chart/' . $chart->getID() . '/data.csv', 'ASSET_PATH' => $published ? '' : $the_theme['__static_path'], 'published' => $published, 'chartUrl' => $chart_url, 'embedCode' => '<iframe src="' . $chart_url . '" frameborder="0" allowtransparency="true" allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen width="' . $chart->getMetadata('publish.embed-width') . '" height="' . $chart->getMetadata('publish.embed-height') . '"></iframe>', 'chartUrlFs' => strpos($chart_url, '.html') > 0 ? str_replace('index.html', 'fs.html', $chart_url) : $chart_url . '?fs=1', 'stylesheets' => $stylesheets, 'scripts' => $scripts, 'visualization' => $the_vis, 'theme' => $the_theme, 'chartLocale' => str_replace('_', '-', $locale), 'vis_js' => $the_vis_js, 'theme_js' => $the_theme_js, 'chart_js' => $the_chart_js);
    return $page;
}
예제 #9
0
 */
$app->get('/xhr/header/:page', function ($active) use($app) {
    disable_cache($app);
    $page = array();
    add_header_vars($page, $active);
    $res = $app->response();
    $res['Cache-Control'] = 'max-age=0';
    $app->render('header.twig', $page);
});
/**
 * reloads the header menu after login/logout
 */
$app->get('/xhr/home-login', function () use($app) {
    $page = array();
    add_header_vars($page);
    $res = $app->response();
    $res['Cache-Control'] = 'max-age=0';
    $app->render('home-login.twig', $page);
});
/**
 * reloads visualization specific options after the user
 * changed the visualization type
 */
require_once '../lib/utils/themes.php';
$app->get('/xhr/:chartid/vis-options', function ($id) use($app) {
    disable_cache($app);
    check_chart_writable($id, function ($user, $chart) use($app) {
        $page = array('vis' => DatawrapperVisualization::get($chart->getType()), 'theme' => DatawrapperTheme::get($chart->getTheme()), 'language' => substr(DatawrapperSession::getLanguage(), 0, 2));
        $app->render('vis-options.twig', $page);
    });
});
예제 #10
0
<?php

/*
 * DESCRIBE STEP
 */
$app->get('/chart/:id/describe', function ($id) use($app) {
    disable_cache($app);
    check_chart_writable($id, function ($user, $chart) use($app) {
        $page = array('title' => $chart->getID() . ' :: ' . __('Check & Describe'), 'chartData' => $chart->loadData(), 'chart' => $chart);
        add_header_vars($page, 'chart', 'chart-editor/describe.css');
        add_editor_nav($page, 2);
        switch (substr(DatawrapperSession::getLanguage(), 0, 2)) {
            case 'de':
                $k = '.';
                $d = ',';
                break;
            case 'fr':
                $k = ' ';
                $d = ',';
                break;
            default:
                $k = ',';
                $d = '.';
        }
        $page['columntypes'] = array('text' => 'Text', 'number' => 'Number', 'date' => 'Date');
        $page['numberformats'] = array('n3' => '3 (' . number_format(1234.56789, 3, $d, $k) . ')', 'n2' => '2 (' . number_format(1234.56789, 2, $d, $k) . ')', 'n1' => '1 (' . number_format(1234.56789, 1, $d, $k) . ')', 'n0' => '0 (' . number_format(1234.56789, 0, $d, $k) . ')');
        $page['significantdigits'] = array('s6' => '6 (' . number_format(1234.56789, 2, $d, $k) . ')', 's5' => '5 (' . number_format(123.456789, 2, $d, $k) . ')', 's4' => '4 (' . number_format(12.34, 2, $d, $k) . ')', 's3' => '3 (' . number_format(1.23, 2, $d, $k) . ')', 's2' => '2 (' . number_format(0.12, 2, $d, $k) . ')', 's1' => '1 (' . number_format(0.01, 2, $d, $k) . ')');
        $app->render('chart/describe.twig', $page);
    });
});
예제 #11
0
function add_header_vars(&$page, $active = null)
{
    // define the header links
    global $app;
    $config = $GLOBALS['dw_config'];
    if (!isset($active)) {
        $active = explode('/', $app->request()->getResourceUri());
        $active = $active[1];
    }
    $user = DatawrapperSession::getUser();
    $headlinks = array();
    if ($user->isLoggedIn() || empty($config['prevent_guest_charts'])) {
        $headlinks[] = array('url' => '/chart/create', 'id' => 'chart', 'title' => __('Create Chart'), 'icon' => 'pencil');
    }
    if ($user->isLoggedIn() && $user->hasCharts()) {
        $headlinks[] = array('url' => '/mycharts/', 'id' => 'mycharts', 'title' => __('My Charts'), 'icon' => 'signal');
    } else {
        $headlinks[] = array('url' => '/gallery/', 'id' => 'gallery', 'title' => __('Gallery'), 'icon' => 'signal');
    }
    if (isset($config['navigation'])) {
        foreach ($config['navigation'] as $item) {
            $link = array('url' => str_replace('%lang%', substr(DatawrapperSession::getLanguage(), 0, 2), $item['url']), 'id' => $item['id'], 'title' => __($item['title']));
            if (!empty($item['icon'])) {
                $link['icon'] = $item['icon'];
            }
            $headlinks[] = $link;
        }
    }
    // language dropdown
    if (!empty($config['languages'])) {
        $langDropdown = array('url' => '', 'id' => 'lang', 'dropdown' => array(), 'title' => __('Language'), 'icon' => 'font');
        foreach ($config['languages'] as $lang) {
            $langDropdown['dropdown'][] = array('url' => '#lang-' . $lang['id'], 'title' => $lang['title']);
        }
        if (count($langDropdown['dropdown']) > 1) {
            $headlinks[] = $langDropdown;
        }
    }
    if ($user->isLoggedIn()) {
        $shortenedMail = $user->getEmail();
        $shortenedMail = strlen($shortenedMail) > 18 ? substr($shortenedMail, 0, 9) . '...' . substr($shortenedMail, strlen($shortenedMail) - 9) : $shortenedMail;
        $headlinks[] = array('url' => '#user', 'id' => 'user', 'title' => $shortenedMail, 'icon' => 'user', 'dropdown' => array(array('url' => '/account/settings', 'icon' => 'wrench', 'title' => __('Settings')), array('url' => '#logout', 'icon' => 'off', 'title' => __('Logout'))));
        if ($user->isAdmin()) {
            $headlinks[] = array('url' => '/admin', 'id' => 'admin', 'icon' => 'fire', 'title' => __('Admin'));
        }
    } else {
        $headlinks[] = array('url' => '#login', 'id' => 'login', 'title' => __('Login / Sign Up'), 'icon' => 'user');
    }
    foreach ($headlinks as $i => $link) {
        $headlinks[$i]['active'] = $headlinks[$i]['id'] == $active;
    }
    $page['headlinks'] = $headlinks;
    $page['user'] = DatawrapperSession::getUser();
    $page['language'] = substr(DatawrapperSession::getLanguage(), 0, 2);
    $page['locale'] = DatawrapperSession::getLanguage();
    $page['DW_DOMAIN'] = $config['domain'];
    $page['DW_VERSION'] = DATAWRAPPER_VERSION;
    $page['DW_CHART_CACHE_DOMAIN'] = $config['chart_domain'];
    $page['ADMIN_EMAIL'] = $config['email']['admin'];
    $page['config'] = $config;
    $page['invert_navbar'] = substr($config['domain'], -4) == '.pro';
    $uri = $app->request()->getResourceUri();
    $plugin_assets = DatawrapperHooks::execute(DatawrapperHooks::GET_PLUGIN_ASSETS, $uri);
    if (!empty($plugin_assets)) {
        $plugin_js_files = array();
        $plugin_css_files = array();
        foreach ($plugin_assets as $files) {
            if (!is_array($files)) {
                $files = array($files);
            }
            foreach ($files as $file) {
                if (substr($file, -3) == '.js') {
                    $plugin_js_files[] = $file;
                }
                if (substr($file, -4) == '.css') {
                    $plugin_css_files[] = $file;
                }
            }
        }
        $page['plugin_js'] = $plugin_js_files;
        $page['plugin_css'] = $plugin_css_files;
    }
    if (isset($config['piwik'])) {
        $page['PIWIK_URL'] = $config['piwik']['url'];
        $page['PIWIK_IDSITE'] = $config['piwik']['idSite'];
        if (isset($config['piwik']['idSiteNoCharts'])) {
            $page['PIWIK_IDSITE_NO_CHARTS'] = $config['piwik']['idSiteNoCharts'];
        }
    }
    if ($config['debug']) {
        if (file_exists('../.git')) {
            // parse git branch
            $head = file_get_contents('../.git/HEAD');
            $parts = explode("/", $head);
            $page['BRANCH'] = ' (' . trim($parts[count($parts) - 1]) . ')';
        }
    }
}
예제 #12
0
function get_chart_content($chart, $user, $published = false, $debug = false)
{
    $theme_css = array();
    $theme_js = array();
    $next_theme_id = $chart->getTheme();
    $locale = DatawrapperSession::getLanguage();
    while (!empty($next_theme_id)) {
        $theme = DatawrapperTheme::get($next_theme_id);
        $theme_js[] = $theme['__static_path'] . $next_theme_id . '.js';
        if ($theme['hasStyles']) {
            $theme_css[] = $theme['__static_path'] . $next_theme_id . '.css';
        }
        $next_theme_id = $theme['extends'];
    }
    $abs = 'http://' . $GLOBALS['dw_config']['domain'];
    $debug = $GLOBALS['dw_config']['debug'] == true || $debug;
    if ($published && !$debug) {
        $base_js = array('//assets-datawrapper.s3.amazonaws.com/globalize.min.js', '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js', '//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js');
        if (substr($locale, 0, 2) != 'en') {
            $base_js[] = '//assets-datawrapper.s3.amazonaws.com/cultures/globalize.culture.' . str_replace('_', '-', $locale) . '.js';
        }
    } else {
        // use local assets
        $base_js = array($abs . '/static/vendor/globalize/globalize.min.js', $abs . '/static/vendor/underscore/underscore-min.js', $abs . '/static/vendor/jquery/jquery-1.9.1' . ($debug ? '' : '.min') . '.js');
        if (substr($locale, 0, 2) != 'en') {
            $base_js[] = $abs . '/static/vendor/globalize/cultures/globalize.culture.' . str_replace('_', '-', $locale) . '.js';
        }
    }
    $vis_js = array();
    $vis_css = array();
    $next_vis_id = $chart->getType();
    $vis_libs = array();
    $vis_locale = array();
    // visualizations may define localized strings, e.g. "other"
    while (!empty($next_vis_id)) {
        $vis = DatawrapperVisualization::get($next_vis_id);
        $vjs = array();
        if (!empty($vis['libraries'])) {
            foreach ($vis['libraries'] as $url) {
                // at first we check if the library lives in ./lib of the vis module
                if (file_exists(ROOT_PATH . 'www/' . $vis['__static_path'] . $url)) {
                    $vis_libs[] = $vis['__static_path'] . $url;
                } else {
                    if (file_exists(ROOT_PATH . 'www/static/vendor/' . $url)) {
                        $vis_libs[] = '/static/vendor/' . $url;
                    }
                }
            }
        }
        if (!empty($vis['locale']) && is_array($vis['locale'])) {
            foreach ($vis['locale'] as $term => $translations) {
                if (!isset($vis_locale[$term])) {
                    $vis_locale[$term] = $translations;
                }
            }
        }
        $vjs[] = $vis['__static_path'] . $vis['id'] . '.js';
        $vis_js = array_merge($vis_js, array_reverse($vjs));
        if ($vis['hasCSS']) {
            $vis_css[] = $vis['__static_path'] . $vis['id'] . '.css';
        }
        $next_vis_id = !empty($vis['extends']) ? $vis['extends'] : null;
    }
    $styles = array_merge($vis_css, array_reverse($theme_css));
    $the_vis = DatawrapperVisualization::get($chart->getType());
    $the_vis['locale'] = $vis_locale;
    $the_theme = DatawrapperTheme::get($chart->getTheme());
    if ($published) {
        $scripts = array_merge($base_js, array('/lib/vis/' . $the_vis['id'] . '-' . $the_vis['version'] . '.min.js', '/lib/theme/' . $the_theme['id'] . '-' . $the_theme['version'] . '.min.js'));
        $styles = array($chart->getID() . '.min.css');
        $the_vis['__static_path'] = '';
        $the_theme['__static_path'] = '';
    } else {
        $scripts = array_unique(array_merge($base_js, array('/static/js/datawrapper' . ($debug ? '' : '.min') . '.js'), array_reverse($theme_js), array_reverse($vis_js), $vis_libs));
    }
    $cfg = $GLOBALS['dw_config'];
    $published_urls = DatawrapperHooks::execute(DatawrapperHooks::GET_PUBLISHED_URL, $chart);
    if (empty($published_urls)) {
        $chart_url = 'http://' . $cfg['chart_domain'] . '/' . $chart->getID() . '/';
    } else {
        $chart_url = $published_urls[0];
        // ignore urls except from the first one
    }
    $page = array('chartData' => $chart->loadData(), 'chart' => $chart, 'chartLocale' => str_replace('_', '-', $locale), 'lang' => strtolower(substr($locale, 0, 2)), 'metricPrefix' => get_metric_prefix($locale), 'theme' => $the_theme, 'l10n__domain' => $the_theme['__static_path'], 'visualization' => $the_vis, 'stylesheets' => $styles, 'scripts' => $scripts, 'themeJS' => array_reverse($theme_js), 'visJS' => array_merge(array_reverse($vis_js), $vis_libs), 'origin' => !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '', 'DW_DOMAIN' => 'http://' . $cfg['domain'] . '/', 'DW_CHART_DATA' => 'http://' . $cfg['domain'] . '/chart/' . $chart->getID() . '/data', 'ASSET_PATH' => $published ? '' : $the_theme['__static_path'], 'trackingCode' => !empty($analyticsMod) ? $analyticsMod->getTrackingCode($chart) : '', 'chartUrl' => $chart_url, 'embedCode' => '<iframe src="' . $chart_url . '" frameborder="0" allowtransparency="true" allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen width="' . $chart->getMetadata('publish.embed-width') . '" height="' . $chart->getMetadata('publish.embed-height') . '"></iframe>', 'chartUrlFs' => strpos($chart_url, '.html') > 0 ? str_replace('index.html', 'fs.html', $chart_url) : $chart_url . '?fs=1');
    return $page;
}
예제 #13
0
<?php

$locale = str_replace('-', '_', DatawrapperSession::getLanguage());
$domain = 'messages';
putenv('LANGUAGE=' . $locale);
setlocale(LC_ALL, $locale);
setlocale(LC_TIME, $locale . '.utf8');
class Datawrapper_L10N
{
    private $__messages = array();
    /*
     * load messages
     */
    public function loadMessages($locale)
    {
        global $memcache;
        $locale = str_replace('-', '_', $locale);
        $mkey = 'l10n-messages-' . $locale;
        if (isset($_GLOBALS['dw-config']['memcache'])) {
            // pull translation from memcache
            $msg = $memcache->get($mkey);
            if (!empty($msg)) {
                return $msg;
            }
        }
        // core
        $messages = array();
        $messages['core'] = $this->parse(ROOT_PATH . 'locale/' . $locale . '.json');
        $plugins = PluginQuery::create()->filterByEnabled(true)->find();
        foreach ($plugins as $plugin) {
            $messages[$plugin->getName()] = $this->parse($plugin->getPath() . 'locale/' . $locale . '.json');
예제 #14
0
<?php

define('ROOT_PATH', dirname(dirname(__FILE__)) . '/');
define('NO_SLIM', 1);
define('NO_SESSION', 1);
require ROOT_PATH . 'lib/bootstrap.php';
if (isset($dw_config['memcache'])) {
    $memcache->flush();
    print "flushed memcache!\n";
} else {
    print "memcache is not configured.\n";
}
DatawrapperSession::setLanguage("de_DE");
print DatawrapperSession::getLanguage() . "\n";
print __("This little tool reduces the time needed to create a correct chart and embed it into any website from hours to seconds. It makes charting easy, and helps you avoiding common pitfalls.");