Beispiel #1
0
function check_chart_public($id, $callback)
{
    $chart = ChartQuery::create()->findPK($id);
    $loggedUser = DatawrapperSession::getUser();
    if ($chart) {
        $user = $chart->getUser();
        if ($user->isAbleToPublish()) {
            if ($chart->isPublic() || $user == $loggedUser) {
                call_user_func($callback, $user, $chart);
            } else {
                if ($chart->_isDeleted()) {
                    error_chart_deleted();
                } else {
                    error_chart_not_published();
                }
            }
        } else {
            // no such chart
            error_not_allowed_to_publish();
        }
    } else {
        // no such chart
        error_chart_not_found($id);
    }
}
 public static function getInstance()
 {
     if (self::$datawrapper === null) {
         self::$datawrapper = new DatawrapperSession();
     }
     return self::$datawrapper;
 }
Beispiel #3
0
function if_is_admin($callback)
{
    $user = DatawrapperSession::getUser();
    if ($user->isAdmin()) {
        call_user_func($callback);
    } else {
        error('access-denied', 'need admin privileges.');
    }
}
Beispiel #4
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;
}
 private function _all($ignoreRestrictions)
 {
     $res = array_values($this->themes);
     $user = DatawrapperSession::getInstance()->getUser();
     $email = $user->getEmail();
     $domain = substr($email, strpos($email, '@'));
     $res = array();
     foreach ($this->themes as $meta) {
         $res[] = $meta;
     }
     return $res;
 }
 private function _all($ignoreRestrictions)
 {
     $res = array_values($this->themes);
     $user = DatawrapperSession::getInstance()->getUser();
     $email = $user->getEmail();
     $domain = substr($email, strpos($email, '@'));
     $res = array();
     foreach ($this->themes as $meta) {
         if (!isset($meta['restrict']) || $meta['restrict'] == $domain || $meta['restrict'] == $email || $ignoreRestrictions === true || $user->isAdmin()) {
             // of course, admins can see all, too
             $res[] = $meta;
         }
     }
     return $res;
 }
Beispiel #7
0
/**
 * checks if a chart is writeable by the current user (or guest)
 *
 * @param chart_id
 * @param callback the function to be executed if chart is writable
 */
function if_chart_is_writable($chart_id, $callback)
{
    $chart = ChartQuery::create()->findPK($chart_id);
    if (!empty($chart)) {
        $user = DatawrapperSession::getUser();
        $res = $chart->isWritable($user);
        if ($res === true) {
            call_user_func($callback, $user, $chart);
        } else {
            error('access-denied', $res);
        }
    } else {
        error('no-such-chart', '');
    }
}
Beispiel #8
0
 public function users($app, $page)
 {
     $page = array_merge($page, array('title' => __('Users'), 'q' => $app->request()->params('q', '')));
     $sort = $app->request()->params('sort', '');
     $user = DatawrapperSession::getUser();
     function getQuery($user)
     {
         global $app;
         $sort = $app->request()->params('sort', '');
         $query = UserQuery::create()->leftJoin('User.Chart')->withColumn('COUNT(Chart.Id)', 'NbCharts')->groupBy('User.Id')->filterByDeleted(false);
         $q = $app->request()->params('q');
         if ($q) {
             $query->where('email LIKE "%' . $q . '%" OR name LIKE "%' . $q . '%"');
         }
         if (!$user->isSysAdmin()) {
             $query->filterByRole('sysadmin', Criteria::NOT_EQUAL);
         }
         switch ($sort) {
             case 'name':
                 $query->orderByName('asc');
                 break;
             case 'email':
                 $query->orderByEmail('asc');
                 break;
             case 'charts':
                 $query->orderBy('NbCharts', 'desc');
                 break;
             case 'created_at':
             default:
                 $query->orderBy('createdAt', 'desc');
                 break;
         }
         return $query;
     }
     $curPage = $app->request()->params('page', 0);
     $total = getQuery($user)->count();
     $perPage = 50;
     $append = '';
     if ($page['q']) {
         $append = '&q=' . $page['q'];
     }
     if (!empty($sort)) {
         $append .= '&sort=' . $sort;
     }
     add_pagination_vars($page, $total, $curPage, $perPage, $append);
     $page['users'] = getQuery($user)->limit($perPage)->offset($curPage * $perPage)->find();
     $app->render('plugins/admin-users/admin-users.twig', $page);
 }
function check_chart_writable($id, $callback)
{
    $chart = ChartQuery::create()->findPK($id);
    if ($chart) {
        $user = DatawrapperSession::getUser();
        if ($chart->isWritable($user) === true) {
            call_user_func($callback, $user, $chart);
        } else {
            // no such chart
            error_chart_not_writable();
        }
    } else {
        // no such chart
        error_chart_not_found($id);
    }
}
Beispiel #10
0
 public function init()
 {
     $plugin = $this;
     // hook into chart publication
     DatawrapperHooks::register(DatawrapperHooks::GET_CHART_ACTIONS, function () use($plugin) {
         // no export possible without email
         $user = DatawrapperSession::getUser();
         if ($user->getEmail() == '') {
             return array();
         }
         return array('id' => 'export-image', 'title' => __("Export to static image for printing", $plugin->getName()), 'icon' => 'print');
     });
     // provide static assets files
     $this->declareAssets(array('export-image.js', 'export-image.css'), "|/chart/[^/]+/publish|");
     // hook into job execution
     DatawrapperHooks::register('export_image', array($this, 'exportImage'));
 }
Beispiel #11
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);
}
Beispiel #12
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;
 }
Beispiel #13
0
function user_charts($app, $user, $key, $val)
{
    $curPage = $app->request()->params('page');
    $q = $app->request()->params('q');
    if (empty($curPage)) {
        $curPage = 0;
    }
    $perPage = 12;
    $filter = !empty($key) ? array($key => $val) : array();
    if (!empty($q)) {
        $filter['q'] = $q;
    }
    $charts = ChartQuery::create()->getPublicChartsByUser($user, $filter, $curPage * $perPage, $perPage);
    $total = ChartQuery::create()->countPublicChartsByUser($user, $filter);
    $page = array('charts' => $charts, 'bymonth' => nbChartsByMonth($user), 'byvis' => nbChartsByType($user), 'bylayout' => nbChartsByLayout($user), 'bystatus' => nbChartsByStatus($user), 'key' => $key, 'val' => $val, 'search_query' => empty($q) ? '' : $q, 'mycharts_base' => '/mycharts');
    if (DatawrapperSession::getUser()->isAdmin() && $user != DatawrapperSession::getUser()) {
        $page['user2'] = $user;
        $page['mycharts_base'] = '/admin/charts/' . $user->getId();
        $page['all_users'] = UserQuery::create()->filterByDeleted(false)->orderByEmail()->find();
    }
    add_header_vars($page, 'mycharts');
    add_pagination_vars($page, $total, $curPage, $perPage, empty($q) ? '' : '&q=' . $q);
    $app->render('mycharts.twig', $page);
}
Beispiel #14
0
function get_theme_js($theme, $themeJS)
{
    $all = '';
    $org = DatawrapperSession::getUser()->getCurrentOrganization();
    if (!empty($org)) {
        $org = '/' . $org->getID();
    } else {
        $org = '';
    }
    $keys = DatawrapperHooks::execute(DatawrapperHooks::GET_PUBLISH_STORAGE_KEY);
    if (is_array($keys)) {
        $org .= '/' . join($keys, '/');
    }
    foreach ($themeJS as $js) {
        if (substr($js, 0, 7) != "http://" && substr($js, 0, 8) != "https://" && substr($js, 0, 2) != '//') {
            $all .= "\n\n\n" . file_get_contents(ROOT_PATH . 'www' . $js);
        }
    }
    $all = jsminify($all);
    $theme_js_md5 = md5($all . $org);
    $theme_path = 'theme/' . $theme['id'] . '-' . $theme_js_md5 . '.min.js';
    return array($theme_path, $all);
}
Beispiel #15
0
require_once ROOT_PATH . 'controller/admin.php';
$app->notFound(function () {
    error_not_found();
});
if ($dw_config['debug']) {
    $app->get('/phpinfo', function () use($app) {
        phpinfo();
    });
}
/*
 * before processing any other route we check if the
 * user is not logged in and if prevent_guest_access is activated.
 * if both is true we redirect to /login
 */
$app->hook('slim.before.router', function () use($app, $dw_config) {
    $user = DatawrapperSession::getUser();
    // allow logged-in users
    if ($user->isLoggedIn()) {
        return;
    }
    // allow access if this is a public installation
    if (empty($dw_config['prevent_guest_access'])) {
        return;
    }
    // allow access if a proper secret is given (required for publishing charts
    // (see download()) in private installations)
    $requiredKey = sha1(isset($dw_config['secure_auth_key']) ? $dw_config['secure_auth_key'] : '');
    $givenKey = isset($_REQUEST['seckey']) ? $_REQUEST['seckey'] : null;
    if ($requiredKey === $givenKey) {
        return;
    }
Beispiel #16
0
        $pwd = $payload->pwd;
    }
    if ($curUser->isLoggedIn()) {
        if ($user_id == 'current' || $curUser->getId() === $user_id) {
            $user = $curUser;
        } else {
            if ($curUser->isAdmin()) {
                $user = UserQuery::create()->findPK($user_id);
                $pwd = $user->getPwd();
            }
        }
        if (!empty($user)) {
            if ($user->getPwd() == $pwd) {
                // Delete user
                if (!$curUser->isAdmin()) {
                    DatawrapperSession::logout();
                }
                $user->erase();
                ok();
            } else {
                Action::logAction($user, 'delete-request-wrong-password', json_encode(get_user_ips()));
                error('wrong-password', __('The password you entered is not correct.'));
            }
        } else {
            error('user-not-found', 'no user found with that id');
        }
    } else {
        error('need-login', 'you must be logged in to do that');
    }
});
$app->put('/account/reset-password', function () use($app) {
 public function getConfig()
 {
     if (isset($GLOBALS['dw_config']['plugins'][$this->getName()])) {
         $cfg = $GLOBALS['dw_config']['plugins'][$this->getName()];
     } else {
         $cfg = array();
     }
     // apply organization-specific custom configuration
     $org = DatawrapperSession::getUser()->getCurrentOrganization();
     if (!empty($org)) {
         $pd = PluginDataQuery::create()->filterByPlugin($this->getPluginOM())->where('PluginData.Key LIKE ?', 'custom_config/' . $org->getId() . '/%')->find();
         foreach ($pd as $c) {
             $k = explode('/', $c->getKey());
             $k = explode('.', $k[2]);
             if (count($k) == 1) {
                 $cfg[$k[0]] = $c->getData();
             } else {
                 if (count($k) == 2) {
                     $cfg[$k[0]][$k[1]] = $c->getData();
                 } else {
                     if (count($k) == 3) {
                         $cfg[$k[0]][$k[1]][$k[2]] = $c->getData();
                     } else {
                         if (count($k) == 4) {
                             $cfg[$k[0]][$k[1]][$k[2]][$k[3]] = $c->getData();
                         }
                     }
                 }
             }
         }
     }
     return $cfg;
 }
Beispiel #18
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);
    });
});
Beispiel #19
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');
Beispiel #20
0
 public static function load()
 {
     if (defined('NO_SESSION')) {
         $plugins = PluginQuery::create()->distinct()->filterByEnabled(true)->filterByIsPrivate(false)->find();
     } else {
         $plugins = self::getUserPlugins(DatawrapperSession::getUser()->getId());
     }
     $not_loaded_yet = array();
     foreach ($plugins as $plugin) {
         if (!isset(self::$loaded[$plugin->getId()])) {
             $not_loaded_yet[] = $plugin;
         }
     }
     $could_not_install = array();
     $init_queue = array();
     $load_plugin = function ($plugin) use(&$init_queue) {
         $plugin_path = ROOT_PATH . 'plugins/' . $plugin->getName();
         // first if this plugin uses composer, require the autoloader
         if (file_exists($plugin_path . '/vendor/autoload.php')) {
             require_once $plugin_path . '/vendor/autoload.php';
         }
         if (file_exists($plugin_path . '/plugin.php')) {
             require_once $plugin_path . '/plugin.php';
             // init plugin class
             $className = $plugin->getClassName();
             $pluginClass = new $className();
         } else {
             $pluginClass = new DatawrapperPlugin($plugin->getName());
             if (file_exists($plugin_path . '/init.php')) {
                 $pluginClass->injectInitFunction(function ($plugin) use($plugin_path) {
                     include_once $plugin_path . '/init.php';
                 });
             }
         }
         // then, lets also load the libraries required by this lib
         // this is DEPRECATED, all new plugins should use the autoload
         // method using composer or similar
         foreach ($pluginClass->getRequiredLibraries() as $lib) {
             require_once $plugin_path . '/' . $lib;
         }
         $init_queue[] = $pluginClass;
         return $pluginClass;
     };
     while (count($not_loaded_yet) > 0) {
         $try = $not_loaded_yet;
         $not_loaded_yet = array();
         while (count($try) > 0) {
             $plugin = array_shift($try);
             $id = $plugin->getId();
             $deps = $plugin->getDependencies();
             unset($deps['core']);
             // ignore core dependency
             $can_load = true;
             if (is_array($deps)) {
                 foreach ($deps as $dep => $version) {
                     if (!isset(self::$loaded[$dep])) {
                         // dependency not loaded
                         $can_load = false;
                         if (!file_exists(ROOT_PATH . 'plugins/' . $dep) || isset($could_not_install[$dep])) {
                             // dependency does not exists, not good
                             $could_not_install[$id] = true;
                         }
                         break;
                     }
                 }
             }
             if (isset(self::$loaded[$id]) && self::$loaded[$id]) {
                 // plugin already loaded by now
                 continue;
             }
             if ($can_load) {
                 // load plugin
                 self::$loaded[$id] = true;
                 self::$instances[$id] = $load_plugin($plugin);
             } else {
                 if (!isset($could_not_install[$id])) {
                     $not_loaded_yet[] = $plugin;
                     // so try next time
                 }
             }
         }
     }
     // now initialize all plugins
     while (count($init_queue) > 0) {
         $pluginClass = array_shift($init_queue);
         $pluginClass->init();
     }
 }
Beispiel #21
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]) . ')';
        }
    }
}
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;
}
Beispiel #23
0
/*
 * secure passwords with secure_auth_key, if configured
 */
function secure_password($pwd)
{
    global $dw_config;
    if (isset($dw_config['secure_auth_key'])) {
        return hash_hmac('sha256', $pwd, $dw_config['secure_auth_key']);
    } else {
        return $pwd;
    }
}
require ROOT_PATH . 'lib/session/database.php';
require ROOT_PATH . 'lib/session/DatawrapperSession.php';
if (!defined('NO_SESSION')) {
    DatawrapperSession::initSession();
}
function debug_log($txt)
{
    $h = fopen(ROOT_PATH . 'log.txt', 'a+');
    fwrite($h, microtime(true) . ': ' . $txt . "\n");
    fclose($h);
}
require ROOT_PATH . 'lib/l10n.php';
require ROOT_PATH . 'lib/utils/parse_config.php';
parse_config();
if (!defined('NO_SLIM')) {
    // Initialize Slim app..
    if (ROOT_PATH == '../') {
        // ..either with TwigView for Datawrapper UI,...
        require_once ROOT_PATH . 'vendor/Slim-Extras/Views/TwigView.php';
Beispiel #24
0
    $app->get('/account/?', function () use($app, $pages) {
        $app->redirect('/account/' . $pages[0]['url'] . '/');
    });
    // redirect to settings
    $app->get('/settings/?', function () use($app) {
        $app->redirect('/account');
    });
    $user = DatawrapperSession::getUser();
    foreach ($pages as $page) {
        $context = array('title' => $page['title'], 'gravatar' => md5(strtolower(trim($user->getEmail()))), 'pages' => $pages, 'active' => $page['url'], 'user' => $user);
        add_header_vars($context, 'account');
        $app->get('/account/' . $page['url'] . '/?', function () use($app, $context, $page) {
            $u = DatawrapperSession::getUser();
            if ($u->isSysAdmin()) {
                if ($app->request()->get('uid') != null) {
                    $u = UserQuery::create()->findPk($app->request()->get('uid'));
                    if ($u) {
                        $context['user'] = $u;
                        $context['notme'] = $u != DatawrapperSession::getUser();
                        $context['gravatar'] = md5(strtolower(trim($u->getEmail())));
                        // update links to other pages
                        for ($i = 0; $i < count($context['pages']); $i++) {
                            $context['pages'][$i]['params'] = '?uid=' . $u->getId();
                        }
                    }
                }
            }
            call_user_func_array($page['controller']($app, $context), func_get_args());
        });
    }
});
<?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.");
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>)';
        }
    }
}
Beispiel #27
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);
    });
});
Beispiel #28
0
/*
 * endpoint for validating an invitation. The user sends his new password
 */
$app->post('/account/invitation/:token', function ($token) use($app) {
    $data = json_decode($app->request()->getBody());
    if (!empty($token)) {
        $users = UserQuery::create()->filterByActivateToken($token)->find();
        if (count($users) != 1) {
            error("token-invalid", __("This activation token is invalid. Your email address is probably already activated."));
        } elseif (empty($data->pwd1)) {
            error("password-missing", __("You must enter a password."));
        } elseif ($data->pwd1 != $data->pwd2) {
            error("password-mismatch", __("Both passwords must be the same."));
        } else {
            $user = $users[0];
            $user->setActivateToken('');
            $user->setPwd($data->pwd1);
            $user->save();
            // NOTE: we don't need a confirmation.
            # send confirmation email
            // $name   = $user->getEmail();
            // $domain = $GLOBALS['dw_config']['domain'];
            // $from   = $GLOBALS['dw_config']['email'];
            // $link = 'http://' . $domain;
            // include('../../lib/templates/confirmation-email.php');
            // mail($name, __('Confirmation of account creation') . ' ' . $domain, $confirmation_email, 'From: ' . $from);
            DatawrapperSession::login($user);
            ok();
        }
    }
});
Beispiel #29
0
 public static function load()
 {
     $plugins = PluginQuery::create()->filterByEnabled(true);
     if (!defined('NO_SESSION')) {
         $user_id = DatawrapperSession::getUser()->getId();
         if (!empty($user_id)) {
             $plugins->where('Plugin.Id IN (SELECT plugin_id FROM plugin_organization WHERE organization_id IN (SELECT organization_id FROM user_organization WHERE user_id = ?))', $user_id)->_or();
         }
         $plugins = $plugins->where('Plugin.IsPrivate = FALSE');
     }
     $plugins = $plugins->find();
     $not_loaded_yet = array();
     foreach ($plugins as $plugin) {
         if (!isset(self::$loaded[$plugin->getId()])) {
             $not_loaded_yet[] = $plugin;
         }
     }
     $could_not_install = array();
     if (!function_exists('load_plugin')) {
         function load_plugin($plugin)
         {
             $plugin_path = ROOT_PATH . 'plugins/' . $plugin->getName() . '/plugin.php';
             if (file_exists($plugin_path)) {
                 require $plugin_path;
                 // init plugin class
                 $className = $plugin->getClassName();
                 $pluginClass = new $className();
             } else {
                 $pluginClass = new DatawrapperPlugin($plugin->getName());
             }
             // but before we load the libraries required by this lib
             foreach ($pluginClass->getRequiredLibraries() as $lib) {
                 require_once ROOT_PATH . 'plugins/' . $plugin->getName() . '/' . $lib;
             }
             $pluginClass->init();
             return $pluginClass;
         }
     }
     while (count($not_loaded_yet) > 0) {
         $try = $not_loaded_yet;
         $not_loaded_yet = array();
         while (count($try) > 0) {
             $plugin = array_shift($try);
             $id = $plugin->getId();
             $deps = $plugin->getDependencies();
             unset($deps['core']);
             // ignore core dependency
             $can_load = true;
             if (is_array($deps)) {
                 foreach ($deps as $dep => $version) {
                     if (!isset(self::$loaded[$dep])) {
                         // dependency not loaded
                         $can_load = false;
                         if (!file_exists(ROOT_PATH . 'plugins/' . $dep) || isset($could_not_install[$dep])) {
                             // dependency does not exists, not good
                             $could_not_install[$id] = true;
                         }
                         break;
                     }
                 }
             }
             if (isset(self::$loaded[$id]) && self::$loaded[$id]) {
                 // plugin already loaded by now
                 continue;
             }
             if ($can_load) {
                 // load plugin
                 self::$loaded[$id] = true;
                 self::$instances[$id] = load_plugin($plugin);
             } else {
                 if (!isset($could_not_install[$id])) {
                     $not_loaded_yet[] = $plugin;
                     // so try next time
                 }
             }
         }
     }
 }