Skip to content

Commit

Permalink
Merge pull request #423 from matomo-org/PG-2903-ga-import-no-data-screen
Browse files Browse the repository at this point in the history
Added GA import tab in no data screen
  • Loading branch information
AltamashShaikh authored Jul 12, 2023
2 parents ae2fad6 + 5fc955a commit 8e34416
Show file tree
Hide file tree
Showing 17 changed files with 697 additions and 66 deletions.
52 changes: 20 additions & 32 deletions Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,29 +106,12 @@ public function index($errorMessage = false)
$maxEndDateDesc = Date::factory($maxEndDate)->toString();
}

$isConnectAccountsActivated = Manager::getInstance()->isPluginActivated('ConnectAccounts') && ConnectAccounts::isMatomoOAuthEnabled();
$authBaseUrl = $isConnectAccountsActivated ? "https://" . StaticContainer::get('CloudAccountsInstanceId') . '/index.php?' : '';
$jwt = Common::getRequestVar('state', '', 'string');
if(empty($jwt) && Piwik::hasUserSuperUserAccess() && $isConnectAccountsActivated) {
// verify an existing user by supplying a jwt too
$jwt = ConnectHelper::buildOAuthStateJwt(SettingsPiwik::getPiwikInstanceId(),
ConnectAccounts::INITIATED_BY_GA);
}
$googleAuthUrl = '';
if($isConnectAccountsActivated) {
$googleAuthUrl = $authBaseUrl . Http::buildQuery([
'module' => 'ConnectAccounts',
'action' => 'initiateOauth',
'state' => $jwt,
'strategy' => GoogleConnect::getStrategyName()
]);
}

$isClientConfigurable = StaticContainer::get('GoogleAnalyticsImporter.isClientConfigurable');
if ($isConnectAccountsActivated) {
if (GoogleAnalyticsImporter::isConnectAccountsPluginActivated()) {
$notification = new Notification(Piwik::translate('GoogleAnalyticsImporter_GoogleOauthCompleteWarning', ['<strong>', '</strong>']));
$notification->context = Notification::CONTEXT_WARNING;
$notification->raw = true;
$notification->flags = Notification::FLAG_CLEAR;
Notification\Manager::notify('GoogleAnalyticsImporter_OauthCompletionWarning', $notification);
}
return $this->renderTemplate('index', [
Expand Down Expand Up @@ -184,17 +167,10 @@ public function index($errorMessage = false)
],
],
],
'isConnectAccountsActivated' => $isConnectAccountsActivated,
'radioOptions' => !$isConnectAccountsActivated ? [] : [
'connectAccounts' => Piwik::translate('ConnectAccounts_OptionQuickConnectWithGa'),
'manual' => Piwik::translate('ConnectAccounts_OptionAdvancedConnectWithGa'),
],
'googleAuthUrl' => $googleAuthUrl,
'manualUploadText' => Piwik::translate('GoogleAnalyticsImporter_ConfigureTheImporterLabel2')
. '<br />' . Piwik::translate('GoogleAnalyticsImporter_ConfigureTheImporterLabel3', [
'<a href="https://matomo.org/faq/general/set-up-google-analytics-import/" rel="noreferrer noopener" target="_blank">',
'</a>',
]),
'isConnectAccountsActivated' => GoogleAnalyticsImporter::isConnectAccountsPluginActivated(),
'radioOptions' => GoogleAnalyticsImporter::getRadioOptions(),
'googleAuthUrl' => GoogleAnalyticsImporter::getGoogleOAuthUrl(),
'manualUploadText' => GoogleAnalyticsImporter::getManualUploadText(),
]);
}

Expand Down Expand Up @@ -281,6 +257,10 @@ public function configureClient()

Nonce::checkNonce('GoogleAnalyticsImporter.googleClientConfig', Common::getRequestVar('config_nonce'));

if (GoogleAnalyticsImporter::isConnectAccountsPluginActivated() && GoogleConnect::isStrategyActive()) {
GoogleConnect::disableMatomoCloudOverride();
}

/** @var Authorization $authorization */
$authorization = StaticContainer::get(Authorization::class);

Expand Down Expand Up @@ -316,10 +296,18 @@ public function configureClient()
$errorMessage = substr($errorMessage, 0, 1024);
}

Url::redirectToUrl(Url::getCurrentUrlWithoutQueryString() . Url::getCurrentQueryStringWithParametersModified([
$modifiedParameters = [
'action' => 'index',
'error' => $errorMessage,
]));
];
$isNoDataPage = Common::getRequestVar('isNoDataPage', '');
if ($isNoDataPage) {
$modifiedParameters = [
'module' => 'CoreHome',
'action' => 'index',
];
}
Url::redirectToUrl(Url::getCurrentUrlWithoutQueryString() . Url::getCurrentQueryStringWithParametersModified($modifiedParameters));
}

public function deleteImportStatus()
Expand Down
93 changes: 92 additions & 1 deletion GoogleAnalyticsImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@
use Piwik\DataAccess\RawLogDao;
use Piwik\DataTable;
use Piwik\Date;
use Piwik\Http;
use Piwik\Period;
use Piwik\Piwik;
use Piwik\Nonce;
use Piwik\Plugins\GoogleAnalyticsImporter\Google\Authorization;
use Piwik\View;
use Piwik\Plugin\Manager;
use Piwik\Plugin\ViewDataTable;
use Piwik\Plugins\ConnectAccounts\ConnectAccounts;
use Piwik\Plugins\ConnectAccounts\helpers\ConnectHelper;
use Piwik\Plugins\ConnectAccounts\Strategy\Google\GoogleConnect;
use Piwik\Plugins\Referrers\API;
use Piwik\SettingsPiwik;
use Piwik\Site;
use Psr\Log\LoggerInterface;

Expand Down Expand Up @@ -64,7 +71,8 @@ public function registerEvents()
'SitesManager.deleteSite.end' => 'onSiteDeleted',
'Template.jsGlobalVariables' => 'addImportedDateRangesForSite',
'Archiving.isRequestAuthorizedToArchive' => 'isRequestAuthorizedToArchive',
'AssetManager.getJavaScriptFiles' => 'getJsFiles'
'AssetManager.getJavaScriptFiles' => 'getJsFiles',
'Template.embedGAImportNoData' => 'embedGAImportNoData'
];
}

Expand Down Expand Up @@ -240,6 +248,22 @@ public function getClientSideTranslationKeys(&$translationKeys)
$translationKeys[] = 'GoogleAnalyticsImporter_FutureDateHelp';
$translationKeys[] = 'GoogleAnalyticsImporter_ScheduleImportDescription';
$translationKeys[] = 'GoogleAnalyticsImporter_EndDateHelpText';
$translationKeys[] = 'GoogleAnalyticsImporter_Authorize';
$translationKeys[] = 'GoogleAnalyticsImporter_GoogleOauthCompleteWarning';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep01';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep02';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep03';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep04';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep05';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep06';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep07';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep07Note';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep08';
$translationKeys[] = 'GoogleAnalyticsImporter_GAImportNoDataScreenStep09';
$translationKeys[] = 'GoogleAnalyticsImporter_Start';
$translationKeys[] = 'GoogleAnalyticsImporter_ReAuthorize';
$translationKeys[] = 'GoogleAnalyticsImporter_AccountsConnectedSuccessfully';
$translationKeys[] = 'GoogleAnalyticsImporter_UploadSuccessful';

if (Manager::getInstance()->isPluginActivated('ConnectAccounts') && ConnectAccounts::isMatomoOAuthEnabled()) {
$translationKeys[] = "ConnectAccounts_ConfigureGoogleAuthHelp1";
Expand Down Expand Up @@ -483,4 +507,71 @@ public static function hasOverLapCheckParams()
}
return true;
}

public static function getRadioOptions()
{

return (!self::isConnectAccountsPluginActivated() ? [] : [
'connectAccounts' => Piwik::translate('ConnectAccounts_OptionQuickConnectWithGa'),
'manual' => Piwik::translate('ConnectAccounts_OptionAdvancedConnectWithGa'),
]);
}

public static function getManualUploadText()
{
return Piwik::translate('GoogleAnalyticsImporter_ConfigureTheImporterLabel2')
. '<br />' . Piwik::translate('GoogleAnalyticsImporter_ConfigureTheImporterLabel3', [
'<a href="https://matomo.org/faq/general/set-up-google-analytics-import/" rel="noreferrer noopener" target="_blank">',
'</a>',
]);
}

public static function getGoogleOAuthUrl()
{
$googleAuthUrl = '';
$isConnectAccountsActivated = self::isConnectAccountsPluginActivated();
$authBaseUrl = $isConnectAccountsActivated ? "https://" . StaticContainer::get('CloudAccountsInstanceId') . '/index.php?' : '';
$jwt = Common::getRequestVar('state', '', 'string');
if(empty($jwt) && Piwik::hasUserSuperUserAccess() && $isConnectAccountsActivated) {
// verify an existing user by supplying a jwt too
$jwt = ConnectHelper::buildOAuthStateJwt(SettingsPiwik::getPiwikInstanceId(),
ConnectAccounts::INITIATED_BY_GA);
}
if($isConnectAccountsActivated) {
$googleAuthUrl = $authBaseUrl . Http::buildQuery([
'module' => 'ConnectAccounts',
'action' => 'initiateOauth',
'state' => $jwt,
'strategy' => GoogleConnect::getStrategyName()
]);
}

return $googleAuthUrl;
}

public static function isConnectAccountsPluginActivated()
{
return Manager::getInstance()->isPluginActivated('ConnectAccounts') && ConnectAccounts::isMatomoOAuthEnabled();
}

public function embedGAImportNoData(&$out, $isGA3)
{
Piwik::checkUserHasSomeViewAccess();
$isConnectAccountsPluginActivated = self::isConnectAccountsPluginActivated();
/** @var Authorization $authorization */
$authorization = StaticContainer::get(Authorization::class);
$view = new View("@GoogleAnalyticsImporter/gaImportNoData");
$view->nonce = Nonce::getNonce('GoogleAnalyticsImporter.googleClientConfig', 1200);
$view->auth_nonce = Nonce::getNonce('gaimport.auth', 1200);
$view->isConnectAccountsActivated = $isConnectAccountsPluginActivated;
$view->strategy = $isConnectAccountsPluginActivated && GoogleConnect::isStrategyActive() ? GoogleConnect::getStrategyName() : 'CUSTOM';
$view->radioOptions = self::getRadioOptions();
$view->manualUploadText = self::getManualUploadText();
$view->googleAuthUrl = self::getGoogleOAuthUrl();
$view->isGA3 = $isGA3;
$view->hasClientConfiguration = $authorization->hasClientConfiguration();
$view->isConfigured = $authorization->hasAccessToken();
$view->isNoDataPage = true;
$out .= $view->render();
}
}
Binary file added images/google-analytics.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion javascripts/configureImportNotification.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
};

(async () => {
const response = await fetch('/index.php?' + new URLSearchParams(searchParams));
const response = await fetch(window.piwik.piwik_url + 'index.php?' + new URLSearchParams(searchParams));
const data = await response.json();
if (data.showNotification && data.configureURL) {
showNotification(data.configureURL);
Expand Down
2 changes: 1 addition & 1 deletion javascripts/googleAnalyticsImporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

//?module=CoreAdminHome&action=home&idSite=1&period=day&date=yesterday";
(async () => {
const response = await fetch('/index.php?' + new URLSearchParams(searchParams));
const response = await fetch(window.piwik.piwik_url + 'index.php?' + new URLSearchParams(searchParams));
const data = await response.json();
if ($('.site-without-data').length && data.isGASite) {
displayPendingNotification('', 'successMessage');
Expand Down
18 changes: 17 additions & 1 deletion lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,22 @@
"OauthFailedMessage": "We encountered an issue during the authorization process for importing your GA reports. To try again, please click the button below. If the problem persists, please contact our support team for assistance. They will assist you in resolving the issue and getting your historical GA data imported.",
"ConfigureImportNotificationMessage": "Don't miss out on your valuable historical insights! %1$sImport your Google Analytics data for %2$s%3$s into your Matomo platform now.",
"FutureDateHelp": "The import process has been stopped because it attempted to import data for a future or present date (%1$s). The importer will automatically retry the import tomorrow to ensure that correct and complete data is imported. ",
"GoogleOauthCompleteWarning": "%1$sNote:%2$s You may receive a warning from Google when completing the OAuth process saying \"%1$sGoogle hasn’t verified this app%2$s\". In this case, you can safely continue by clicking on \"%1$sAdvanced%2$s\", and then \"%1$sGo to matomo.cloud (unsafe)%2$s\"."
"GoogleOauthCompleteWarning": "%1$sNote:%2$s You may receive a warning from Google when completing the OAuth process saying \"%1$sGoogle hasn’t verified this app%2$s\". In this case, you can safely continue by clicking on \"%1$sAdvanced%2$s\", and then \"%1$sGo to matomo.cloud (unsafe)%2$s\".",
"NoDataScreenIntro": "Importing your Google Analytics data is easy with Matomo. You can use this to create a backup of your properties and reporting data, and analyse them using Matomo.",
"NoDataScreenOptionsDescription": "You can choose from two options: connecting with your Google Analytics account is the easiest option and works for small and medium traffic websites. If you have many websites or some high-traffic websites, the advanced Google OAuth configuration will allow faster migration of data.",
"NoDataScreenFollowThisSteps": "Follow these steps to set it up:",
"GAImportNoDataScreenStep01": "Download the OAuth credentials from your Google account by following this %1$sguide%2$s.",
"GAImportNoDataScreenStep02": "Upload the OAuth credentials.",
"GAImportNoDataScreenStep03": "Click the \"%1$s\" button (this opens a new tab so you can follow the next steps in this tab).",
"GAImportNoDataScreenStep04": "Navigate to the %1$sGoogle Analytics Import admin page%2$s. %3$sLearn more%4$s.",
"GAImportNoDataScreenStep05": "Select the Import type.",
"GAImportNoDataScreenStep06": "Fill out the Schedule an Import form.",
"GAImportNoDataScreenStep07": "Click \"%1$s\".",
"GAImportNoDataScreenStep07Note": "%1$sNote:%2$s Once you click \"%3$s\", Matomo will automatically create a new Matomo website for each selected property.",
"GAImportNoDataScreenStep08": "Importing data takes time, %1$sclick here to monitor the status of your data import%2$s.",
"GAImportNoDataScreenStep09": "To see your data, refresh this page and then select the newly created Matomo website from the dropdown on the top left.",
"NoDataScreenFollowStepComplete": "%1$sCongratulations!%2$s You have successfully configured your Google Analytics import. As noted earlier, this data is being imported into a new Matomo website. To verify that data is being imported, visit your %3$sGoogle Analytics Import page%4$s in the settings and check that the import job is running.",
"AccountsConnectedSuccessfully": "You have successfully connected your Google account!",
"UploadSuccessful": "Upload successful!"
}
}
69 changes: 69 additions & 0 deletions stylesheets/styles.less
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,73 @@

.importStatusesTable ul li {
list-style-type: disc;
}

#site-without-data {
#ga-import {
.form-group.row {
margin-top: -0.5rem;
margin-bottom: unset;
}

.ga-import-warning {
.alert-warning {
background: @color-orange-brand;
color: white;
&::before {
color: unset;
}
}
}

.radio {
margin-left: 1rem;
}

.btn-quick-connect, .advance-upload-button, .btn-forward-to-Oauth {
margin-left: 1.5rem;
}

.advance-upload-button, .btn-forward-to-Oauth, .btn-quick-connect {
margin-top: 0.5rem;
margin-bottom: 1.2rem;
}

.upload-div {
padding-top: 0.5rem;
}

.p-half-point {
padding-top: 0.5rem;
}

.connected-message-successful {
margin-top: -0.5rem;
display: inline-block;
vertical-align: middle;
margin-left: 1.5rem;

span.icon-ok {
top: 2px;
position: relative;
}
}

#ga3WarningNotification .close {
position: absolute;
/* top: -5px; */
right: 1%;
padding: 0 !important;
background: transparent !important;
border: none !important;
/* float: right; */
font-size: 20px !important;
font-weight: bold;
line-height: 20px !important;
color: inherit !important;
opacity: 0.3;
filter: alpha(opacity=30);
cursor: pointer;
}
}
}
53 changes: 53 additions & 0 deletions templates/gaImportNoData.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{% if isGA3 %}
<div class="ga-import-warning" piwik-alert="warning" id="ga3WarningNotification">
{{ 'GoogleAnalyticsImporter_ConfigureTheImporterHelp'|translate('<strong>', '</strong>')|raw }}
<button type="button" class="close" data-dismiss="alert"> × </button>
</div>
{% endif %}
<div class="right">
<img src="plugins/GoogleAnalyticsImporter/images/google-analytics.png" style="height: 5rem;">
</div>
<p>{{ 'GoogleAnalyticsImporter_NoDataScreenIntro'|translate }}</p>
<br>

{% if isConnectAccountsActivated %}
<p>{{ 'GoogleAnalyticsImporter_NoDataScreenOptionsDescription'|translate }}</p>
<br>
<ul class="list-style-decimal" id="manual-advance-option">
<div vue-entry="ConnectAccounts.ConfigureConnection" manual-config-nonce="{{ nonce }}"
manual-forward-to-auth-nonce="{{ auth_nonce }}"
manual-action-url="{{ linkTo({'action': 'configureClient', 'module': 'GoogleAnalyticsImporter'}) }}"
manual-authorize-url="{{ linkTo({'action': 'forwardToAuth', 'module': 'GoogleAnalyticsImporter'}) }}"
manual-is-configured="{{ isConfigured|json_encode }}"
index-action-url="{{ linkTo({'action': 'index', 'module': 'GoogleAnalyticsImporter'}) }}"
primary-text="{{ 'GoogleAnalyticsImporter_ConfigureTheImporterLabel1'|translate }}"
radio-options="{{ radioOptions|json_encode|e('html_attr') }}"
manual-config-text="{{ manualUploadText|e('html_attr') }}"
connect-accounts-url="{{googleAuthUrl|e('html_attr')}}"
is-no-data-page="true"
has-client-configuration="{{ hasClientConfiguration|json_encode }}"
connect-accounts-btn-text="{{ 'ConnectAccounts_GaImportBtn' |translate}}"
strategy="{{ strategy|json_encode }}"
additional-help-text="{{ 'GoogleAnalyticsImporter_ConfigureTheImporterHelp'|translate('<strong>', '</strong>')|raw }}"></div>
</ul>
{% else %}
<p>{{ 'GoogleAnalyticsImporter_NoDataScreenFollowThisSteps'|translate }}</p>
<ul class="list-style-decimal" id="manual-option">
<div vue-entry="GoogleAnalyticsImporter.ConfigureConnection" config-nonce="{{ nonce }}"
is-no-data-page="true"
is-configured="{{ isConfigured|json_encode }}"
has-client-configuration="{{ hasClientConfiguration|json_encode }}"
forward-to-auth-nonce="{{ auth_nonce }}"
index-action-url="{{ linkTo({'action': 'index', 'module': 'GoogleAnalyticsImporter'}) }}"
action-url="{{ linkTo({'action': 'configureClient', 'module': 'GoogleAnalyticsImporter'}) }}"
strategy="{{ strategy|json_encode }}"
authorize-url="{{ linkTo({'action': 'forwardToAuth', 'module': 'GoogleAnalyticsImporter'}) }}"></div>
</ul>
{% endif %}
<br>
<p>{{ 'GoogleAnalyticsImporter_NoDataScreenFollowStepComplete'|translate('<strong>', '</strong>', '<a href="'~ linkTo({'action': 'index', 'module': 'GoogleAnalyticsImporter'}) ~ '" target="_blank" rel="noreferrer noopener ">', '</a>')|raw }}</p>
<script>
$('body').on('click', '#ga3WarningNotification .close', function(){
$('#ga3WarningNotification').hide();
});
</script>
Loading

0 comments on commit 8e34416

Please sign in to comment.