Welcome to mirror list, hosted at ThFree Co, Russian Federation.

API.php « API « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f6a0541ca881e658882f5ae017fc7e9565b26626 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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
356
357
358
359
360
361
362
363
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<?php

/**
 * Piwik - Open source web analytics
 * 
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 * @version $Id$
 * 
 * @category Piwik_Plugins
 * @package Piwik_API
 */

/**
 * 
 * @package Piwik_API
 */
class Piwik_API extends Piwik_Plugin {

	public function getInformation() {
		return array(
			'description' => Piwik_Translate('API_PluginDescription'),
			'author' => 'Piwik',
			'author_homepage' => 'http://piwik.org/',
			'version' => Piwik_Version::VERSION,
		);
	}
	
	public function getListHooksRegistered() {
		return array(
			'AssetManager.getCssFiles' => 'getCssFiles',
			'TopMenu.add' => 'addTopMenu',
		);
	}
	
	public function addTopMenu() {
		Piwik_AddTopMenu('General_API', array('module' => 'API', 'action' => 'listAllAPI'), true, 7);
	}

	public function getCssFiles($notification) {
		$cssFiles = &$notification->getNotificationObject();
		
		$cssFiles[] = "plugins/API/css/styles.css";
	}
}


/**
 * 
 * @package Piwik_API
 */
class Piwik_API_API 
{
	static private $instance = null;

	/**
	 * @return Piwik_API_API
	 */
	static public function getInstance()
	{
		if (self::$instance == null)
		{
			self::$instance = new self;
		}
		return self::$instance;
	}

	public function getDefaultMetrics() 
	{
		$translations = array(
			// Standard metrics
    		'nb_visits' => 'General_ColumnNbVisits',
    		'nb_uniq_visitors' => 'General_ColumnNbUniqVisitors',
    		'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(
			// Processed in AddColumnsProcessedMetrics
			'nb_actions_per_visit' => 'General_ColumnActionsPerVisit',
    		'avg_time_on_site' => 'General_ColumnAvgTimeOnSite',
    		'bounce_rate' => 'General_ColumnBounceRate',
    		'conversion_rate' => 'General_ColumnConversionRate',
		);
		return array_map('Piwik_Translate', $translations);
	}
	
    /*
     * Loads reports metadata, then return the requested one, 
     * matching optional API parameters.
     */
	public function getMetadata($idSite, $apiModule, $apiAction, $apiParameters = array(), $language = false)
    {
    	Piwik_Translate::getInstance()->reloadLanguage($language);
    	static $reportsMetadata = array();
    	$cacheKey = $idSite.$language;
    	if(!isset($reportsMetadata[$cacheKey]))
    	{
    		$reportsMetadata[$cacheKey] = $this->getReportMetadata($idSite);
    	}
    	
    	foreach($reportsMetadata[$cacheKey] 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;
    }
    
	/**
	 * Triggers a hook to ask plugins for available Reports.
	 * Returns metadata information about each report (category, name, dimension, metrics, etc.) 
	 *
	 * @param string $idSites Comma separated list of website Ids
	 * @return array
	 */
	public function getReportMetadata($idSites = array()) 
	{
		if (!is_array($idSites)) 
		{ 
            $idSites = array($idSites); 
		}
		 
		$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)
		{
			// Ensure all metrics have a translation
			$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'));
		return $availableReports;
	}

	public function getProcessedReport($idSite, $date, $period, $apiModule, $apiAction, $apiParameters = false, $language = false)
    {
    	if($apiParameters === false)
    	{
    		$apiParameters = array();
    	}
        // Is this report found in the Metadata available reports?
        $reportMetadata = $this->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language);
        if(empty($reportMetadata))
        {
        	throw new Exception("Requested report $apiModule.$apiAction for Website id=$idSite not found in the list of available reports. \n");
        }
        $reportMetadata = reset($reportMetadata);
        
		// Generate Api call URL passing custom parameters
		$parameters = array_merge( $apiParameters, array(
			'method' => $apiModule.'.'.$apiAction,
			'idSite' => $idSite,
			'period' => $period,
			'date' => $date,
			'format' => 'original',
			'serialize' => '0',
			'language' => $language,
		));
		$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']
    	);
    	
		// See ArchiveProcessing/Period.php - unique visitors are not processed for year period
    	if($period == 'year')
    	{
    		unset($columns['nb_uniq_visitors']);
    		unset($reportMetadata['metrics']['nb_uniq_visitors']);
    	}
    	
        if(isset($reportMetadata['processedMetrics']))
        {
        	$processedMetricsAdded = $this->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');
        	
    		// Add processed metrics to be displayed for this report
        	foreach($metricsGoalDisplay as $goalMetricId)
        	{
        		if(isset($reportMetadata['metricsGoal'][$goalMetricId]))
        		{
        			$columns[$goalMetricId] = $reportMetadata['metricsGoal'][$goalMetricId];
        		}
        	}
        }
        if(isset($reportMetadata['metricsGoal']))
        {
        	// To process conversion_rate, we need to apply the Goal processed filter
        	// only requesting to process the basic metrics
        	// This adds goal metrics as well as standard metrics
        	$dataTable->filter('AddColumnsProcessedMetricsGoal', array($enable=true, Piwik_DataTable_Filter_AddColumnsProcessedMetricsGoal::GOALS_MINIMAL_REPORT));
        }
        elseif(isset($reportMetadata['processedMetrics']))
        {
        	// Add processed metrics
        	$dataTable->filter('AddColumnsProcessedMetrics');
        }
        $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;
    			}
    		}
    		$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']);
	}
}