Newer
Older
mattpiwik
a validé
/**
* Piwik - Open source web analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html Gpl v3 or later
mattpiwik
a validé
class Piwik_API extends Piwik_Plugin {
public function getInformation() {
'description' => Piwik_Translate('API_PluginDescription'),
'homepage' => 'misc/redirectToUrl.php?url=http://dev.piwik.org/trac/wiki/API/Reference',
'author_homepage' => 'http://piwik.org/',
'version' => Piwik_Version::VERSION,
return array(
mattpiwik
a validé
'AssetManager.getCssFiles' => 'getCssFiles',
'TopMenu.add' => 'addTopMenu',
);
}
mattpiwik
a validé
public function addTopMenu() {
Piwik_AddTopMenu('General_API', array('module' => 'API', 'action' => 'listAllAPI'), true, 7);
}
$cssFiles = &$notification->getNotificationObject();
$cssFiles[] = "plugins/API/templates/styles.css";
}
mattpiwik
a validé
static private $instance = null;
/**
* @return Piwik_API_API
*/
static public function getInstance()
{
if (self::$instance == null)
{
$c = __CLASS__;
self::$instance = new $c();
}
return self::$instance;
}
public function getDefaultMetrics()
{
$translations = array(
// Standard metrics
'nb_uniq_visitors' => 'General_ColumnNbUniqVisitors',
'nb_visits' => 'General_ColumnNbVisits',
'nb_actions' => 'General_ColumnNbActions',
// Do not display these in reports, as they are not so relevant
// They are used to process metrics below
// 'nb_visits_converted' => 'General_ColumnVisitsWithConversions',
// 'max_actions' => 'General_ColumnMaxActions',
// 'sum_visit_length' => 'General_ColumnSumVisitLength',
// 'bounce_count'
);
$translations = array_map('Piwik_Translate', $translations);
return $translations;
}
public function getDefaultProcessedMetrics()
{
$translations = array(
'nb_actions_per_visit' => 'General_ColumnActionsPerVisit',
'avg_time_on_site' => 'General_ColumnAvgTimeOnSite',
'bounce_rate' => 'General_ColumnBounceRate',
);
return array_map('Piwik_Translate', $translations);
}
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/*
* Loads reports metadata, then return the requested one (possibly matching parameters, if passed)
*/
public function getMetadata($idSite, $apiModule, $apiAction, $apiParameters = array())
{
static $reportsMetadata = array();
if(!isset($reportsMetadata[$idSite]))
{
$reportsMetadata[$idSite] = Piwik_API_API::getInstance()->getReportMetadata($idSite);
}
foreach($reportsMetadata[$idSite] as $report)
{
if($report['module'] == $apiModule
&& $report['action'] == $apiAction)
{
if(empty($apiParameters))
{
return array($report);
}
if(empty($report['parameters']))
{
continue;
}
$diff = array_diff($report['parameters'], $apiParameters);
if(empty($diff))
{
return array($report);
}
}
}
return false;
}
* Returns metadata information about each report (category, name, dimension, metrics, etc.)
public function getReportMetadata($idSites = false)
{
$idSites = Piwik_Site::getIdSitesFromIdSitesString($idSites);
$availableReports = array();
Piwik_PostEvent('API.getReportMetadata', $availableReports, $idSites);
foreach ($availableReports as &$availableReport) {
if (!isset($availableReport['metrics'])) {
$availableReport['metrics'] = $this->getDefaultMetrics();
}
if (!isset($availableReport['processedMetrics'])) {
$availableReport['processedMetrics'] = $this->getDefaultProcessedMetrics();
}
}
// Some plugins need to add custom metrics after all plugins hooked in
Piwik_PostEvent('API.getReportMetadata.end', $availableReports, $idSites);
$knownMetrics = array_merge( $this->getDefaultMetrics(), $this->getDefaultProcessedMetrics() );
foreach($availableReports as &$availableReport)
{
$metrics = $availableReport['metrics'];
$cleanedMetrics = array();
foreach($metrics as $metricId => $metricTranslation)
{
// When simply the column name was given, ie 'metric' => array( 'nb_visits' )
// $metricTranslation is in this case nb_visits. We look for a known translation.
if(is_numeric($metricId)
&& isset($knownMetrics[$metricTranslation]))
{
$metricId = $metricTranslation;
$metricTranslation = $knownMetrics[$metricTranslation];
}
$cleanedMetrics[$metricId] = $metricTranslation;
}
$availableReport['metrics'] = $cleanedMetrics;
// Remove array elements that are false (to clean up API output)
foreach($availableReport as $attributeName => $attributeValue)
{
if(empty($attributeValue))
{
unset($availableReport[$attributeName]);
}
}
// Processing a uniqueId for each report,
// can be used by UIs as a key to match a given report
$uniqueId = $availableReport['module'] . '_' . $availableReport['action'];
if(!empty($availableReport['parameters']))
{
foreach($availableReport['parameters'] as $key => $value)
{
$uniqueId .= '_' . $key . '--' . $value;
}
}
$availableReport['uniqueId'] = $uniqueId;
// Sort results to ensure consistent order
usort($availableReports, array($this, "sort"));
public function getProcessedReport($idSite, $date, $period, $apiModule, $apiAction, $apiParameters = false)
{
if($apiParameters === false)
{
$apiParameters = array();
}
// Is this report found in the Metadata available reports?
$reportMetadata = $this->getMetadata($idSite, $apiModule, $apiAction, $apiParameters);
if(empty($reportMetadata))
{
throw new Exception("Requested report not found in the list of available reports. \n");
}
$reportMetadata = reset($reportMetadata);
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Generate Api call URL passing custom parameters
$parameters = array_merge( $apiParameters, array(
'method' => $apiModule.'.'.$apiAction,
'idSite' => $idSite,
'period' => $period,
'date' => $date,
'format' => 'original',
));
$url = Piwik_Url::getQueryStringFromParameters($parameters);
$request = new Piwik_API_Request($url);
try {
/** @var Piwik_DataTable */
$dataTable = $request->process();
} catch(Exception $e) {
throw new Exception("API returned an error: ".$e->getMessage()."\n");
}
// Table with a Dimension (Keywords, Pages, Browsers, etc.)
if(isset($reportMetadata['dimension']))
{
$callback = 'handleTableReport';
}
// Table without a dimension, simple list of general metrics (eg. VisitsSummary.get)
else
{
$callback = 'handleTableSimple';
}
list($newReport, $columns, $rowsMetadata) = $this->$callback($idSite, $period, $dataTable, $reportMetadata);
foreach($columns as $columnId => &$name)
{
$name = ucfirst($name);
}
$website = new Piwik_Site($idSite);
return array(
'website' => $website->getName(),
'prettyDate' => Piwik_Period::factory($period, Piwik_Date::factory($date))->getLocalizedLongString(),
'metadata' => $reportMetadata,
'columns' => $columns,
'reportData' => $newReport,
'reportMetadata' => $rowsMetadata,
);
}
private function handleTableSimple($idSite, $period, $dataTable, $reportMetadata)
{
$renderer = new Piwik_DataTable_Renderer_Php();
$renderer->setTable($dataTable);
$renderer->setSerialize(false);
$reportTable = $renderer->render();
$newReport = array();
foreach($reportTable as $metric => $value)
{
// Use translated metric from metadata
// If translation not found, do not display the returned data
if(isset($reportMetadata['metrics'][$metric]))
{
$value = Piwik::getPrettyValue($idSite, $metric, $value, $htmlAllowed = false, $timeAsSentence = false);
$metric = $reportMetadata['metrics'][$metric];
$newReport[] = array(
'label' => $metric,
'value' => $value
);
}
}
$columns = array(
'label' => Piwik_Translate('General_Name'),
'value' => Piwik_Translate('General_Value'),
);
return array(
$newReport,
$columns,
$rowsMetadata = array()
);
}
private function handleTableReport($idSite, $period, $dataTable, $reportMetadata)
{
// displayed columns
$columns = array_merge(
array('label' => $reportMetadata['dimension'] ),
$reportMetadata['metrics']
);
if($period != 'day')
{
unset($columns['nb_uniq_visitors']);
}
if(isset($reportMetadata['processedMetrics']))
{
// Add processed metrics
$dataTable->filter('AddColumnsProcessedMetrics');
$processedMetricsAdded = Piwik_API_API::getInstance()->getDefaultProcessedMetrics();
foreach($processedMetricsAdded as $processedMetricId => $processedMetricTranslation)
{
// this processed metric can be displayed for this report
if(isset($reportMetadata['processedMetrics'][$processedMetricId]))
{
$columns[$processedMetricId] = $processedMetricTranslation;
}
}
}
// Display the global Goal metrics
if(isset($reportMetadata['metricsGoal']))
{
$metricsGoalDisplay = array('conversion_rate', 'revenue');
// to have conversion_rate, we need to apply the Goal processed filter
// only requesting to process the basic metrics
$dataTable->filter('AddColumnsProcessedMetricsGoal', array($enable=true, Piwik_DataTable_Filter_AddColumnsProcessedMetricsGoal::GOALS_MINIMAL_REPORT));
// Add processed metrics to be displayed for this report
foreach($metricsGoalDisplay as $goalMetricId)
{
if(isset($reportMetadata['metricsGoal'][$goalMetricId]))
{
$columns[$goalMetricId] = $reportMetadata['metricsGoal'][$goalMetricId];
}
}
}
$dataTable->filter('SafeDecodeLabel', array($outputHTML = false));
$renderer = new Piwik_DataTable_Renderer_Php();
$renderer->setTable($dataTable);
$renderer->setSerialize(false);
$reportTable = $renderer->render();
$rowsMetadata = array();
$newReport = array();
foreach($reportTable as $rowId => $row)
{
// ensure all displayed columns have 0 values
foreach($columns as $id => $name)
{
if(!isset($row[$id]))
{
$row[$id] = 0;
}
}
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
$newRow = array();
foreach($row as $columnId => $value)
{
// Keep displayed columns
if(isset($columns[$columnId]))
{
$newRow[$columnId] = Piwik::getPrettyValue($idSite, $columnId, $value, $htmlAllowed = false, $timeAsSentence = false);
}
// We try and only keep metadata
// - if the column value is not an array (eg. metrics per goal)
// - if the column name doesn't contain _ (which is by standard, a metric column)
elseif(!is_array($value)
&& strpos($columnId, '_') === false
)
{
$rowsMetadata[$rowId][$columnId] = $value;
}
}
$newReport[] = $newRow;
}
return array(
$newReport,
$columns,
$rowsMetadata
);
}
/**
* API metadata are sorted by category/name
* @param $a
* @param $b
* @return int
*/
private function sort($a, $b)
{
return ($category = strcmp($a['category'], $b['category'])) != 0
? $category
: strcmp($a['action'], $b['action']);
}