Skip to content

Commit

Permalink
throw an exception in case a plugin contains a malformed json transla…
Browse files Browse the repository at this point in the history
…tion file
  • Loading branch information
tsteur committed Oct 22, 2013
1 parent 7090ace commit 0e03cf5
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 4 deletions.
35 changes: 35 additions & 0 deletions core/Common.php
Expand Up @@ -584,6 +584,41 @@ public static function json_decode($json, $assoc = false)
return json_decode($json, $assoc);
}

/**
* Detects whether an error occurred during the last json encode/decode.
* @return bool
*/
public static function hasJsonErrorOccurred()
{
return json_last_error() != JSON_ERROR_NONE;
}

/**
* Returns a human readable error message in case an error occcurred during the last json encode/decode.
* Returns an empty string in case there was no error.
*
* @return string
*/
public static function getLastJsonError()
{
switch (json_last_error()) {
case JSON_ERROR_NONE:
return '';
case JSON_ERROR_DEPTH:
return 'Maximum stack depth exceeded';
case JSON_ERROR_STATE_MISMATCH:
return 'Underflow or the modes mismatch';
case JSON_ERROR_CTRL_CHAR:
return 'Unexpected control character found';
case JSON_ERROR_SYNTAX:
return 'Syntax error, malformed JSON';
case JSON_ERROR_UTF8:
return 'Malformed UTF-8 characters, possibly incorrectly encoded';
}

return 'Unknown error';
}

/**
* Returns the list of parent classes for the given class.
*
Expand Down
28 changes: 24 additions & 4 deletions core/Plugin/Manager.php
Expand Up @@ -11,6 +11,7 @@

namespace Piwik\Plugin;

use Piwik\Common;
use Piwik\Config as PiwikConfig;
use Piwik\EventDispatcher;
use Piwik\Filesystem;
Expand Down Expand Up @@ -742,11 +743,9 @@ private function loadTranslation($plugin, $langCode)
$defaultEnglishLangPath = sprintf($path, 'en');

if (file_exists($defaultLangPath)) {
$data = file_get_contents($defaultLangPath);
$translations = json_decode($data, true);
$translations = $this->getTranslationsFromFile($defaultLangPath);
} elseif (file_exists($defaultEnglishLangPath)) {
$data = file_get_contents($defaultEnglishLangPath);
$translations = json_decode($data, true);
$translations = $this->getTranslationsFromFile($defaultEnglishLangPath);
} else {
return false;
}
Expand Down Expand Up @@ -897,6 +896,27 @@ private function removePluginFromTrackerConfig($pluginName)
}
}
}

/**
* @param string $pathToTranslationFile
* @throws \Exception
* @return mixed
*/
private function getTranslationsFromFile($pathToTranslationFile)
{
$data = file_get_contents($pathToTranslationFile);
$translations = json_decode($data, true);

if (is_null($translations) && Common::hasJsonErrorOccurred()) {
$jsonError = Common::getLastJsonError();

$message = sprintf('Not able to load translation file %s: %s', $pathToTranslationFile, $jsonError);

throw new \Exception($message);
}

return $translations;
}
}

/**
Expand Down

0 comments on commit 0e03cf5

Please sign in to comment.