public function controller($app) { $plugin = $this; $app->get('/gallery(/?|/by/:key/:val)', function ($key = false, $val = false) use($app, $plugin) { disable_cache($app); $user = DatawrapperSession::getUser(); $curPage = $app->request()->params('page'); if (empty($curPage)) { $curPage = 0; } $perPage = 60; $filter = !empty($key) ? array($key => $val) : array(); try { $charts = ChartQuery::create()->getGalleryCharts($filter, $curPage * $perPage, $perPage); $total = ChartQuery::create()->countGalleryCharts($filter); } catch (Exception $e) { // make sure bogus input for the filter doesn't kill the site $charts = array(); $total = 0; } $page = array('charts' => $charts, 'byvis' => $plugin->nbChartsByType(), 'key' => $key, 'val' => $val); add_pagination_vars($page, $total, $curPage, $perPage); add_header_vars($page, 'gallery'); $app->render('plugins/' . $plugin->getName() . '/gallery.twig', $page); }); }
function check_chart_exists($id, $callback) { $chart = ChartQuery::create()->findPK($id); if ($chart) { call_user_func($callback, $chart); } else { // no such chart error_chart_not_found($id); } }
public function dashboard($app, $page) { // returns a CSV from a MySQL resultset function res2csv($rs) { $csv = ""; $keys = array(); $results = array(); foreach ($rs as $r) { if (count($keys) == 0) { foreach ($r as $key => $val) { if (is_string($key)) { $keys[] = $key; } } $csv = implode(";", $keys) . "\\n"; } $results[] = $r; } $results = array_reverse($results); foreach ($results as $r) { $values = array(); foreach ($keys as $key) { $values[] = $r[$key]; } $csv .= implode(";", $values) . "\\n"; } return $csv; } $con = Propel::getConnection(); $data = array(); $publised_sql = 'SELECT DATE_FORMAT(published_at, \'%Y-%m-%d\') pub_date, COUNT(*) pub_count FROM `chart` WHERE last_edit_step = 5 GROUP BY pub_date ORDER BY `pub_date` DESC LIMIT 1,90'; $publised_week_sql = 'SELECT DATE_FORMAT(published_at, \'%Y-w%u\') pub_date, COUNT(*) pub_count FROM `chart` WHERE last_edit_step = 5 GROUP BY pub_date ORDER BY `pub_date` DESC LIMIT 1,26'; $user_signups_sql = 'SELECT DATE_FORMAT(created_at, \'%Y-%m-%d\') create_date, COUNT(*) user_count FROM `user` GROUP BY create_date ORDER BY `create_date` DESC LIMIT 1,90'; $numUsers = UserQuery::create()->filterByDeleted(false)->count(); $numUsersPending = UserQuery::create()->filterByDeleted(false)->filterByRole(UserPeer::ROLE_PENDING)->count(); $numUsersActivated = UserQuery::create()->filterByDeleted(false)->filterByRole(UserPeer::ROLE_EDITOR)->count(); $numUsersDeleted = UserQuery::create()->filterByDeleted(true)->count(); $users_csv = "Type;Count\\nPending;{$numUsersPending}\\nActivated;{$numUsersActivated}\\nDeleted;{$numUsersDeleted}"; $numCharts = ChartQuery::create()->filterByDeleted(false)->count(); $numChartsUpload = ChartQuery::create()->filterByLastEditStep(array('max' => 1))->filterByDeleted(false)->count(); $numChartsDescribe = ChartQuery::create()->filterByLastEditStep(2)->filterByDeleted(false)->count(); $numChartsVisualize = ChartQuery::create()->filterByLastEditStep(3)->filterByDeleted(false)->count(); $numChartsPublished = ChartQuery::create()->filterByLastEditStep(array('min' => 4))->filterByDeleted(false)->count(); $charts_csv = "LastEditStep;Count\\nUpload;{$numChartsUpload}\\nDescribe;{$numChartsDescribe}\\nVisualize;{$numChartsVisualize}\\nPublish;{$numChartsPublished}\\n"; $charts_by_type_csv = res2csv($con->query('SELECT type, COUNT(*) FROM chart WHERE deleted = 0 GROUP BY type;')); $charts_by_type_csv = str_replace('-chart', '', $charts_by_type_csv); $page = array_merge($page, array('num_users' => $numUsers, 'num_users_activated' => $numUsersActivated, 'num_charts' => $numCharts, 'num_charts_published' => $numChartsPublished, 'published_csv' => res2csv($con->query($publised_sql)), 'published_week_csv' => res2csv($con->query($publised_week_sql)), 'users_csv' => $users_csv, 'charts_edit_step_csv' => $charts_csv, 'charts_by_type_csv' => $charts_by_type_csv, 'created_csv' => res2csv($con->query('SELECT DATE_FORMAT(created_at, \'%Y-%m-%d\') pub_date, COUNT(*) pub_count FROM `chart` GROUP BY pub_date ORDER BY `pub_date` DESC LIMIT 1,90')), 'created_weekly_csv' => res2csv($con->query('SELECT DATE_FORMAT(created_at, \'%Y-w%u\') pub_date, COUNT(*) pub_count FROM `chart` GROUP BY pub_date ORDER BY `pub_date` DESC LIMIT 1,26')), 'user_signups_csv' => res2csv($con->query($user_signups_sql)), 'linechart' => DatawrapperVisualization::get('line-chart'), 'columnchart' => DatawrapperVisualization::get('column-chart'), 'donutchart' => DatawrapperVisualization::get('donut-chart'), 'chartLocale' => 'en-US')); $app->render('plugins/admin-dashboard/admin-dashboard.twig', $page); }
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); }
} } $org->save(); ok(array('active' => $org->hasPlugin($plugin))); } }); })->conditions(array('op' => '(remove|add|toggle|config)')); /* * get charts of an organization */ $app->get('/organizations/:id/charts', function ($org_id) use($app) { $user = DatawrapperSession::getUser(); $org = OrganizationQuery::create()->findPk($org_id); if ($org) { if ($org->hasUser($user) || $user->isAdmin()) { $query = ChartQuery::create()->filterByDeleted(false)->orderByLastModifiedAt(Criteria::DESC)->filterByOrganization($org); // filter by visualization $vis = $app->request()->get('vis'); if (isset($vis)) { $vis = explode(',', $vis); $conds = array(); foreach ($vis as $v) { $query->condition($conds[] = 'c' . count($conds), 'Chart.Type = ?', $v); } $query->where($conds, 'or'); } // filter by month $months = $app->request()->get('months'); if (isset($months)) { $months = explode(',', $months); $conds = array();
<?php $app->get('/chart/create', function () use($app) { disable_cache($app); $cfg = $GLOBALS['dw_config']; $user = DatawrapperSession::getUser(); if (!$user->isLoggedIn() && isset($cfg['prevent_guest_charts']) && $cfg['prevent_guest_charts']) { error_access_denied(); } else { $chart = ChartQuery::create()->createEmptyChart($user); $app->redirect('/chart/' . $chart->getId() . '/upload'); } });
public static function login($user, $keepLoggedIn = true, $dontLog = false) { $_SESSION['dw-user-id'] = $user->getId(); self::getInstance()->user = $user; if (!$dontLog) { Action::logAction($user, 'login'); } // reload plugins since there might be new plugins // becoming available after logins DatawrapperPluginManager::load(); $_SESSION['persistent'] = $keepLoggedIn; $_SESSION['last_action_time'] = time(); // make sure that the charts of the guest now belong to // the logged or newly created user $charts = ChartQuery::create()->findByGuestSession(session_id()); foreach ($charts as $chart) { $chart->setAuthorId($user->getId()); $chart->setGuestSession(''); $chart->save(); } // restore user organization if (empty($_SESSION['dw-user-organization'])) { // let's check the last chart $lastChart = ChartQuery::create()->filterByUser($user)->filterByOrganizationId(null, Criteria::ISNOTNULL)->orderByLastModifiedAt(Criteria::DESC)->findOne(); if (!empty($lastChart)) { $_SESSION['dw-user-organization'] = $lastChart->getOrganization()->getId(); } } }
$d = array(array(1, "second"), array(60, "minute"), array(3600, "hour"), array(86400, "day"), array(604800, "week"), array(2592000, "month"), array(31104000, "year")); $w = array(); $return = array(); $now = time(); $diff = $now - $time; $secondsLeft = $diff; for ($i = 6; $i > -1; $i--) { $w[$i] = intval($secondsLeft / ($d[$i][0] * 2)); $secondsLeft -= $w[$i] * $d[$i][0]; if ($w[$i] != 0) { $return[] = abs($w[$i] * 2) . " " . $d[$i][1] . ($w[$i] > 1 ? 's' : '') . " "; } } $return = implode(' and ', array_slice($return, 0, 1)); //. ($diff>0 ?"ago" : "left"); return $return; }; return array('url' => '/themes', 'title' => __('Themes', $plugin->getName()), 'controller' => function ($app, $page) use($plugin, $relativeTime) { $themes = DatawrapperTheme::all(); foreach ($themes as $i => $theme) { $c = ChartQuery::create()->filterByTheme($theme['id'])->orderByLastModifiedAt('desc')->findOne(); if ($c) { $themes[$i]['last_used'] = $relativeTime(strtotime($c->getLastModifiedAt())); } else { $themes[$i]['last_used'] = 'never'; } } $page = array_merge($page, array('title' => 'Themes', 'themes' => $themes, 'count' => count_charts_per_themes())); $app->render('plugins/' . $plugin->getName() . '/admin-themes.twig', $page); }, 'order' => '3'); });
/** * Removes this object from datastore and sets delete attribute. * * @param PropelPDO $con * @return void * @throws PropelException * @see BaseObject::setDeleted() * @see BaseObject::isDeleted() */ public function delete(PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("This object has already been deleted."); } if ($con === null) { $con = Propel::getConnection(ChartPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $deleteQuery = ChartQuery::create()->filterByPrimaryKey($this->getPrimaryKey()); $ret = $this->preDelete($con); if ($ret) { $deleteQuery->delete($con); $this->postDelete($con); $con->commit(); $this->setDeleted(true); } else { $con->commit(); } } catch (Exception $e) { $con->rollBack(); throw $e; } }
<?php //GET route $app->get('/', function () use($app) { disable_cache($app); if ($app->request()->get('c')) { // found link to a legacy chart $app->redirect('/legacy/' . $app->request()->get('c') . '.html'); } else { $chart_ids = array('RXoKw', 'a4Yyf', '78iap', 'weD23'); $charts = ChartQuery::create()->findPKs($chart_ids); $page = array('title' => '', 'pageClass' => 'home', 'recent_charts' => $charts); add_header_vars($page, ''); $app->render('home.twig', $page); } });
public static function login($user, $keepLoggedIn = true) { $_SESSION['dw-user-id'] = $user->getId(); self::getInstance()->user = $user; Action::logAction($user, 'login'); $_SESSION['persistent'] = $keepLoggedIn; $_SESSION['last_action_time'] = time(); // make sure that the charts of the guest now belong to // the logged or newly created user $charts = ChartQuery::create()->findByGuestSession(session_id()); foreach ($charts as $chart) { $chart->setAuthorId($user->getId()); $chart->setGuestSession(''); $chart->save(); } }
/** * Returns the number of related Chart objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related Chart objects. * @throws PropelException */ public function countCharts(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if (null === $this->collCharts || null !== $criteria) { if ($this->isNew() && null === $this->collCharts) { return 0; } else { $query = ChartQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query->filterByUser($this)->count($con); } } else { return count($this->collCharts); } }
$user = new User(); $user->setEmail('test'); $pwd = !empty($dw_config['testuser_pwd']) ? $dw_config['testuser_pwd'] : 'test'; $user->setPwd(hash_hmac('sha256', $pwd, DW_AUTH_SALT)); $user->setRole('editor'); $user->setCreatedAt(time()); $user->save(); $themes = DatawrapperTheme::all(true); foreach (glob("../test/test-charts/*.json") as $test) { $config = json_decode(file_get_contents($test), true); $data = $config['_data']; unset($config['_data']); unset($config['_sig']); if (isset($config['_id'])) { $config['metadata']['describe']['__test_id'] = $config['_id']; unset($config['_id']); } unset($config['id']); foreach ($themes as $theme) { $chart = new Chart(); $chart->setId(ChartQuery::create()->getUnusedRandomId()); $chart->setUser($user); $chart->unserialize($config); $chart->writeData($data); $chart->setTheme($theme['id']); $chart->setLastEditStep(5); $chart->save(); } } print "To see the charts, please visit\n"; print 'http://' . $GLOBALS['dw_config']['domain'] . '/admin/charts/' . $user->getId() . "\n";
public function getRecentCharts($count = 10) { return ChartQuery::create()->filterByUser($this)->filterByDeleted(false)->filterByLastEditStep(array("min" => 3))->orderByLastModifiedAt('desc')->limit($count)->find(); }
/** * Returns a new ChartQuery object. * * @param string $modelAlias The alias of a model in the query * @param ChartQuery|Criteria $criteria Optional Criteria to build the query from * * @return ChartQuery */ public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof ChartQuery) { return $criteria; } $query = new ChartQuery(); if (null !== $modelAlias) { $query->setModelAlias($modelAlias); } if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
/** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this User is new, it will return * an empty collection; or if this User has previously * been saved, it will retrieve related Charts from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in User. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelObjectCollection|Chart[] List of Chart objects */ public function getChartsJoinChartRelatedByForkedFrom($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = ChartQuery::create(null, $criteria); $query->joinWith('ChartRelatedByForkedFrom', $join_behavior); return $this->getCharts($query, $con); }
public function chartCount() { return count(ChartQuery::create()->getPublicChartsByUser($this)); }
/** * Get the associated Chart object * * @param PropelPDO Optional Connection object. * @return Chart The associated Chart object. * @throws PropelException */ public function getChart(PropelPDO $con = null) { if ($this->aChart === null && ($this->chart_id !== "" && $this->chart_id !== null)) { $this->aChart = ChartQuery::create()->findPk($this->chart_id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aChart->addJobs($this); */ } return $this->aChart; }
function if_chart_exists($id, $callback) { $chart = ChartQuery::create()->findPK($id); if ($chart) { call_user_func($callback, $chart); } else { // no such chart error('no-such-chart', ''); } }
/** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this Chart is new, it will return * an empty collection; or if this Chart has previously * been saved, it will retrieve related ChartsRelatedById from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in Chart. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelObjectCollection|Chart[] List of Chart objects */ public function getChartsRelatedByIdJoinOrganization($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = ChartQuery::create(null, $criteria); $query->joinWith('Organization', $join_behavior); return $this->getChartsRelatedById($query, $con); }
$sql = "SELECT type, COUNT(*) c FROM chart WHERE show_in_gallery = 1 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; } $app->get('/gallery(/?|/by/:key/:val)', function ($key = false, $val = false) use($app) { disable_cache($app); $user = DatawrapperSession::getUser(); $curPage = $app->request()->params('page'); if (empty($curPage)) { $curPage = 0; } $perPage = 12; $filter = !empty($key) ? array($key => $val) : array(); $charts = ChartQuery::create()->getGalleryCharts($filter, $curPage * $perPage, $perPage); $total = ChartQuery::create()->countGalleryCharts($filter); $page = array('charts' => $charts, 'bymonth' => gal_nbChartsByMonth(), 'byvis' => gal_nbChartsByType(), 'key' => $key, 'val' => $val); add_pagination_vars($page, $total, $curPage, $perPage); add_header_vars($page, 'gallery'); $app->render('gallery.twig', $page); });
<?php /** * API: get data to a chart * * @param chart_id chart id */ $app->get('/chart/:id/data(\\.csv)?', function ($chart_id) use($app) { disable_cache($app); $chart = ChartQuery::create()->findPK($chart_id); $res = $app->response(); $res['Cache-Control'] = 'max-age=0'; $res['Content-Type'] = 'text/csv'; $res['Content-Disposition'] = 'attachment; filename="datawrapper-' . $chart_id . '.csv"'; if (!empty($chart)) { print $chart->loadData(); } else { error_chart_not_found($chart_id); } });
/** * checks if a chart is reable by the current user (or guest) * * @param chart_id * @param callback the function to be executed if chart is writable */ function if_chart_is_readable($chart_id, $callback) { $chart = ChartQuery::create()->findPK($chart_id); if ($chart) { $user = DatawrapperSession::getUser(); if ($chart->isReadable($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); } }