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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
|
<?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: Proxy.php 581 2008-07-27 23:07:52Z matt $
*
* @package Piwik_API
*/
/**
* The API Proxy receives all the API calls requests and forwards them to the given module.
*
* It registers all the APIable plugins (@see Piwik_Apiable)
* The class checks that a call to the API has the correct number of parameters.
* The proxy is a singleton that has the knowledge of every method available, their parameters and default values.
*
* It can also log the performances of the API calls (time spent, parameter values, etc.)
*
* @package Piwik_API
*/
class Piwik_API_Proxy
{
static $classCalled = null;
// array of already registered plugins names
protected $alreadyRegistered = array();
private $api = array();
// when a parameter doesn't have a default value we use this constant
const NO_DEFAULT_VALUE = null;
static private $instance = null;
protected function __construct()
{}
/**
* Singleton, returns instance
*
* @return Piwik_API_Proxy
*/
static public function getInstance()
{
if (self::$instance == null)
{
$c = __CLASS__;
self::$instance = new $c();
}
return self::$instance;
}
/**
* Registers the API information of a given module.
*
* The module to be registered must be
* - extending the Piwik_Apiable class
* - a singleton (providing a getInstance() method)
* - the API file must be located in plugins/ModuleName/API.php
* for example plugins/Referers/API.php
*
* The method will introspect the methods, their parameters, etc.
*
* @param string ModuleName eg. "UserSettings"
*/
public function registerClass( $moduleName )
{
if(isset($this->alreadyRegistered[$moduleName]))
{
return;
}
$this->includeApiFile($moduleName);
$class = $this->getClassNameFromModule($moduleName);
$rClass = new ReflectionClass($class);
if(!$rClass->isSubclassOf(new ReflectionClass("Piwik_Apiable")))
{
throw new Exception("To publish its public methods in the API, the class '$class' must be a subclass of 'Piwik_Apiable'.");
}
$this->checkClassIsSingleton($class);
foreach($rClass->getMethods() as $method)
{
$this->loadMethodMetadata($class, $method);
}
$this->alreadyRegistered[$moduleName] = true;
}
/**
* Checks that the method exists in the class
*
* @param string The class name
* @param string The method name
* @throws exception If the method is not found
*/
public function checkMethodExists($className, $methodName)
{
if(!$this->isMethodAvailable($className, $methodName))
{
throw new Exception("The method '$methodName' does not exist or is not available in the module '".$className."'.");
}
}
/**
* Magic method used to set a flag telling the module named currently being called
*
*/
public function __get($name)
{
self::$classCalled = $name;
return $this;
}
/**
* Method always called when making an API request.
* It checks several things before actually calling the real method on the given module.
*
* It also logs the API calls, with the parameters values, the returned value, the performance, etc.
* You can enable logging in config/global.ini.php (log_api_call)
*
* @param string The method name
* @param array The parameters
*
* @throws Piwik_Access_NoAccessException
*/
public function __call($methodName, $parameterValues )
{
$returnedValue = null;
try {
$this->registerClass(self::$classCalled);
$className = $this->getClassNameFromModule(self::$classCalled);
// instanciate the object
$object = call_user_func(array($className, "getInstance"));
// check method exists
$this->checkMethodExists($className, $methodName);
// all parameters to the function call must be non null
$this->checkParametersAreNotNull($className, $methodName, $parameterValues);
// start the timer
$timer = new Piwik_Timer;
// call the method
$returnedValue = call_user_func_array(array($object, $methodName), $parameterValues);
// log the API Call
$parameterNamesDefaultValues = $this->getParametersList($className, $methodName);
Zend_Registry::get('logger_api_call')->log(
self::$classCalled,
$methodName,
$parameterNamesDefaultValues,
$parameterValues,
$timer->getTimeMs(),
$returnedValue
);
}
catch( Piwik_Access_NoAccessException $e) {
throw $e;
}
self::$classCalled = null;
return $returnedValue;
}
protected function includeApiFile($fileName)
{
$potentialPaths = array( "plugins/". $fileName ."/API.php", );
$found = false;
foreach($potentialPaths as $path)
{
if(Zend_Loader::isReadable($path))
{
require_once $path;
$found = true;
break;
}
}
if(!$found)
{
throw new Exception("API module $fileName not found.");
}
}
protected function loadMethodMetadata($class, $method)
{
// use this trick to read the static attribute of the class
// $class::$methodsNotToPublish doesn't work
$variablesClass = get_class_vars($class);
$variablesClass['methodsNotToPublish'][] = 'getInstance';
if($method->isPublic()
&& !$method->isConstructor()
&& !in_array($method->getName(), $variablesClass['methodsNotToPublish'] )
)
{
$name = $method->getName();
$parameters = $method->getParameters();
$aParameters = array();
foreach($parameters as $parameter)
{
$nameVariable = $parameter->getName();
$defaultValue = Piwik_API_Proxy::NO_DEFAULT_VALUE;
if($parameter->isDefaultValueAvailable())
{
$defaultValue = $parameter->getDefaultValue();
}
$aParameters[$nameVariable] = $defaultValue;
}
$this->api[$class][$name]['parameters'] = $aParameters;
$this->api[$class][$name]['numberOfRequiredParameters'] = $method->getNumberOfRequiredParameters();
}
}
/**
* Returns the 'moduleName' part of 'Piwik_moduleName_API' classname
*
* @param string moduleName
* @return string className
*/
protected function getModuleNameFromClassName( $className )
{
$start = strpos($className, '_') + 1;
return substr($className, $start , strrpos($className, '_') - $start);
}
/**
* Returns a string containing links to examples on how to call a given method on a given API
* It will export links to XML, CSV, HTML, JSON, PHP, etc.
* It will not export links for methods such as deleteSite or deleteUser
*
* @param string the class
* @param methodName the method
* @return string|false when not possible
*/
public function getExampleUrl($class, $methodName, $parametersToSet = array())
{
$knowExampleDefaultParametersValues = array(
'access' => 'view',
'userLogin' => 'test',
'password' => 'passwordExample',
'passwordMd5ied' => 'passwordExample',
'email' => 'test@example.org',
'siteName' => 'new example website',
'urls' => 'http://example.org', // used in addSite, updateSite
'languageCode' => 'fr',
);
foreach($parametersToSet as $name => $value)
{
$knowExampleDefaultParametersValues[$name] = $value;
}
// no links for these method names
$doNotPrintExampleForTheseMethods = array(
'deleteSite',
'deleteUser',
);
if(in_array($methodName,$doNotPrintExampleForTheseMethods))
{
return false;
}
// we try to give an URL example to call the API
$aParameters = $this->getParametersList($class, $methodName);
$moduleName = $this->getModuleNameFromClassName($class);
$urlExample = '?module=API&method='.$moduleName.'.'.$methodName.'&';
foreach($aParameters as $nameVariable=> $defaultValue)
{
// if there isn't a default value for a given parameter,
// we need a 'know default value' or we can't generate the link
if($defaultValue === Piwik_API_Proxy::NO_DEFAULT_VALUE)
{
if(isset($knowExampleDefaultParametersValues[$nameVariable]))
{
$exampleValue = $knowExampleDefaultParametersValues[$nameVariable];
$urlExample .= $nameVariable . '=' . $exampleValue . '&';
}
else
{
return false;
}
}
}
return substr($urlExample,0,-1);
}
/**
* Returns a HTML page containing help for all the successfully loaded APIs.
* For each module it will return a mini help with the method names, parameters to give,
* links to get the result in Xml/Csv/etc
*
* @return string
*/
public function getAllInterfaceString( $outputExampleUrls = true, $prefixUrls = '' )
{
$str = '';
$token_auth = "&token_auth=" . Piwik::getCurrentUserTokenAuth();
$parametersToSet = array(
'idSite' => Piwik_Common::getRequestVar('idSite', 1, 'int'),
'period' => Piwik_Common::getRequestVar('period', 'day', 'string'),
'date' => Piwik_Common::getRequestVar('date', 'today', 'string')
);
foreach($this->api as $class => $info)
{
$moduleName = $this->getModuleNameFromClassName($class);
$str .= "\n<h2 id='$moduleName'>Module ".$moduleName."</h2>";
foreach($info as $methodName => $infoMethod)
{
$params = $this->getStrListParameters($class, $methodName);
$str .= "\n" . "- <b>$moduleName.$methodName " . $params . "</b>";
$str .= '<small>';
if($outputExampleUrls)
{
// we prefix all URLs with $prefixUrls
// used when we include this output in the Piwik official documentation for example
$str .= "<span class=\"example\">";
$exampleUrl = $this->getExampleUrl($class, $methodName, $parametersToSet);
if($exampleUrl !== false)
{
$lastNUrls = '';
if( ereg('(&period)|(&date)',$exampleUrl))
{
$exampleUrlRss1 = $prefixUrls . $this->getExampleUrl($class, $methodName, $parametersToSet + array('date' => 'last10')) ;
$exampleUrlRss2 = $prefixUrls . $this->getExampleUrl($class, $methodName, $parametersToSet + array('date' => 'last5','period' => 'week',));
$lastNUrls = ", RSS of the last <a target=_blank href='$exampleUrlRss1&format=rss$token_auth'>10 days</a>, <a target=_blank href='$exampleUrlRss2&format=Rss'>5 weeks</a>,
XML of the <a target=_blank href='$exampleUrlRss1&format=xml$token_auth'>last 10 days</a>";
}
$exampleUrl = $prefixUrls . $exampleUrl ;
$str .= " [ Example in
<a target=_blank href='$exampleUrl&format=xml$token_auth'>XML</a>,
<a target=_blank href='$exampleUrl&format=PHP&prettyDisplay=true$token_auth'>PHP</a>,
<a target=_blank href='$exampleUrl&format=JSON$token_auth'>Json</a>,
<a target=_blank href='$exampleUrl&format=Csv$token_auth'>Csv</a>,
<a target=_blank href='$exampleUrl&format=Html$token_auth'>Basic html</a>
$lastNUrls
]";
}
else
{
$str .= " [ No example available ]";
}
$str .= "</span>";
}
$str .= '</small>';
$str .= "\n<br>";
}
}
return $str;
}
/**
* Returns the methods $class.$name parameters (and default value if provided) as a string.
*
* @param string The class name
* @param string The method name
* @return string For example "(idSite, period, date = 'today')"
*/
private function getStrListParameters($class, $name)
{
$aParameters = $this->getParametersList($class, $name);
$asParameters = array();
foreach($aParameters as $nameVariable=> $defaultValue)
{
$str = $nameVariable;
if($defaultValue !== Piwik_API_Proxy::NO_DEFAULT_VALUE)
{
$str .= " = '$defaultValue'";
}
$asParameters[] = $str;
}
$sParameters = implode(", ", $asParameters);
return "($sParameters)";
}
/**
* Returns the parameters names and default values for the method $name
* of the class $class
*
* @param string The class name
* @param string The method name
* @return array Format array(
* 'testParameter' => null, // no default value
* 'life' => 42, // default value = 42
* 'date' => 'yesterday',
* );
*/
public function getParametersList($class, $name)
{
return $this->api[$class][$name]['parameters'];
}
/**
* Returns the number of required parameters (parameters without default values).
*
* @param string The class name
* @param string The method name
* @return int The number of required parameters
*/
private function getNumberOfRequiredParameters($class, $name)
{
return $this->api[$class][$name]['numberOfRequiredParameters'];
}
/**
* Returns true if the method is found in the API of the given class name.
*
* @param string The class name
* @param string The method name
* @return bool
*/
private function isMethodAvailable( $className, $methodName)
{
return isset($this->api[$className][$methodName]);
}
/**
* Checks that all given parameters are not null
*
* @param array of values
* @throws exception If any parameter value is null
*/
private function checkParametersAreNotNull($className, $methodName, $parametersValues)
{
foreach($parametersValues as $value)
{
if(is_null($value))
{
$nbParamsRequired = $this->getNumberOfRequiredParameters($className, $methodName);
throw new Exception("The parameters are not valid. The method called requires $nbParamsRequired parameters. Please check your URL and the method API.");
}
}
}
/**
* Checks that the class is a Singleton (presence of the getInstance() method)
*
* @param string The class name
* @throws exception If the class is not a Singleton
*/
private function checkClassIsSingleton($className)
{
if(!method_exists($className, "getInstance"))
{
throw new Exception("Objects that provide an API must be Singleton and have a 'static public function getInstance()' method.");
}
}
/**
* Returns the API class name given the module name.
*
* For exemple for $module = 'Referers' it returns 'Piwik_Referers_API'
* Piwik_Referers_API is the class that extends Piwik_Apiable
* and that contains the methods to be published in the API.
*
* @param string module name
* @return string class name
*/
protected function getClassNameFromModule($module)
{
$class = Piwik::prefixClass($module ."_API");
return $class;
}
}
|