Skip to content
Extraits de code Groupes Projets
Valider 578e7e74 rédigé par Thomas Steur's avatar Thomas Steur
Parcourir les fichiers

and there we have a dimension generator including example and documentation

parent b8af5d8c
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
......@@ -70,6 +70,11 @@ abstract class ActionDimension extends Dimension
return $this->columnType;
}
public function onLookupAction(Request $request, Action $action)
{
return false;
}
/**
* @return string|int
* @throws \Exception in case not implemented
......
......@@ -262,18 +262,17 @@ abstract class Action
$dimensions = ActionDimension::getAllDimensions();
foreach ($dimensions as $dimension) {
if (method_exists($dimension, 'onLookupAction')) {
$value = $dimension->onLookupAction($this->request, $this);
if ($value !== false) {
$field = $dimension->getColumnName();
$value = $dimension->onLookupAction($this->request, $this);
if (empty($field)) {
throw new Exception('Dimension ' . get_class($dimension) . ' does not define a field name');
}
if ($value !== false) {
$actions[$field] = array($value, $dimension->getActionId());
Common::printDebug("$field = $value");
}
$actions[$field] = array($value, $dimension->getActionId());
Common::printDebug("$field = $value");
}
}
......
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\CoreConsole\Commands;
use Piwik\Common;
use Piwik\DbHelper;
use Piwik\Plugin\ActionDimension;
use Piwik\Plugin\Report;
use Piwik\Plugin\VisitDimension;
use Piwik\Translate;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* TODO automatically create or modify translation file for instance for dimension name
*/
class GenerateDimension extends GeneratePluginBase
{
protected function configure()
{
$this->setName('generate:dimension')
->setDescription('Adds a new dimension to an existing plugin. This allows you to persist new values during tracking.')
->addOption('pluginname', null, InputOption::VALUE_REQUIRED, 'The name of an existing plugin which does not have a menu defined yet')
->addOption('type', null, InputOption::VALUE_REQUIRED, 'Whether you want to create a Visit or an Action dimension')
->addOption('dimensionname', null, InputOption::VALUE_REQUIRED, 'A human readable name of the dimension which will be for instance visible in the UI')
->addOption('columnname', null, InputOption::VALUE_REQUIRED, 'The name of the column in the MySQL database the dimension will be stored under')
->addOption('columntype', null, InputOption::VALUE_REQUIRED, 'The MySQL type for your dimension, for instance "VARCHAR(255) NOT NULL".');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$pluginName = $this->getPluginName($input, $output);
$type = $this->getDimensionType($input, $output);
$dimensionName = $this->getDimensionName($input, $output);
$columnName = $this->getColumnName($input, $output, $type);
$columType = $this->getColumnType($input, $output);
$dimensionClassName = $this->getDimensionClassName($dimensionName);
$exampleFolder = PIWIK_INCLUDE_PATH . '/plugins/ExamplePlugin';
$replace = array('example_action_dimension' => strtolower($columnName),
'example_visit_dimension' => strtolower($columnName),
'INTEGER(11) DEFAULT 0 NOT NULL' => strtoupper($columType),
'VARCHAR(255) DEFAULT NULL' => strtoupper($columType),
'ExampleVisitDimension' => $dimensionClassName,
'ExampleActionDimension' => $dimensionClassName,
'ExamplePlugin_DimensionName' => ucfirst($dimensionName),
'ExamplePlugin' => $pluginName,
);
$whitelistFiles = array('/Columns');
if ('visit' == $type) {
$whitelistFiles[] = '/Columns/ExampleVisitDimension.php';
} elseif ('action' == $type) {
$whitelistFiles[] = '/Columns/ExampleActionDimension.php';
} else {
throw new \InvalidArgumentException('This dimension type is not available');
}
$this->copyTemplateToPlugin($exampleFolder, $pluginName, $replace, $whitelistFiles);
$this->writeSuccessMessage($output, array(
sprintf('Columns/%s.php for %s generated.', ucfirst($dimensionClassName), $pluginName),
'You should now implement the events within this file',
'Enjoy!'
));
}
private function getDimensionClassName($dimensionName)
{
$dimensionName = trim($dimensionName);
$dimensionName = str_replace(' ', '', $dimensionName);
$dimensionName = preg_replace("/[^A-Za-z0-9]/", '', $dimensionName);
$dimensionName = ucfirst($dimensionName);
return $dimensionName;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return array
* @throws \RunTimeException
*/
protected function getDimensionName(InputInterface $input, OutputInterface $output)
{
$validate = function ($dimensionName) {
if (empty($dimensionName)) {
throw new \InvalidArgumentException('Please enter the name of your dimension');
}
if (preg_match("/[^A-Za-z0-9 ]/", $dimensionName)) {
throw new \InvalidArgumentException('Only alpha numerical characters and whitespaces are allowed');
}
return $dimensionName;
};
$dimensionName = $input->getOption('dimensionname');
if (empty($dimensionName)) {
$dialog = $this->getHelperSet()->get('dialog');
$dimensionName = $dialog->askAndValidate($output, 'Enter a human readable name of your dimension, for instance "Browser": ', $validate);
} else {
$validate($dimensionName);
}
$dimensionName = ucfirst($dimensionName);
return $dimensionName;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return array
* @throws \RunTimeException
*/
protected function getColumnName(InputInterface $input, OutputInterface $output, $type)
{
$validate = function ($columnName) use ($type) {
if (empty($columnName)) {
throw new \InvalidArgumentException('Please enter the name of the dimension column');
}
if (preg_match("/[^A-Za-z0-9_ ]/", $columnName)) {
throw new \InvalidArgumentException('Only alpha numerical characters, underscores and whitespaces are allowed');
}
if ('visit' == $type) {
$columns = array_keys(DbHelper::getTableColumns(Common::prefixTable('log_visit')));
} elseif ('action' == $type) {
$columns = array_keys(DbHelper::getTableColumns(Common::prefixTable('log_link_visit_action')));
} else {
$columns = array();
}
foreach ($columns as $column) {
if (strtolower($column) === strtolower($columnName)) {
throw new \InvalidArgumentException('This column name is already in use.');
}
}
return $columnName;
};
$columnName = $input->getOption('columnname');
if (empty($columnName)) {
$dialog = $this->getHelperSet()->get('dialog');
$columnName = $dialog->askAndValidate($output, 'Enter the name of the column under which it should be stored in the MySQL database, for instance "visit_total_time": ', $validate);
} else {
$validate($columnName);
}
return $columnName;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return array
* @throws \RunTimeException
*/
protected function getColumnType(InputInterface $input, OutputInterface $output)
{
$validate = function ($columnType) {
if (empty($columnType)) {
throw new \InvalidArgumentException('Please enter the type of the dimension column');
}
return $columnType;
};
$columnType = $input->getOption('columntype');
if (empty($columnType)) {
$dialog = $this->getHelperSet()->get('dialog');
$columnType = $dialog->askAndValidate($output, 'Enter the type of the column under which it should be stored in the MySQL database, for instance "VARCHAR(255) NOT NULL": ', $validate);
} else {
$validate($columnType);
}
return $columnType;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return array
* @throws \RunTimeException
*/
protected function getDimensionType(InputInterface $input, OutputInterface $output)
{
$acceptedValues = array('visit', 'action');
$validate = function ($type) use ($acceptedValues) {
if (empty($type) || !in_array($type, $acceptedValues)) {
throw new \InvalidArgumentException('Please enter a valid dimension type (' . implode(', ', $acceptedValues) . '): ');
}
return $type;
};
$type = $input->getOption('type');
if (empty($type)) {
$dialog = $this->getHelperSet()->get('dialog');
$type = $dialog->askAndValidate($output, 'Please choose the type of dimension you want to create (' . implode(', ', $acceptedValues) . '): ', $validate, false, null, $acceptedValues);
} else {
$validate($type);
}
return $type;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return array
* @throws \RunTimeException
*/
protected function getPluginName(InputInterface $input, OutputInterface $output)
{
$pluginNames = $this->getPluginNames();
$invalidName = 'You have to enter a name of an existing plugin.';
return $this->askPluginNameAndValidate($input, $output, $pluginNames, $invalidName);
}
}
......@@ -90,7 +90,7 @@ class GenerateReport extends GeneratePluginBase
$apiName = 'get' . ucfirst($reportName);
return lcfirst($apiName);
return $apiName;
}
/**
......
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\ExamplePlugin\Columns;
use Piwik\Common;
use Piwik\Piwik;
use Piwik\Plugin\ActionDimension;
use Piwik\Plugin\Segment;
use Piwik\Tracker\ActionPageview;
use Piwik\Tracker\Request;
use Piwik\Tracker\Visitor;
use Piwik\Tracker\Action;
/**
* This example dimension recognizes a new tracking url parameter that is supposed to save the keywords that were used
* on a certain page. Please note that dimension instances are usually cached during one tracking request so they
* should be stateless (meaning an instance of this dimension will be reused if requested multiple times).
*/
class ExampleActionDimension extends ActionDimension
{
/**
* This will be the name of the column in the log_link_visit_action table if a $columnType is specified.
* @var string
*/
protected $columnName = 'example_action_dimension';
/**
* If a columnType is defined, we will create this a column in the MySQL table having this type. Please make sure
* MySQL will understand this type. Once you change the column type the Piwik platform will notify the user to
* perform an update which can sometimes take a long time so be careful when choosing the correct column type.
* @var string
*/
protected $columnType = 'VARCHAR(255) DEFAULT NULL';
/**
* The name of the dimension which will be visible for instance in the UI of a related report and in the mobile app.
* @return string
*/
public function getName()
{
return Piwik::translate('ExamplePlugin_DimensionName');
}
/**
* By defining one or multiple segments user can filter their users by this column. For instance show all actions
* only considering users having more than 10 achievement points. If you do not want to define a segment for this
* dimension just remove the column.
*/
protected function configureSegments()
{
$segment = new Segment();
$segment->setSegment('keywords');
$segment->setCategory('General_Actions');
$segment->setName('ExamplePlugin_DimensionName');
$segment->setAcceptedValues('Here you should explain which values are accepted/useful: Any word, for instance MyKeyword1, MyKeyword2');
$this->addSegment($segment);
}
/**
* This event is triggered before a new action is logged to the log_link_visit_action table. It overwrites any
* looked up action so it makes usually no sense to implement both methods but it sometimes does. You can assign
* any value to the column or return boolan false in case you do not want to save any value.
*
* @param Request $request
* @param Visitor $visitor
* @param Action $action
*
* @return mixed|false
*/
public function onNewAction(Request $request, Visitor $visitor, Action $action)
{
if (!($action instanceof ActionPageview)) {
// save value only in case it is a page view.
return false;
}
$value = Common::getRequestVar('my_page_keywords', false, 'string', $request->getParams());
if (false === $value) {
return $value;
}
$value = trim($value);
return substr($value, 0, 255);
}
/**
* If the value you want to save for your dimension is something like a page title or page url, you usually do not
* want to save the raw value over and over again to save bytes in the database. Instead you want to save each value
* once in the log_action table and refer to this value by its ID in the log_link_visit_action table. You can do
* this by returning an action id in "getActionId()" and by returning a value here. If a value should be ignored
* or not persisted just return boolean false. Please note if you return a value here and you implement the event
* "onNewAction" the value will be probably overwritten by the other event. So make sure to implement only one of
* those.
*
* @param Request $request
* @param Action $action
*
* @return false|mixed
public function onLookupAction(Request $request, Action $action)
{
if (!($action instanceof ActionPageview)) {
// save value only in case it is a page view.
return false;
}
$value = Common::getRequestVar('my_page_keywords', false, 'string', $request->getParams());
if (false === $value) {
return $value;
}
$value = trim($value);
return substr($value, 0, 255);
}
*/
/**
* An action id. The value returned by the lookup action will be associated with this id in the log_action table.
* @return int
public function getActionId()
{
return Action::TYPE_PAGE_URL;
}
*/
}
\ No newline at end of file
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\ExamplePlugin\Columns;
use Piwik\Piwik;
use Piwik\Plugin\VisitDimension;
use Piwik\Plugin\Segment;
use Piwik\Tracker\Request;
use Piwik\Tracker\Visitor;
use Piwik\Tracker\Action;
/**
* This example dimension counts achievement points for each user. A user gets one achievement point for each action
* plus five extra achievement points for each conversion. This would allow you to create a ranking showing the most
* active/valueable users. It is just an example, you can log pretty much everything and even just store any custom
* request url property. Please note that dimension instances are usually cached during one tracking request so they
* should be stateless (meaning an instance of this dimension will be reused if requested multiple times).
*/
class ExampleVisitDimension extends VisitDimension
{
/**
* This will be the name of the column in the log_visit table if a $columnType is specified.
* @var string
*/
protected $columnName = 'example_visit_dimension';
/**
* If a columnType is defined, we will create this a column in the MySQL table having this type. Please make sure
* MySQL will understand this type. Once you change the column type the Piwik platform will notify the user to
* perform an update which can sometimes take a long time so be careful when choosing the correct column type.
* @var string
*/
protected $columnType = 'INTEGER(11) DEFAULT 0 NOT NULL';
/**
* The name of the dimension which will be visible for instance in the UI of a related report and in the mobile app.
* @return string
*/
public function getName()
{
return Piwik::translate('ExamplePlugin_DimensionName');
}
/**
* By defining one or multiple segments user can filter their users by this column. For instance show all reports
* only considering users having more than 10 achievement points. If you do not want to define a segment for this
* dimension just remove the column.
*/
protected function configureSegments()
{
$segment = new Segment();
$segment->setSegment('achievementPoints');
$segment->setCategory('Enter Segment Category Name');
$segment->setName('ExamplePlugin_DimensionName');
$segment->setAcceptedValues('Here you should explain which values are accepted/useful: Any number, for instance 1, 2, 3 , 99');
$this->addSegment($segment);
}
/**
* The onNewVisit method is triggered when a new visitor is detected. This means here you can define an initial
* value for this user. By returning boolean false no value will be saved. Once the user makes another action the
* event "onExistingVisit" is executed. That means for each visitor this method is executed once. If you do not want
* to perform any action on a new visit you can just remove this method.
*
* @param Request $request
* @param Visitor $visitor
* @param Action|null $action
* @return mixed|false
*/
public function onNewVisit(Request $request, Visitor $visitor, $action)
{
if (empty($action)) {
return 0;
}
return 1;
// you could also easily save any custom tracking url parameters
// return Common::getRequestVar('myCustomTrackingParam', 'default', 'string', $request->getParams());
// return Common::getRequestVar('linuxversion', false, 'string', $request->getParams());
}
/**
* The onExistingVisit method is triggered when a visitor was recognized meaning it is not a new visitor.
* If you want you can overwrite any previous value set by the event onNewVisit. By returning boolean false no value
* will be updated. If you do not want to perform any action on a new visit you can just remove this method.
*
* @param Request $request
* @param Visitor $visitor
* @param Action|null $action
*
* @return mixed|false
*/
public function onExistingVisit(Request $request, Visitor $visitor, $action)
{
if (empty($action)) {
return false; // Do not change an already persisted value
}
return $visitor->getVisitorColumn($this->columnName) + 1;
}
/**
* This event is executed shortly after "onNewVisit" or "onExistingVisit" in case the visitor converted a goal.
* In this example we give the user 5 extra points for this achievement. Usually this event is not needed and you
* can simply remove this method therefore. An example would be for instance to persist the last converted
* action url. Return boolean false if you do not want to change the value in some cases or just remove the value.
*
* @param Request $request
* @param Visitor $visitor
* @param Action|null $action
*
* @return mixed|false
*/
public function onConvertedVisit(Request $request, Visitor $visitor, $action)
{
return $visitor->getVisitorColumn($this->columnName) + 5; // give this visitor 5 extra achievement points
}
/**
* By implementing this event you can persist a value to the log_conversion table persisting this value for a
* specific conversion. The persisted value will be logged along the conversion and will not be changed afterwards.
* This allows you to generated reports that shows for instance which url was called how often for a speicifc
* conversion. Once you implement this event and a $columnType is defined a column in the log_conversion MySQL table
* will be automatically created.
*
* @param Request $request
* @param Visitor $visitor
* @param Action|null $action
*
* @return mixed
public function onRecordGoal(Request $request, Visitor $visitor, $action)
{
return $visitor->getVisitorColumn($this->columnName);
}
*/
/**
* Sometimes you may want to make sure another dimension is executed before your dimension so you can persist
* a value depending on the value of other dimensions. You can do this by defining an array of dimension names.
* If you access any value of any other column within your events, you should require them here. Otherwise those
* values may not be available.
* @return array
public function getRequiredVisitFields()
{
return array('idsite', 'server_time');
}
*/
}
\ No newline at end of file
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter