Beispiel #1
0
 public function configureView(ViewDataTable $view)
 {
     if ($view->isViewDataTableId(Sparklines::ID)) {
         $view->requestConfig->apiMethodToRequestDataTable = 'VisitFrequency.get';
         $this->addSparklineColumns($view);
         $view->config->addTranslations($this->getSparklineTranslations());
         $numberFormatter = NumberFormatter::getInstance();
         $view->config->filters[] = function (DataTable $table) use($numberFormatter) {
             $firstRow = $table->getFirstRow();
             if ($firstRow) {
                 $value = $firstRow->getColumn('nb_visits_returning');
                 if (false !== $value) {
                     $firstRow->setColumn('nb_visits_returning', $numberFormatter->formatNumber($value));
                 }
                 $value = $firstRow->getColumn('nb_actions_returning');
                 if (false !== $value) {
                     $firstRow->setColumn('nb_actions_returning', $numberFormatter->formatNumber($value));
                 }
                 $value = $firstRow->getColumn('nb_actions_per_visit_returning');
                 if (false !== $value) {
                     $firstRow->setColumn('nb_actions_per_visit_returning', $numberFormatter->formatNumber($value, 1));
                 }
                 $value = $firstRow->getColumn('bounce_rate_returning');
                 if (false !== $value) {
                     $firstRow->setColumn('bounce_rate_returning', $numberFormatter->formatNumber($value, $precision = 1));
                 }
             }
         };
     }
 }
Beispiel #2
0
 public function getMetrics($domain)
 {
     try {
         $response = Http::sendHttpRequest(self::URL . urlencode($domain), $timeout = 10, @$_SERVER['HTTP_USER_AGENT']);
         $xml = @simplexml_load_string($response);
         $value = $xml ? NumberFormatter::getInstance()->formatNumber((int) $xml->SD->POPULARITY['TEXT']) : null;
     } catch (\Exception $e) {
         $this->logger->warning('Error while getting Alexa SEO stats: {message}', array('message' => $e->getMessage()));
         $value = null;
     }
     $logo = \Piwik\Plugins\Referrers\getSearchEngineLogoFromUrl('http://alexa.com');
     $link = self::LINK . urlencode($domain);
     return array(new Metric('alexa', 'SEO_AlexaRank', $value, $logo, $link));
 }
Beispiel #3
0
 public function renderReport($processedReport)
 {
     $isGoalPluginEnabled = Common::isGoalPluginEnabled();
     $prettyDate = $processedReport['prettyDate'];
     $reportData = $processedReport['reportData'];
     $evolutionMetrics = array();
     $multiSitesAPIMetrics = API::getApiMetrics($enhanced = true);
     foreach ($multiSitesAPIMetrics as $metricSettings) {
         $evolutionMetrics[] = $metricSettings[API::METRIC_EVOLUTION_COL_NAME_KEY];
     }
     $floatRegex = self::FLOAT_REGEXP;
     // no decimal for all metrics to shorten SMS content (keeps the monetary sign for revenue metrics)
     $reportData->filter('ColumnCallbackReplace', array(array_merge(array_keys($multiSitesAPIMetrics), $evolutionMetrics), function ($value) use($floatRegex) {
         return preg_replace_callback($floatRegex, function ($matches) {
             return round($matches[0]);
         }, $value);
     }));
     // evolution metrics formatting :
     //  - remove monetary, percentage and white spaces to shorten SMS content
     //    (this is also needed to be able to test $value != 0 and see if there is an evolution at all in SMSReport.twig)
     //  - adds a plus sign
     $reportData->filter('ColumnCallbackReplace', array($evolutionMetrics, function ($value) use($floatRegex) {
         $matched = preg_match($floatRegex, $value, $matches);
         $formatted = $matched ? sprintf("%+d", $matches[0]) : $value;
         return \Piwik\NumberFormatter::getInstance()->formatPercentEvolution($formatted);
     }));
     $dataRows = $reportData->getRows();
     $reportMetadata = $processedReport['reportMetadata'];
     $reportRowsMetadata = $reportMetadata->getRows();
     $siteHasECommerce = array();
     foreach ($reportRowsMetadata as $rowMetadata) {
         $idSite = $rowMetadata->getColumn('idsite');
         $siteHasECommerce[$idSite] = Site::isEcommerceEnabledFor($idSite);
     }
     $view = new View('@MobileMessaging/SMSReport');
     $view->assign("isGoalPluginEnabled", $isGoalPluginEnabled);
     $view->assign("reportRows", $dataRows);
     $view->assign("reportRowsMetadata", $reportRowsMetadata);
     $view->assign("prettyDate", $prettyDate);
     $view->assign("siteHasECommerce", $siteHasECommerce);
     $view->assign("displaySiteName", $processedReport['metadata']['action'] == 'getAll');
     // segment
     $segment = $processedReport['segment'];
     $displaySegment = $segment != null;
     $view->assign("displaySegment", $displaySegment);
     if ($displaySegment) {
         $view->assign("segmentName", $segment['name']);
     }
     $this->rendering .= $view->render();
 }
Beispiel #4
0
 public function fetchIndexedPagesCount($domain)
 {
     $url = self::SEARCH_URL . urlencode($domain);
     try {
         $response = str_replace(' ', ' ', Http::sendHttpRequest($url, $timeout = 10, @$_SERVER['HTTP_USER_AGENT']));
         if (preg_match('#([0-9\\,]+) results#i', $response, $p)) {
             return NumberFormatter::getInstance()->formatNumber((int) str_replace(',', '', $p[1]));
         } else {
             return 0;
         }
     } catch (\Exception $e) {
         $this->logger->warning('Error while getting Google search SEO stats: {message}', array('message' => $e->getMessage()));
         return null;
     }
 }
Beispiel #5
0
 public function configureView(ViewDataTable $view)
 {
     if ($view->isViewDataTableId(Sparklines::ID)) {
         /** @var Sparklines $view */
         $view->requestConfig->apiMethodToRequestDataTable = 'API.get';
         $this->addSparklineColumns($view);
         $view->config->addTranslations($this->getSparklineTranslations());
         $numberFormatter = NumberFormatter::getInstance();
         $view->config->filters[] = function (DataTable $table) use($view, $numberFormatter) {
             $firstRow = $table->getFirstRow();
             if ($firstRow->getColumn('nb_pageviews') + $firstRow->getColumn('nb_downloads') + $firstRow->getColumn('nb_outlinks') == 0 && $firstRow->getColumn('nb_actions') > 0) {
                 $view->config->removeSparklineMetric(array('nb_downloads', 'nb_uniq_downloads'));
                 $view->config->removeSparklineMetric(array('nb_outlinks', 'nb_uniq_outlinks'));
                 $view->config->removeSparklineMetric(array('nb_pageviews', 'nb_uniq_pageviews'));
                 $view->config->removeSparklineMetric(array('nb_searches', 'nb_keywords'));
             } else {
                 $view->config->removeSparklineMetric(array('nb_actions'));
             }
             $nbUsers = $firstRow->getColumn('nb_users');
             if (!is_numeric($nbUsers) || 0 >= $nbUsers) {
                 $view->config->replaceSparklineMetric(array('nb_users'), '');
             }
             $avgGenerationTime = $firstRow->getColumn('avg_time_generation');
             if (false === $avgGenerationTime) {
                 // fix avgGenerationTime is not formatted if value is false
                 /** @var Formatter $formatter */
                 $formatter = StaticContainer::get('Piwik\\Metrics\\Formatter');
                 $avgGenerationTime = $formatter->getPrettyTimeFromSeconds($avgGenerationTime, true);
                 $firstRow->setColumn('avg_time_generation', $avgGenerationTime);
             }
             $numberMetrics = array('nb_visits', 'nb_uniq_visitors', 'nb_uniq_visitors', 'nb_users', 'nb_actions', 'nb_pageviews', 'nb_uniq_pageviews', 'nb_searches', 'nb_keywords', 'nb_downloads', 'nb_uniq_downloads', 'nb_outlinks', 'nb_uniq_outlinks', 'max_actions');
             foreach ($numberMetrics as $metric) {
                 $value = $firstRow->getColumn($metric);
                 if (false !== $value) {
                     $firstRow->setColumn($metric, $numberFormatter->formatNumber($value));
                 }
             }
             $value = $firstRow->getColumn('bounce_rate');
             if (false !== $value) {
                 $firstRow->setColumn('bounce_rate', $numberFormatter->formatPercent($value, $precision = 1));
             }
             $value = $firstRow->getColumn('nb_actions_per_visit');
             if (false !== $value) {
                 $firstRow->setColumn('nb_actions_per_visit', $numberFormatter->formatNumber($value, $maxFraction = 1));
             }
         };
     }
 }
Beispiel #6
0
 public function getMetrics($domain)
 {
     $url = self::URL . urlencode($domain);
     try {
         $response = str_replace(' ', ' ', Http::sendHttpRequest($url, $timeout = 10, @$_SERVER['HTTP_USER_AGENT']));
         if (preg_match('#([0-9,\\.]+) results#i', $response, $p)) {
             $pageCount = NumberFormatter::getInstance()->formatNumber((int) str_replace(array(',', '.'), '', $p[1]));
         } else {
             $pageCount = 0;
         }
     } catch (\Exception $e) {
         $this->logger->warning('Error while getting Bing SEO stats: {message}', array('message' => $e->getMessage()));
         $pageCount = null;
     }
     $logo = SearchEngine::getInstance()->getLogoFromUrl('http://bing.com');
     return array(new Metric('bing-index', 'SEO_Bing_IndexedPages', $pageCount, $logo, null, null, 'General_Pages'));
 }
Beispiel #7
0
 public function getMetrics($domain)
 {
     try {
         $response = Http::sendHttpRequest(self::URL . urlencode($domain), $timeout = 10, @$_SERVER['HTTP_USER_AGENT']);
         preg_match('#DMOZ Sites[^\\(]+\\([0-9]-[0-9]+ of ([0-9]+)\\)#', $response, $p);
         if (!empty($p[1])) {
             $value = NumberFormatter::getInstance()->formatNumber((int) $p[1]);
         } else {
             $value = 0;
         }
         // Add DMOZ only if > 0 entries found
         if ($value == 0) {
             return array();
         }
     } catch (\Exception $e) {
         $this->logger->warning('Error while getting Dmoz SEO stats: {message}', array('message' => $e->getMessage()));
         $value = null;
     }
     $logo = SearchEngine::getInstance()->getLogoFromUrl('http://dmoz.org');
     return array(new Metric('dmoz', 'SEO_Dmoz', $value, $logo));
 }
Beispiel #8
0
 private function formatMetrics(&$metrics)
 {
     $formatter = new NumberFormatter();
     foreach ($metrics as $metricName => &$value) {
         if (in_array($metricName, $this->displayedMetricColumns)) {
             if (strpos($metricName, 'revenue') !== false) {
                 continue;
             }
             $value = $formatter->format($value);
         }
     }
 }
Beispiel #9
0
 /**
  * Returns a prettified time value (in seconds).
  *
  * @param int $numberOfSeconds The number of seconds.
  * @param bool $displayTimeAsSentence If set to true, will output `"5min 17s"`, if false `"00:05:17"`.
  * @param bool $round Whether to round to the nearest second or not.
  * @return string
  * @api
  */
 public function getPrettyTimeFromSeconds($numberOfSeconds, $displayTimeAsSentence = false, $round = false)
 {
     $numberOfSeconds = $round ? (int) $numberOfSeconds : (double) $numberOfSeconds;
     $isNegative = false;
     if ($numberOfSeconds < 0) {
         $numberOfSeconds = -1 * $numberOfSeconds;
         $isNegative = true;
     }
     // Display 01:45:17 time format
     if ($displayTimeAsSentence === false) {
         $days = floor($numberOfSeconds / 86400);
         $hours = floor(($reminder = $numberOfSeconds - $days * 86400) / 3600);
         $minutes = floor(($reminder = $reminder - $hours * 3600) / 60);
         $seconds = floor($reminder - $minutes * 60);
         if ($days == 0) {
             $time = sprintf("%02s", $hours) . ':' . sprintf("%02s", $minutes) . ':' . sprintf("%02s", $seconds);
         } else {
             $time = sprintf(Piwik::translate('Intl_NDays'), $days) . " " . sprintf("%02s", $hours) . ':' . sprintf("%02s", $minutes) . ':' . sprintf("%02s", $seconds);
         }
         $centiSeconds = $numberOfSeconds * 100 % 100;
         if ($centiSeconds) {
             $time .= '.' . sprintf("%02s", $centiSeconds);
         }
         if ($isNegative) {
             $time = '-' . $time;
         }
         return $time;
     }
     $secondsInYear = 86400 * 365.25;
     $years = floor($numberOfSeconds / $secondsInYear);
     $minusYears = $numberOfSeconds - $years * $secondsInYear;
     $days = floor($minusYears / 86400);
     $minusDays = $numberOfSeconds - $days * 86400;
     $hours = floor($minusDays / 3600);
     $minusDaysAndHours = $minusDays - $hours * 3600;
     $minutes = floor($minusDaysAndHours / 60);
     $seconds = $minusDaysAndHours - $minutes * 60;
     $precision = $seconds > 0 && $seconds < 0.01 ? 3 : 2;
     $seconds = NumberFormatter::getInstance()->formatNumber(round($seconds, $precision), $precision);
     if ($years > 0) {
         $return = sprintf(Piwik::translate('General_YearsDays'), $years, $days);
     } elseif ($days > 0) {
         $return = sprintf(Piwik::translate('General_DaysHours'), $days, $hours);
     } elseif ($hours > 0) {
         $return = sprintf(Piwik::translate('General_HoursMinutes'), $hours, $minutes);
     } elseif ($minutes > 0) {
         $return = sprintf(Piwik::translate('General_MinutesSeconds'), $minutes, $seconds);
     } else {
         $return = sprintf(Piwik::translate('Intl_NSecondsShort'), $seconds);
     }
     if ($isNegative) {
         $return = '-' . $return;
     }
     return $return;
 }
Beispiel #10
0
 private function formatMetrics(&$metrics)
 {
     $formatter = NumberFormatter::getInstance();
     foreach ($metrics as $metricName => &$value) {
         if (in_array($metricName, $this->displayedMetricColumns)) {
             if (strpos($metricName, 'revenue') !== false) {
                 $currency = isset($metrics['idsite']) ? Site::getCurrencySymbolFor($metrics['idsite']) : '';
                 $value = $formatter->formatCurrency($value, $currency);
                 continue;
             }
             $value = $formatter->format($value);
         }
     }
 }
Beispiel #11
0
/**
 * Global format method
 *
 * required to format y axis values using pcharts internal format callbacks
 * @param $value
 * @return mixed
 */
function formatYAxis($value)
{
    return NumberFormatter::getInstance()->format($value);
}
Beispiel #12
0
 private function paintReportTable()
 {
     //Color and font restoration
     $this->TCPDF->SetFillColor($this->tableBackgroundColor[0], $this->tableBackgroundColor[1], $this->tableBackgroundColor[2]);
     $this->TCPDF->SetTextColor($this->reportTextColor[0], $this->reportTextColor[1], $this->reportTextColor[2]);
     $this->TCPDF->SetFont('');
     $fill = true;
     $url = false;
     $leftSpacesBeforeLogo = str_repeat(' ', $this->leftSpacesBeforeLogo);
     $logoWidth = $this->logoWidth;
     $logoHeight = $this->logoHeight;
     $rowsMetadata = $this->reportRowsMetadata->getRows();
     // Draw a body of report table
     foreach ($this->report->getRows() as $rowId => $row) {
         $rowMetrics = $row->getColumns();
         $rowMetadata = isset($rowsMetadata[$rowId]) ? $rowsMetadata[$rowId]->getColumns() : array();
         if (isset($rowMetadata['url'])) {
             $url = $rowMetadata['url'];
         }
         foreach ($this->reportColumns as $columnId => $columnName) {
             // Label column
             if ($columnId == 'label') {
                 $isLogoDisplayable = isset($rowMetadata['logo']);
                 $text = '';
                 $posX = $this->TCPDF->GetX();
                 $posY = $this->TCPDF->GetY();
                 if (isset($rowMetrics[$columnId])) {
                     $text = substr($rowMetrics[$columnId], 0, $this->truncateAfter);
                     if ($isLogoDisplayable) {
                         $text = $leftSpacesBeforeLogo . $text;
                     }
                 }
                 $text = $this->formatText($text);
                 $this->TCPDF->Cell($this->labelCellWidth, $this->cellHeight, $text, 'LR', 0, 'L', $fill, $url);
                 if ($isLogoDisplayable) {
                     if (isset($rowMetadata['logoWidth'])) {
                         $logoWidth = $rowMetadata['logoWidth'];
                     }
                     if (isset($rowMetadata['logoHeight'])) {
                         $logoHeight = $rowMetadata['logoHeight'];
                     }
                     $restoreY = $this->TCPDF->getY();
                     $restoreX = $this->TCPDF->getX();
                     $this->TCPDF->SetY($posY);
                     $this->TCPDF->SetX($posX);
                     $topMargin = 1.3;
                     // Country flags are not very high, force a bigger top margin
                     if ($logoHeight < 16) {
                         $topMargin = 2;
                     }
                     $path = Filesystem::getPathToPiwikRoot() . "/" . $rowMetadata['logo'];
                     if (file_exists($path)) {
                         $this->TCPDF->Image($path, $posX + ($leftMargin = 2), $posY + $topMargin, $logoWidth / 4);
                     }
                     $this->TCPDF->SetXY($restoreX, $restoreY);
                 }
             } else {
                 // No value means 0
                 if (empty($rowMetrics[$columnId])) {
                     $rowMetrics[$columnId] = 0;
                 }
                 $this->TCPDF->Cell($this->cellWidth, $this->cellHeight, NumberFormatter::getInstance()->format($rowMetrics[$columnId]), 'LR', 0, 'L', $fill);
             }
         }
         $this->TCPDF->Ln();
         // Top/Bottom grey border for all cells
         $this->TCPDF->SetDrawColor($this->rowTopBottomBorder[0], $this->rowTopBottomBorder[1], $this->rowTopBottomBorder[2]);
         $this->TCPDF->Cell($this->totalWidth, 0, '', 'T');
         $this->setBorderColor();
         $this->TCPDF->Ln(0.2);
         $fill = !$fill;
     }
 }
Beispiel #13
0
 /**
  * Utility method that calculates evolution values for a set of current & past values
  * and sets properties on a View w/ HTML that displays the evolution percents.
  *
  * @param string $date The date of the current values.
  * @param array $currentValues Array mapping view property names w/ present values.
  * @param string $lastPeriodDate The date of the period in the past.
  * @param array $previousValues Array mapping view property names w/ past values. Keys
  *                              in this array should be the same as keys in $currentValues.
  * @return array Added current values
  */
 private function addEvolutionPropertiesToView($date, $currentValues, $lastPeriodDate, $previousValues)
 {
     foreach ($previousValues as $name => $pastValue) {
         $currentValue = $currentValues[$name];
         $evolutionName = $name . 'Evolution';
         $currentValueFormatted = NumberFormatter::getInstance()->format($currentValue);
         $pastValueFormatted = NumberFormatter::getInstance()->format($pastValue);
         $currentValues[$evolutionName] = array('currentValue' => $currentValue, 'pastValue' => $pastValue, 'tooltip' => Piwik::translate('General_EvolutionSummaryGeneric', array(Piwik::translate('General_NVisits', $currentValueFormatted), $date, Piwik::translate('General_NVisits', $pastValueFormatted), $lastPeriodDate, CalculateEvolutionFilter::calculate($currentValue, $pastValue, $precision = 1))));
     }
     return $currentValues;
 }
Beispiel #14
0
 protected function addFilter_percentEvolution()
 {
     $percentage = new Twig_SimpleFilter('percentEvolution', function ($string) {
         $formatter = NumberFormatter::getInstance();
         return $formatter->formatPercentEvolution($string);
     });
     $this->twig->addFilter($percentage);
 }
Beispiel #15
0
 /**
  * @dataProvider getPercentNumberEvolutionFormattingTestData
  */
 public function testPercentEvolutionNumberFormatting($language, $value, $expected)
 {
     StaticContainer::get('Piwik\\Translation\\Translator')->setCurrentLanguage($language);
     $formatter = NumberFormatter::getInstance();
     $this->assertEquals($expected, $formatter->formatPercentEvolution($value));
 }
 /**
  * Prepare metrics toggles with spark lines
  * @return array
  */
 protected function getMetricsToggles()
 {
     $i = 0;
     $metrics = array();
     foreach ($this->availableMetrics as $metric => $metricData) {
         $unit = Metrics::getUnit($metric, $this->idSite);
         $change = isset($metricData['change']) ? $metricData['change'] : false;
         list($first, $last) = $this->getFirstAndLastDataPointsForMetric($metric);
         $details = Piwik::translate('RowEvolution_MetricBetweenText', array(NumberFormatter::getInstance()->format($first), NumberFormatter::getInstance()->format($last)));
         if ($change !== false) {
             $lowerIsBetter = Metrics::isLowerValueBetter($metric);
             if (substr($change, 0, 1) == '+') {
                 $changeClass = $lowerIsBetter ? 'bad' : 'good';
                 $changeImage = $lowerIsBetter ? 'arrow_up_red' : 'arrow_up';
             } else {
                 if (substr($change, 0, 1) == '-') {
                     $changeClass = $lowerIsBetter ? 'good' : 'bad';
                     $changeImage = $lowerIsBetter ? 'arrow_down_green' : 'arrow_down';
                 } else {
                     $changeClass = 'neutral';
                     $changeImage = false;
                 }
             }
             $change = '<span class="' . $changeClass . '">' . ($changeImage ? '<img src="plugins/MultiSites/images/' . $changeImage . '.png" /> ' : '') . $change . '</span>';
             $details .= ', ' . Piwik::translate('RowEvolution_MetricChangeText', $change);
         }
         // set metric min/max text (used as tooltip for details)
         $max = isset($metricData['max']) ? $metricData['max'] : 0;
         $min = isset($metricData['min']) ? $metricData['min'] : 0;
         $min .= $unit;
         $max .= $unit;
         $minmax = Piwik::translate('RowEvolution_MetricMinMax', array($metricData['name'], NumberFormatter::getInstance()->formatNumber($min), NumberFormatter::getInstance()->formatNumber($max)));
         $newMetric = array('label' => $metricData['name'], 'details' => $details, 'minmax' => $minmax, 'sparkline' => $this->getSparkline($metric));
         // Multi Rows, each metric can be for a particular row and display an icon
         if (!empty($metricData['logo'])) {
             $newMetric['logo'] = $metricData['logo'];
         }
         // TODO: this check should be determined by metric metadata, not hardcoded here
         if ($metric == 'nb_users' && $first == 0 && $last == 0) {
             $newMetric['hide'] = true;
         }
         $metrics[] = $newMetric;
         $i++;
     }
     return $metrics;
 }
Beispiel #17
0
 /**
  * Calculates the evolution from one value to another and returns HTML displaying
  * the evolution percent. The HTML includes an up/down arrow and is colored red, black or
  * green depending on whether the evolution is negative, 0 or positive.
  *
  * No HTML is returned if the current value and evolution percent are both 0.
  *
  * @param string $date The date of the current value.
  * @param int $currentValue The value to calculate evolution to.
  * @param string $pastDate The date of past value.
  * @param int $pastValue The value in the past to calculate evolution from.
  * @return string|false The HTML or `false` if the evolution is 0 and the current value is 0.
  * @api
  */
 protected function getEvolutionHtml($date, $currentValue, $pastDate, $pastValue)
 {
     $evolutionPercent = CalculateEvolutionFilter::calculate($currentValue, $pastValue, $precision = 1);
     // do not display evolution if evolution percent is 0 and current value is 0
     if ($evolutionPercent == 0 && $currentValue == 0) {
         return false;
     }
     $titleEvolutionPercent = $evolutionPercent;
     if ($evolutionPercent < 0) {
         $class = "negative-evolution";
         $img = "arrow_down.png";
     } elseif ($evolutionPercent == 0) {
         $class = "neutral-evolution";
         $img = "stop.png";
     } else {
         $class = "positive-evolution";
         $img = "arrow_up.png";
         $titleEvolutionPercent = '+' . $titleEvolutionPercent;
     }
     $currentValue = NumberFormatter::getInstance()->format($currentValue);
     $pastValue = NumberFormatter::getInstance()->format($pastValue);
     $title = Piwik::translate('General_EvolutionSummaryGeneric', array(Piwik::translate('General_NVisits', $currentValue), $date, Piwik::translate('General_NVisits', $pastValue), $pastDate, $titleEvolutionPercent));
     $result = '<span class="metricEvolution" title="' . $title . '"><img style="padding-right:4px" src="plugins/MultiSites/images/' . $img . '"/><strong';
     if (isset($class)) {
         $result .= ' class="' . $class . '"';
     }
     $result .= '>' . $evolutionPercent . '</strong></span>';
     return $result;
 }
 /**
  * @dataProvider getPercentNumberEvolutionFormattingTestData
  */
 public function testPercentEvolutionNumberFormatting($language, $value, $expected)
 {
     $this->translator->setCurrentLanguage($language);
     $numberFormatter = new NumberFormatter($this->translator);
     $this->assertEquals($expected, $numberFormatter->formatPercentEvolution($value));
 }
Beispiel #19
0
 protected function addFilter_money()
 {
     $formatter = $this->formatter;
     $moneyFilter = new Twig_SimpleFilter('money', function ($amount) use($formatter) {
         if (func_num_args() != 2) {
             throw new Exception('the money modifier expects one parameter: the idSite.');
         }
         $idSite = func_get_args();
         $idSite = $idSite[1];
         $currencySymbol = Site::getCurrencySymbolFor($idSite);
         return NumberFormatter::getInstance()->formatCurrency($amount, $currencySymbol, GoalManager::REVENUE_PRECISION);
     });
     $this->twig->addFilter($moneyFilter);
 }
Beispiel #20
0
 public function configureView(ViewDataTable $view)
 {
     $idGoal = Common::getRequestVar('idGoal', 0, 'string');
     $idSite = $this->getIdSite();
     if ($view->isViewDataTableId(Sparklines::ID)) {
         /** @var Sparklines $view */
         $isEcommerceEnabled = $this->isEcommerceEnabled($idSite);
         $onlySummary = Common::getRequestVar('only_summary', 0, 'int');
         if ($onlySummary && !empty($idGoal)) {
             if (is_numeric($idGoal)) {
                 $view->config->title_attributes = array('piwik-goal-page-link' => $idGoal);
             }
             // in Goals overview summary we show proper title for a goal
             $goal = $this->getGoal($idGoal);
             if (!empty($goal['name'])) {
                 $view->config->title = Piwik::translate('Goals_GoalX', "'" . $goal['name'] . "'");
             }
         } else {
             $view->config->title = '';
         }
         $numberFormatter = NumberFormatter::getInstance();
         $view->config->filters[] = function (DataTable $table) use($numberFormatter, $idSite) {
             $firstRow = $table->getFirstRow();
             if ($firstRow) {
                 $revenue = $firstRow->getColumn('revenue');
                 $currencySymbol = Site::getCurrencySymbolFor($idSite);
                 $revenue = $numberFormatter->formatCurrency($revenue, $currencySymbol, GoalManager::REVENUE_PRECISION);
                 $firstRow->setColumn('revenue', $revenue);
                 $conversionRate = $firstRow->getColumn('conversion_rate');
                 if (false !== $conversionRate) {
                     $firstRow->setColumn('conversion_rate', $numberFormatter->formatPercent($conversionRate, $precision = 1));
                 }
                 $conversions = $firstRow->getColumn('nb_conversions');
                 if (false !== $conversions) {
                     $firstRow->setColumn('nb_conversions', $numberFormatter->formatNumber($conversions));
                 }
                 $visitsConverted = $firstRow->getColumn('nb_visits_converted');
                 if (false !== $visitsConverted) {
                     $firstRow->setColumn('nb_visits_converted', $numberFormatter->formatNumber($visitsConverted));
                 }
             }
         };
         $view->config->addTranslations(array('nb_visits' => Piwik::translate('VisitsSummary_NbVisitsDescription'), 'nb_conversions' => Piwik::translate('Goals_ConversionsDescription'), 'nb_visits_converted' => Piwik::translate('General_NVisits'), 'conversion_rate' => Piwik::translate('Goals_OverallConversionRate'), 'revenue' => Piwik::translate('Goals_OverallRevenue')));
         $allowMultiple = Common::getRequestVar('allow_multiple', 0, 'int');
         if ($allowMultiple) {
             $view->config->addSparklineMetric(array('nb_conversions', 'nb_visits_converted'), $order = 10);
         } else {
             $view->config->addSparklineMetric(array('nb_conversions'), $order = 10);
         }
         $view->config->addSparklineMetric(array('conversion_rate'), $order = 20);
         if (empty($idGoal)) {
             // goals overview sparklines below evolution graph
             if ($isEcommerceEnabled) {
                 // this would be ideally done in Ecommerce plugin but then it is hard to keep same order
                 $view->config->addSparklineMetric(array('revenue'), $order = 30);
             }
         } else {
             if ($onlySummary) {
                 // in Goals Overview we list an overview for each goal....
                 $view->config->addTranslation('conversion_rate', Piwik::translate('Goals_ConversionRate'));
             } elseif ($isEcommerceEnabled) {
                 // in Goals detail page...
                 $view->config->addSparklineMetric(array('revenue'), $order = 30);
             }
         }
     } else {
         if ($view->isViewDataTableId(Evolution::ID)) {
             if (!empty($idSite) && Piwik::isUserHasAdminAccess($idSite)) {
                 $view->config->title_edit_entity_url = 'index.php' . Url::getCurrentQueryStringWithParametersModified(array('module' => 'Goals', 'action' => 'manage', 'forceView' => null, 'viewDataTable' => null, 'showtitle' => null, 'random' => null));
             }
             $goal = $this->getGoal($idGoal);
             if (!empty($goal['name'])) {
                 $view->config->title = Piwik::translate('Goals_GoalX', "'" . $goal['name'] . "'");
                 if (!empty($goal['description'])) {
                     $view->config->description = $goal['description'];
                 }
             } else {
                 $view->config->title = Piwik::translate('General_EvolutionOverPeriod');
             }
             if (empty($view->config->columns_to_display)) {
                 $view->config->columns_to_display = array('nb_conversions');
             }
         }
     }
 }
 /**
  * Calculates the evolution percentage for two arbitrary values.
  *
  * @param float|int $currentValue The current metric value.
  * @param float|int $pastValue The value of the metric in the past. We measure the % change
  *                                      from this value to $currentValue.
  * @param float|int $quotientPrecision The quotient precision to round to.
  * @param bool $appendPercentSign Whether to append a '%' sign to the end of the number or not.
  *
  * @return string The evolution percent, eg `'15%'`.
  */
 public static function calculate($currentValue, $pastValue, $quotientPrecision = 0, $appendPercentSign = true)
 {
     $number = self::getPercentageValue($currentValue - $pastValue, $pastValue, $quotientPrecision);
     if ($appendPercentSign) {
         return NumberFormatter::getInstance()->formatPercent($number, $quotientPrecision);
     }
     return NumberFormatter::getInstance()->format($number, $quotientPrecision);
 }