diff --git a/plugins/CustomAlerts/API.php b/plugins/CustomAlerts/API.php index d8b8c1a012c..953b83854f3 100755 --- a/plugins/CustomAlerts/API.php +++ b/plugins/CustomAlerts/API.php @@ -13,14 +13,8 @@ namespace Piwik\Plugins\CustomAlerts; -use Exception; -use Piwik\Piwik; -use Piwik\Common; -use Piwik\Date; use Piwik\Period; use Piwik\Db; -use Piwik\Plugins\SitesManager\API as SitesManagerApi; -use Piwik\Plugins\API\API as MetadataApi; /** * @@ -29,6 +23,11 @@ class API extends \Piwik\Plugin\API { + private function getModel() + { + return new Model(); + } + /** * Returns a single Alert * @@ -36,31 +35,7 @@ class API extends \Piwik\Plugin\API */ public function getAlert($idAlert) { - $alert = Db::fetchAll("SELECT * FROM " - . Common::prefixTable('alert') - . " WHERE idalert = ?", - intval($idAlert) - ); - - if (!$alert) { - throw new Exception(Piwik::translate('CustomAlerts_AlertDoesNotExist', $idAlert)); - } - - $alert = $alert[0]; - - if (!Piwik::isUserIsSuperUserOrTheUser($alert['login'])) { - throw new Exception(Piwik::translate('CustomAlerts_AccessException', $idAlert)); - } - -// $idSites = Piwik_FetchAll("SELECT * FROM " -// . Common::prefixTable('alert_site') -// . " WHERE idalert = ?", -// intval($idAlert) -// ); -// -// $alert['idsites'] = $idSites; - - return $alert; + return $this->getModel()->getAlert($idAlert); } /** @@ -72,83 +47,17 @@ public function getAlert($idAlert) */ public function getAlerts($idSites = array()) { - if (count($idSites)) { - Piwik::checkUserHasViewAccess($idSites); - } else { - Piwik::checkUserHasSomeViewAccess(); - $idSites = SitesManagerApi::getInstance()->getSitesIdWithAtLeastViewAccess(); - } - - $alerts = Db::fetchAll(("SELECT * FROM " - . Common::prefixTable('alert') - . " WHERE idalert IN ( - SELECT pas.idalert FROM " . Common::prefixTable('alert_site') - . " pas WHERE idsite IN (" . implode(",", $idSites) . ")) " - . "AND deleted = 0" - )); - - return $alerts; + return $this->getModel()->getAlert($idSites); } public function getTriggeredAlerts($period, $date, $login = false) { - Piwik::checkUserIsSuperUserOrTheUser($login); - - $this->checkPeriod($period); - $piwikDate = Date::factory($date); - $date = Period::factory($period, $piwikDate); - - $db = Db::get(); - - $sql = "SELECT pa.idalert AS idalert, - pal.idsite AS idsite, - pa.name AS alert_name, - ps.name AS site_name, - login, - period, - report, - report_condition, - report_matched, - metric, - metric_condition, - metric_matched - FROM ". Common::prefixTable('alert_log') ." pal - JOIN ". Common::prefixTable('alert') ." pa - ON pal.idalert = pa.idalert - JOIN ". Common::prefixTable('site') ." ps - ON pal.idsite = ps.idsite - WHERE period = ? - AND ts_triggered BETWEEN ? AND ?"; - - if ($login !== false) { - $sql .= " AND login = \"" . $login . "\""; - } - - return $db->fetchAll($sql, array( - $period, - $date->getDateStart()->getDateStartUTC(), - $date->getDateEnd()->getDateEndUTC()) - ); - + return $this->getModel()->getTriggeredAlerts($period, $date, $login); } public function getAllAlerts($period) { - Piwik::checkUserIsSuperUser(); - - $sql = "SELECT * FROM " - . Common::prefixTable('alert_site') . " alert, " - . Common::prefixTable('alert') . " alert_site " - . "WHERE alert.idalert = alert_site.idalert " - . "AND deleted = 0 "; - - if ($this->isValidPeriod($period)) { - $sql .= sprintf("AND period = '%s'", $period); - } else { - throw new Exception("Invalid period given."); - } - - return Db::fetchAll($sql); + return $this->getModel()->getAllAlerts($period); } /** @@ -168,55 +77,7 @@ public function getAllAlerts($period) */ public function addAlert($name, $idSites, $period, $email, $metric, $metricCondition, $metricValue, $report, $reportCondition = '', $reportValue = '') { - if (!is_array($idSites)) { - $idSites = array($idSites); - } - - Piwik::checkUserHasViewAccess($idSites); - - $name = $this->checkName($name); - $this->checkPeriod($period); - - // save in db - $db = Db::get(); - $idAlert = Db::fetchOne("SELECT max(idalert) + 1 FROM " . Common::prefixTable('alert')); - if ($idAlert == false) { - $idAlert = 1; - } - - $newAlert = array( - 'idalert' => $idAlert, - 'name' => $name, - 'period' => $period, - 'login' => Piwik::getCurrentUserLogin(), - 'enable_mail' => (int) $email, - 'metric' => $metric, - 'metric_condition' => $metricCondition, - 'metric_matched' => (float) $metricValue, - 'report' => $report, - 'deleted' => 0, - ); - - if (!empty($reportCondition) && !empty($reportCondition)) { - $newAlert['report_condition'] = $reportCondition; - $newAlert['report_matched'] = $reportValue; - } - - // Do we have a valid alert for all given idSites? - foreach ($idSites as $idSite) { - if (!$this->isValidAlert($newAlert, $idSite)) { - throw new Exception(Piwik::translate('Alerts_ReportOrMetricIsInvalid')); - } - } - - $db->insert(Common::prefixTable('alert'), $newAlert); - foreach ($idSites as $idSite) { - $db->insert(Common::prefixTable('alert_site'), array( - 'idalert' => $idAlert, - 'idsite' => $idSite - )); - } - return $idAlert; + return $this->getModel()->addAlert($name, $idSites, $period, $email, $metric, $metricCondition, $metricValue, $report, $reportCondition, $reportValue); } /** @@ -237,61 +98,7 @@ public function addAlert($name, $idSites, $period, $email, $metric, $metricCondi */ public function editAlert($idAlert, $name, $idSites, $period, $email, $metric, $metricCondition, $metricValue, $report, $reportCondition = '', $reportValue = '') { - if (!is_array($idSites)) { - $idSites = array($idSites); - } - - Piwik::checkUserHasViewAccess($idSites); - - // Is the name in a valid format? - $name = $this->checkName($name); - - // Is the period valid? - $this->checkPeriod($period); - - // Save in DB - $db = Db::get(); - - $alert = array( - 'name' => $name, - 'period' => $period, - 'login' => 'admin', //Piwik::getCurrentUserLogin(), - 'enable_mail' => (boolean) $email, - 'metric' => $metric, - 'metric_condition' => $metricCondition, - 'metric_matched' => (float) $metricValue, - 'report' => $report, - 'deleted' => 0, - ); - - // - if (!empty($reportCondition) && !empty($reportCondition)) { - $alert['report_condition'] = $reportCondition; - $alert['report_matched'] = $reportValue; - } else { - $alert['report_condition'] = null; - $alert['report_matched'] = null; - } - - // Do we have a valid alert for all given idSites? - foreach ($idSites as $idSite) { - if (!$this->isValidAlert($alert, $idSites)) { - throw new Exception(Piwik::translate('CustomAlerts_ReportOrMetricIsInvalid')); - } - } - - $db->update(Common::prefixTable('alert'), $alert, "idalert = " . $idAlert); - - $db->query("DELETE FROM " . Common::prefixTable("alert_site") . " - WHERE idalert = ?", $idAlert); - - foreach ($idSites as $idSite) { - $db->insert(Common::prefixTable('alert_site'), array( - 'idalert' => $idAlert, - 'idsite' => $idSite - )); - } - return $idAlert; + return $this->getModel()->editAlert($idAlert, $name, $idSites, $period, $email, $metric, $metricCondition, $metricValue, $report, $reportCondition, $reportValue); } /** @@ -301,86 +108,7 @@ public function editAlert($idAlert, $name, $idSites, $period, $email, $metric, $ */ public function deleteAlert($idAlert) { - $alert = $this->getAlert($idAlert); - - if (!$alert) { - throw new Exception(Piwik::translate('CustomAlerts_AlertDoesNotExist', $idAlert)); - } - - Piwik::checkUserIsSuperUserOrTheUser($alert['login']); - - $db = Db::get(); - $db->update( - Common::prefixTable('alert'), - array("deleted" => 1), - "idalert = " . $idAlert - ); + $this->getModel()->deleteAlert($idAlert); } - - /** - * Checks whether a report + metric exists for - * the given idSites and if the a dimension is - * given (requires report_condition, report_matched) - * - * @param array alert - * @param int $idSite - * @return boolean - */ - private function isValidAlert($alert, $idSite) - { - list($module, $action) = explode(".", $alert['report']); - - $report = MetadataApi::getInstance()->getMetadata($idSite, $module, $action); - - // If there is no report matching module + action for idSite it's not valid. - if(count($report) == 0) { - return false; - } - - // Merge all available metrics - $allMetrics = $report[0]['metrics']; - if (isset($report[0]['processedMetrics'])) { - $allMetrics = array_merge($allMetrics, $report[0]['processedMetrics']); - } - if (isset($report[0]['metricsGoal'])) { - $allMetrics = array_merge($allMetrics, $report[0]['metricsGoal']); - } - if (isset($report[0]['processedMetricsGoal'])) { - $allMetrics = array_merge($allMetrics, $report[0]['processedMetricsGoal']); - } - - if (!in_array($alert['metric'], array_keys($allMetrics))) { - return false; - } - - // If we have a dimension, we need to check if - // report_condition and report_matched is given. - if (isset($report[0]['dimension']) - && (!isset($alert['report_condition']) || !isset($alert['report_matched']))) { - return false; - } else { - return true; - } - - return false; - } - - private function checkName($name) - { - return urldecode($name); - } - - private function checkPeriod($period) - { - if (!$this->isValidPeriod($period)) { - throw new Exception(Piwik::translate('CustomAlerts_InvalidPeriod')); - } - } - - private function isValidPeriod($period) - { - return in_array($period, array('day', 'week', 'month', 'year')); - } - } ?> \ No newline at end of file diff --git a/plugins/CustomAlerts/Controller.php b/plugins/CustomAlerts/Controller.php index 666262ac43c..e80407384e0 100755 --- a/plugins/CustomAlerts/Controller.php +++ b/plugins/CustomAlerts/Controller.php @@ -78,7 +78,7 @@ public function addNewAlert() $view->alertGroups = array(); $view->alerts = $availableReports; - $view->alertGroupConditions = $this->alertGroupConditions; + $view->alertGroupConditions = $this->alertGroupConditions; $view->alertMetricConditions = $this->alertMetricConditions; return $view->render(); @@ -97,19 +97,13 @@ public function editAlert() $sitesList = SitesManagerApi::getInstance()->getSitesWithAtLeastViewAccess(); $view->sitesList = $sitesList; - // Fetch sites that the alert was defined on. - $sql = "SELECT idsite FROM ".Common::prefixTable('alert_site')." WHERE idalert = ?"; - $sites = Db::fetchAll($sql, $idAlert, \PDO::FETCH_COLUMN); - $idSites = array(); - foreach ($sites as $site) { - $idSites[] = $site['idsite']; - } - $view->sitesDefined = $idSites; + $model = new Model(); + $view->sitesDefined = $model->fetchSiteIdsTheAlertWasDefinedOn($idAlert); $availableReports = MetadataApi::getInstance()->getReportMetadata(); $view->alerts = $availableReports; - $view->alertGroupConditions = $this->alertGroupConditions; + $view->alertGroupConditions = $this->alertGroupConditions; $view->alertMetricConditions = $this->alertMetricConditions; return $view->render(); diff --git a/plugins/CustomAlerts/CustomAlerts.php b/plugins/CustomAlerts/CustomAlerts.php index b781e063a57..c46bd8bfe00 100755 --- a/plugins/CustomAlerts/CustomAlerts.php +++ b/plugins/CustomAlerts/CustomAlerts.php @@ -14,10 +14,7 @@ namespace Piwik\Plugins\CustomAlerts; use Piwik; -use Piwik\Common; -use Piwik\Date; use Piwik\Db; -use Exception; use Piwik\Menu\MenuTop; use Piwik\ScheduledTask; use Piwik\ScheduledTime; @@ -51,54 +48,12 @@ public function getCssFiles(&$cssFiles) public function install() { - $tableAlert = "CREATE TABLE " . Common::prefixTable('alert') . " ( - `idalert` INT NOT NULL PRIMARY KEY , - `name` VARCHAR(100) NOT NULL , - `login` VARCHAR(100) NOT NULL , - `period` VARCHAR(5) NOT NULL , - `report` VARCHAR(150) NOT NULL , - `report_condition` VARCHAR(50) , - `report_matched` VARCHAR(255) , - `metric` VARCHAR(150) NOT NULL , - `metric_condition` VARCHAR(50) NOT NULL , - `metric_matched` FLOAT NOT NULL , - `enable_mail` BOOLEAN NOT NULL , - `deleted` BOOLEAN NOT NULL - ) DEFAULT CHARSET=utf8 ;"; - - $tableAlertSite = "CREATE TABLE " . Common::prefixTable('alert_site') . "( - `idalert` INT( 11 ) NOT NULL , - `idsite` INT( 11 ) NOT NULL , - PRIMARY KEY ( idalert, idsite ) - ) DEFAULT CHARSET=utf8 ;"; - - $tableAlertLog = "CREATE TABLE " . Common::prefixTable('alert_log') . " ( - `idalert` INT( 11 ) NOT NULL , - `idsite` INT( 11 ) NOT NULL , - `ts_triggered` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, - KEY `ts_triggered` (`ts_triggered`) - )"; - - try { - Db::exec($tableAlert); - Db::exec($tableAlertLog); - Db::exec($tableAlertSite); - } catch (Exception $e) { - // mysql code error 1050:table already exists - // see bug #153 http://dev.piwik.org/trac/ticket/153 - if (!Db::get()->isErrNo($e, '1050')) { - throw $e; - } - } + Model::install(); } public function uninstall() { - $tables = array('alert', 'alert_log', 'alert_site'); - foreach ($tables as $table) { - $sql = "DROP TABLE " . Common::prefixTable($table); - Db::exec($sql); - } + Model::uninstall(); } public function addTopMenu() @@ -109,24 +64,24 @@ public function addTopMenu() public function getScheduledTasks(&$tasks) { $tasks[] = new ScheduledTask( - 'Piwik\Plugins\CustomAlerts\Processor', - 'processDailyAlerts', - null, - ScheduledTime::factory('daily') + 'Piwik\Plugins\CustomAlerts\Processor', + 'processDailyAlerts', + null, + ScheduledTime::factory('daily') ); $tasks[] = new ScheduledTask( - 'Piwik\Plugins\CustomAlerts\Processor', - 'processWeeklyAlerts', - null, - ScheduledTime::factory('weekly') + 'Piwik\Plugins\CustomAlerts\Processor', + 'processWeeklyAlerts', + null, + ScheduledTime::factory('weekly') ); $tasks[] = new ScheduledTask( - 'Piwik\Plugins\CustomAlerts\Processor', - 'processMonthlyAlerts', - null, - ScheduledTime::factory('monthly') + 'Piwik\Plugins\CustomAlerts\Processor', + 'processMonthlyAlerts', + null, + ScheduledTime::factory('monthly') ); } } diff --git a/plugins/CustomAlerts/Model.php b/plugins/CustomAlerts/Model.php new file mode 100755 index 00000000000..67ab05d05cf --- /dev/null +++ b/plugins/CustomAlerts/Model.php @@ -0,0 +1,465 @@ +isErrNo($e, '1050')) { + throw $e; + } + } + } + + public static function uninstall() + { + $tables = array('alert', 'alert_log', 'alert_site'); + foreach ($tables as $table) { + $sql = "DROP TABLE " . Common::prefixTable($table); + Db::exec($sql); + } + } + + + /** + * Returns a single Alert + * + * @param int $idAlert + */ + public function getAlert($idAlert) + { + $alert = Db::fetchAll("SELECT * FROM " + . Common::prefixTable('alert') + . " WHERE idalert = ?", + intval($idAlert) + ); + + if (!$alert) { + throw new Exception(Piwik::translate('CustomAlerts_AlertDoesNotExist', $idAlert)); + } + + $alert = $alert[0]; + + if (!Piwik::isUserIsSuperUserOrTheUser($alert['login'])) { + throw new Exception(Piwik::translate('CustomAlerts_AccessException', $idAlert)); + } + +// $idSites = Piwik_FetchAll("SELECT * FROM " +// . Common::prefixTable('alert_site') +// . " WHERE idalert = ?", +// intval($idAlert) +// ); +// +// $alert['idsites'] = $idSites; + + return $alert; + } + + /** + * Returns the Alerts that are defined on the idSites given. + * If no value is given, all Alerts for the current user will + * be returned. + * + * @param array $idSites + */ + public function getAlerts($idSites) + { + if (count($idSites)) { + Piwik::checkUserHasViewAccess($idSites); + } else { + Piwik::checkUserHasSomeViewAccess(); + $idSites = SitesManagerApi::getInstance()->getSitesIdWithAtLeastViewAccess(); + } + + $alerts = Db::fetchAll(("SELECT * FROM " + . Common::prefixTable('alert') + . " WHERE idalert IN ( + SELECT pas.idalert FROM " . Common::prefixTable('alert_site') + . " pas WHERE idsite IN (" . implode(",", $idSites) . ")) " + . "AND deleted = 0" + )); + + return $alerts; + } + + public function getTriggeredAlerts($period, $date, $login) + { + Piwik::checkUserIsSuperUserOrTheUser($login); + + $this->checkPeriod($period); + $piwikDate = Date::factory($date); + $date = Period::factory($period, $piwikDate); + + $db = Db::get(); + + $sql = "SELECT pa.idalert AS idalert, + pal.idsite AS idsite, + pa.name AS alert_name, + ps.name AS site_name, + login, + period, + report, + report_condition, + report_matched, + metric, + metric_condition, + metric_matched + FROM ". Common::prefixTable('alert_log') ." pal + JOIN ". Common::prefixTable('alert') ." pa + ON pal.idalert = pa.idalert + JOIN ". Common::prefixTable('site') ." ps + ON pal.idsite = ps.idsite + WHERE period = ? + AND ts_triggered BETWEEN ? AND ?"; + + if ($login !== false) { + $sql .= " AND login = \"" . $login . "\""; + } + + return $db->fetchAll($sql, array( + $period, + $date->getDateStart()->getDateStartUTC(), + $date->getDateEnd()->getDateEndUTC()) + ); + + } + + public function getAllAlerts($period) + { + Piwik::checkUserIsSuperUser(); + + $sql = "SELECT * FROM " + . Common::prefixTable('alert_site') . " alert, " + . Common::prefixTable('alert') . " alert_site " + . "WHERE alert.idalert = alert_site.idalert " + . "AND deleted = 0 "; + + if ($this->isValidPeriod($period)) { + $sql .= sprintf("AND period = '%s'", $period); + } else { + throw new Exception("Invalid period given."); + } + + return Db::fetchAll($sql); + } + + /** + * Creates an Alert for given website(s). + * + * @param string $name + * @param mixed $idSites + * @param string $period + * @param bool $email + * @param string $metric (nb_uniq_visits, sum_visit_length, ..) + * @param string $metricCondition + * @param float $metricValue + * @param string $report + * @param string $reportCondition + * @param string $reportValue + * @return int ID of new Alert + */ + public function addAlert($name, $idSites, $period, $email, $metric, $metricCondition, $metricValue, $report, $reportCondition, $reportValue) + { + if (!is_array($idSites)) { + $idSites = array($idSites); + } + + Piwik::checkUserHasViewAccess($idSites); + + $name = $this->checkName($name); + $this->checkPeriod($period); + + // save in db + $db = Db::get(); + $idAlert = Db::fetchOne("SELECT max(idalert) + 1 FROM " . Common::prefixTable('alert')); + if ($idAlert == false) { + $idAlert = 1; + } + + $newAlert = array( + 'idalert' => $idAlert, + 'name' => $name, + 'period' => $period, + 'login' => Piwik::getCurrentUserLogin(), + 'enable_mail' => (int) $email, + 'metric' => $metric, + 'metric_condition' => $metricCondition, + 'metric_matched' => (float) $metricValue, + 'report' => $report, + 'deleted' => 0, + ); + + if (!empty($reportCondition) && !empty($reportCondition)) { + $newAlert['report_condition'] = $reportCondition; + $newAlert['report_matched'] = $reportValue; + } + + // Do we have a valid alert for all given idSites? + foreach ($idSites as $idSite) { + if (!$this->isValidAlert($newAlert, $idSite)) { + throw new Exception(Piwik::translate('Alerts_ReportOrMetricIsInvalid')); + } + } + + $db->insert(Common::prefixTable('alert'), $newAlert); + foreach ($idSites as $idSite) { + $db->insert(Common::prefixTable('alert_site'), array( + 'idalert' => $idAlert, + 'idsite' => $idSite + )); + } + return $idAlert; + } + + /** + * Edits an Alert for given website(s). + * + * @param string $idalert ID of the Alert to edit. + * @param string $name Name of Alert + * @param mixed $idSites Single int or array of ints of idSites. + * @param string $period Period the alert is defined on. + * @param bool $email + * @param string $metric (nb_uniq_visits, sum_visit_length, ..) + * @param string $metricCondition + * @param float $metricValue + * @param string $report + * @param string $reportCondition + * @param string $reportValue + * @return boolean + */ + public function editAlert($idAlert, $name, $idSites, $period, $email, $metric, $metricCondition, $metricValue, $report, $reportCondition, $reportValue) + { + if (!is_array($idSites)) { + $idSites = array($idSites); + } + + Piwik::checkUserHasViewAccess($idSites); + + // Is the name in a valid format? + $name = $this->checkName($name); + + // Is the period valid? + $this->checkPeriod($period); + + // Save in DB + $db = Db::get(); + + $alert = array( + 'name' => $name, + 'period' => $period, + 'login' => 'admin', //Piwik::getCurrentUserLogin(), + 'enable_mail' => (boolean) $email, + 'metric' => $metric, + 'metric_condition' => $metricCondition, + 'metric_matched' => (float) $metricValue, + 'report' => $report, + 'deleted' => 0, + ); + + // + if (!empty($reportCondition) && !empty($reportCondition)) { + $alert['report_condition'] = $reportCondition; + $alert['report_matched'] = $reportValue; + } else { + $alert['report_condition'] = null; + $alert['report_matched'] = null; + } + + // Do we have a valid alert for all given idSites? + foreach ($idSites as $idSite) { + if (!$this->isValidAlert($alert, $idSites)) { + throw new Exception(Piwik::translate('CustomAlerts_ReportOrMetricIsInvalid')); + } + } + + $db->update(Common::prefixTable('alert'), $alert, "idalert = " . $idAlert); + + $db->query("DELETE FROM " . Common::prefixTable("alert_site") . " + WHERE idalert = ?", $idAlert); + + foreach ($idSites as $idSite) { + $db->insert(Common::prefixTable('alert_site'), array( + 'idalert' => $idAlert, + 'idsite' => $idSite + )); + } + return $idAlert; + } + + /** + * Delete alert by id. + * + * @param int $idAlert + */ + public function deleteAlert($idAlert) + { + $alert = $this->getAlert($idAlert); + + if (!$alert) { + throw new Exception(Piwik::translate('CustomAlerts_AlertDoesNotExist', $idAlert)); + } + + Piwik::checkUserIsSuperUserOrTheUser($alert['login']); + + $db = Db::get(); + $db->update( + Common::prefixTable('alert'), + array("deleted" => 1), + "idalert = " . $idAlert + ); + } + + public function triggerAlert($idAlert, $idSite) + { + $db = Db::get(); + $db->insert( + Common::prefixTable('alert_log'), + array( + 'idalert' => $idAlert, + 'idsite' => $idSite, + 'ts_triggered' => Date::now()->getDatetime() + ) + ); + } + + public function fetchSiteIdsTheAlertWasDefinedOn($idAlert) + { + $sql = "SELECT idsite FROM ".Common::prefixTable('alert_site')." WHERE idalert = ?"; + $sites = Db::fetchAll($sql, $idAlert, \PDO::FETCH_COLUMN); + + $idSites = array(); + foreach ($sites as $site) { + $idSites[] = $site['idsite']; + } + + return $idSites; + } + + /** + * Checks whether a report + metric exists for + * the given idSites and if the a dimension is + * given (requires report_condition, report_matched) + * + * @param array alert + * @param int $idSite + * @return boolean + */ + private function isValidAlert($alert, $idSite) + { + list($module, $action) = explode(".", $alert['report']); + + $report = MetadataApi::getInstance()->getMetadata($idSite, $module, $action); + + // If there is no report matching module + action for idSite it's not valid. + if(count($report) == 0) { + return false; + } + + // Merge all available metrics + $allMetrics = $report[0]['metrics']; + if (isset($report[0]['processedMetrics'])) { + $allMetrics = array_merge($allMetrics, $report[0]['processedMetrics']); + } + if (isset($report[0]['metricsGoal'])) { + $allMetrics = array_merge($allMetrics, $report[0]['metricsGoal']); + } + if (isset($report[0]['processedMetricsGoal'])) { + $allMetrics = array_merge($allMetrics, $report[0]['processedMetricsGoal']); + } + + if (!in_array($alert['metric'], array_keys($allMetrics))) { + return false; + } + + // If we have a dimension, we need to check if + // report_condition and report_matched is given. + if (isset($report[0]['dimension']) + && (!isset($alert['report_condition']) || !isset($alert['report_matched']))) { + return false; + } else { + return true; + } + + return false; + } + + private function checkName($name) + { + return urldecode($name); + } + + private function checkPeriod($period) + { + if (!$this->isValidPeriod($period)) { + throw new Exception(Piwik::translate('CustomAlerts_InvalidPeriod')); + } + } + + private function isValidPeriod($period) + { + return in_array($period, array('day', 'week', 'month', 'year')); + } + +} +?> \ No newline at end of file diff --git a/plugins/CustomAlerts/Processor.php b/plugins/CustomAlerts/Processor.php index 74da2997094..6b41cc195a3 100755 --- a/plugins/CustomAlerts/Processor.php +++ b/plugins/CustomAlerts/Processor.php @@ -48,9 +48,9 @@ public function processAlerts($period) $alerts = API::getInstance()->getAllAlerts($period); foreach ($alerts as $alert) { - $report = $alert['report']; - $metric = $alert['metric']; - $idSite = $alert['idsite']; + $report = $alert['report']; + $metric = $alert['metric']; + $idSite = $alert['idsite']; $idAlert = $alert['idalert']; $params = array( @@ -65,7 +65,7 @@ public function processAlerts($period) $request = new Piwik\API\Request($params); $result = $request->process(); - $metricOne = $this->getMetricFromTable($result, $alert['metric'], $alert['report_condition'], $alert['report_matched']); + $metricOne = $this->getMetricFromTable($result, $metric, $alert['report_condition'], $alert['report_matched']); // Do we have data? Continue otherwise. if (is_null($metricOne)) { @@ -122,20 +122,13 @@ public function processAlerts($period) } } - //$this->sendNewAlerts($period); + $this->sendNewAlerts($period); } private function triggerAlert($idAlert, $idSite) { - $db = Db::get(); - $db->insert( - Common::prefixTable('alert_log'), - array( - 'idalert' => $idAlert, - 'idsite' => $idSite, - 'ts_triggered' => Date::now()->getDatetime() - ) - ); + $model = new Model(); + $model->triggerAlert($idAlert, $idSite); } /**