PageRenderTime 52ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/LocaleDeveloper/class.localedeveloper.plugin.php

https://github.com/Emaratilicious/Addons
PHP | 385 lines | 271 code | 55 blank | 59 comment | 31 complexity | 98c48f64828d214f4abac12e9685bf21 MD5 | raw file
  1. <?php if (!defined('APPLICATION')) exit();
  2. /*
  3. Copyright 2008, 2009 Vanilla Forums Inc.
  4. This file is part of Garden.
  5. Garden is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  6. Garden is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  7. You should have received a copy of the GNU General Public License along with Garden. If not, see <http://www.gnu.org/licenses/>.
  8. Contact Vanilla Forums Inc. at support [at] vanillaforums [dot] com
  9. */
  10. // Define the plugin:
  11. $PluginInfo['LocaleDeveloper'] = array(
  12. 'Name' => 'Locale Developer',
  13. 'Description' => 'Contains useful functions for locale developers. When you enable this plugin go to its settings page to change your options. This plugin is maintained at http://github.com/vanillaforums/Addons',
  14. 'Version' => '1.1',
  15. 'Author' => "Todd Burry",
  16. 'AuthorEmail' => 'todd@vanillaforums.com',
  17. 'AuthorUrl' => 'http://vanillaforums.org/profile/todd',
  18. 'RequiredApplications' => array('Vanilla' => '2.0.11'),
  19. 'SettingsUrl' => '/dashboard/settings/localedeveloper',
  20. 'SettingsPermission' => 'Garden.Site.Manage',
  21. );
  22. if (C('Plugins.LocaleDeveloper.CaptureDefinitions')) {
  23. // Install the developer locale.
  24. $_Locale = new DeveloperLocale(Gdn::Locale()->Current(), C('EnabledApplications'), C('EnabledPlugins'));
  25. $tmp = Gdn::FactoryOverwrite(TRUE);
  26. Gdn::FactoryInstall(Gdn::AliasLocale, 'DeveloperLocale', dirname(__FILE__).DS.'class.developerlocale.php', Gdn::FactorySingleton, $_Locale);
  27. Gdn::FactoryOverwrite($tmp);
  28. unset($tmp);
  29. }
  30. class LocaleDeveloperPlugin extends Gdn_Plugin {
  31. public $LocalePath;
  32. /**
  33. * @var Gdn_Form Form
  34. */
  35. protected $Form;
  36. public function __construct() {
  37. $this->LocalePath = PATH_UPLOADS.'/LocaleDeveloper';
  38. $this->Form = new Gdn_Form();
  39. parent::__construct();
  40. }
  41. /**
  42. * Save the captured definitions.
  43. *
  44. * @param Gdn_Controller $Sender
  45. * @param array $Args
  46. */
  47. public function Base_Render_After($Sender, $Args) {
  48. $Locale = Gdn::Locale();
  49. if (!is_a($Locale, 'DeveloperLocale'))
  50. return;
  51. $Path = $this->LocalePath.'/tmp_'.RandomString(10);
  52. if (!file_exists(dirname($Path)))
  53. mkdir(dirname($Path), 0777, TRUE);
  54. elseif (file_exists($Path)) {
  55. // Load the existing definitions.
  56. $Locale->Load($Path);
  57. }
  58. // Load the ignore file.
  59. $Definition = array();
  60. include dirname(__FILE__).'/ignore.php';
  61. $Ignore = $Definition;
  62. $Definition = array();
  63. // Figure out whether this as admin or regular page.
  64. if (ArrayHasValue($Sender->CssFiles(), 'admin.css')) {
  65. $FinalPath = $this->LocalePath.'/captured_admin.php';
  66. } else {
  67. $FinalPath = $this->LocalePath.'/captured.php';
  68. }
  69. // Load the definitions that have already been captured.
  70. if (file_exists($FinalPath)) {
  71. include $FinalPath;
  72. }
  73. $Definition = array_merge($Definition, $Locale->CapturedDefinitions());
  74. $Definition = array_diff_key($Definition, $Ignore);
  75. // Save the current definitions.
  76. $fp = fopen($Path, 'wb');
  77. fwrite($fp, $this->GetFileHeader());
  78. LocaleModel::WriteDefinitions($fp, $Definition);
  79. fclose($fp);
  80. // Copy the file over the existing one.
  81. $Result = rename($Path, $FinalPath);
  82. }
  83. /**
  84. *
  85. * @param Gdn_Controller $Sender
  86. * @param array $Args
  87. */
  88. public function SettingsController_Render_Before($Sender, $Args) {
  89. if (strcasecmp($Sender->RequestMethod, 'locales') != 0)
  90. return;
  91. // Add a little pointer to the settings.
  92. $Text = '<div class="Info">'.
  93. sprintf(T('Locale Developer Settings %s.'), Anchor(T('here'), '/dashboard/settings/localedeveloper')).
  94. '</div>';
  95. $Sender->AddAsset('Content', $Text, 'LocaleDeveloperLink');
  96. }
  97. /**
  98. *
  99. * @var SettingsController $Sender
  100. */
  101. public function SettingsController_LocaleDeveloper_Create($Sender, $Args) {
  102. $Sender->Permission('Garden.Settings.Manage');
  103. $Sender->AddSideMenu();
  104. $Sender->SetData('Title', T('Locale Developer'));
  105. switch (strtolower(GetValue(0, $Args, ''))) {
  106. case '':
  107. $this->_Settings($Sender, $Args);
  108. break;
  109. case 'download':
  110. $this->_Download($Sender, $Args);
  111. break;
  112. case 'googletranslate':
  113. $this->_GoogleTranslate($Sender, $Args);
  114. break;
  115. }
  116. }
  117. public function _Download($Sender, $Args) {
  118. try {
  119. // Create the zip file.
  120. $Path = $this->CreateZip();
  121. // Serve the zip file.
  122. Gdn_FileSystem::ServeFile($Path, basename($Path), 'application/zip');
  123. } catch (Exception $Ex) {
  124. $this->Form->AddError($Ex);
  125. $this->_Settings($Sender, $Args);
  126. }
  127. }
  128. public function EnsureDefinitionFile() {
  129. $Path = $this->LocalePath.'/definitions.php';
  130. if (file_exists($Path))
  131. unlink($Path);
  132. $Contents = $this->GetFileHeader().self::FormatInfoArray('$LocaleInfo', $this->GetInfoArray());
  133. Gdn_FileSystem::SaveFile($Path, $Contents);
  134. }
  135. public static function FormatInfoArray($VariableName, $Array) {
  136. $VariableName = '$'.trim($VariableName, '$');
  137. $Result = '';
  138. foreach ($Array as $Key => $Value) {
  139. $Result .= $VariableName."['".addcslashes($Key, "'")."'] = ";
  140. $Result .= var_export($Value, TRUE);
  141. $Result .= ";\n\n";
  142. }
  143. return $Result;
  144. }
  145. public static function FormatValue($Value, $SingleLine = TRUE) {
  146. if (is_bool($Value)) {
  147. return $Value ? 'TRUE' : 'FALSE';
  148. } elseif (is_numeric($Value)) {
  149. return (string)$Value;
  150. } elseif (is_string($Value)) {
  151. if ($SingleLine)
  152. return var_export($Value, TRUE);
  153. else
  154. return "'".addcslashes($Value, "'")."'";
  155. } elseif (is_array($Value)) {
  156. $Result = '';
  157. $ArraySep = $SingleLine ? ', ' : ",\n ";
  158. foreach ($Value as $Key => $ArrayValue) {
  159. if (strlen($Result) > 0)
  160. $Result .= $ArraySep;
  161. if ($SingleLine == 'TRUEFALSE')
  162. $SingleLine = FALSE;
  163. $Result .= "'".addcslashes($Key, "'")."' => ".self::FormatValue($ArrayValue, $SingleLine);
  164. }
  165. $Result = 'array('.$Result.')';
  166. return $Result;
  167. } else {
  168. $Error = print_r($Value);
  169. $Error = str_replace('*/', '', $Error);
  170. return "/* Could not format the following value:\n{$Error}\n*/";
  171. }
  172. }
  173. public function GetFileHeader() {
  174. $Now = Gdn_Format::ToDateTime();
  175. $Result = "<?php if (!defined('APPLICATION')) exit();
  176. /** This file was generated by the Locale Developer plugin on $Now **/\n\n";
  177. return $Result;
  178. }
  179. public function GetInfoArray() {
  180. $Info = C('Plugins.LocaleDeveloper');
  181. foreach ($Info as $Key => $Value) {
  182. if (!$Value)
  183. unset($Info[$Key]);
  184. }
  185. $InfoArray = array(GetValue('Key', $Info, 'LocaleDeveloper') => array(
  186. 'Locale' => GetValue('Locale', $Info, Gdn::Locale()->Current()),
  187. 'Name' => GetValue('Name', $Info, 'Locale Developer'),
  188. 'Description' => 'Automatically gernerated by the Locale Developer plugin.',
  189. 'Version' => '0.1a',
  190. 'Author' => "Your Name",
  191. 'AuthorEmail' => 'Your Email',
  192. 'AuthorUrl' => 'http://your.domain.com',
  193. 'License' => 'Your choice of license'
  194. ));
  195. return $InfoArray;
  196. }
  197. public function _GoogleTranslate($Sender, $Args) {
  198. $Sender->Form = $this->Form;
  199. if ($this->Form->IsPostBack()) {
  200. exit('Foo');
  201. } else {
  202. // Load all of the definitions.
  203. //$Definitions = $this->LoadDefinitions();
  204. //$Sender->SetData('Definitions', $Definitions);
  205. }
  206. $Sender->Render('googletranslate', '', 'plugins/LocaleDeveloper');
  207. }
  208. // public function LoadDefinitions($Path = NULL) {
  209. // if ($Path === NULL)
  210. // $Path = $this->LocalePath;
  211. //
  212. // $Paths = SafeGlob($Path.'/*.php');
  213. // $Definition = array();
  214. // foreach ($Paths as $Path) {
  215. // // Skip the locale developer's changes file.
  216. // if ($Path == $this->LocalePath && basename($Path) == 'changes.php')
  217. // continue;
  218. // include $Path;
  219. // }
  220. // return $Definition;
  221. // }
  222. public function _Settings($Sender, $Args) {
  223. $Sender->Form = $this->Form;
  224. // Grab the existing locale packs.
  225. $LocaleModel = new LocaleModel();
  226. $LocalePacks = $LocaleModel->AvailableLocalePacks();
  227. $LocalArray = array();
  228. foreach ($LocalePacks as $Key => $Info) {
  229. $LocaleArray[$Key] = GetValue('Name', $Info, $Key);
  230. }
  231. $Sender->SetData('LocalePacks', $LocaleArray);
  232. if ($this->Form->IsPostBack()) {
  233. if ($this->Form->GetFormValue('Save')) {
  234. $Values = ArrayTranslate($this->Form->FormValues(), array('Key', 'Name', 'Locale', 'CaptureDefinitions'));
  235. $SaveValues = array();
  236. foreach ($Values as $Key => $Value) {
  237. $SaveValues['Plugins.LocaleDeveloper.'.$Key] = $Value;
  238. }
  239. // Save the settings.
  240. SaveToConfig($SaveValues, '', array('RemoveEmpty' => TRUE));
  241. $Sender->StatusMessage = T('Your changes have been saved.');
  242. } elseif ($this->Form->GetFormValue('GenerateChanges')) {
  243. $Key = $this->Form->GetFormValue('LocalePackForChanges');
  244. if (!$Key)
  245. $this->Form->AddError('ValidateRequired', 'Locale Pack');
  246. $Path = PATH_ROOT.'/locales/'.$Key;
  247. if (!file_exists($Path))
  248. $this->Form->AddError('Could not find the selected locale pack.');
  249. if ($this->Form->ErrorCount() == 0) {
  250. try {
  251. $LocaleModel->GenerateChanges($Path, $this->LocalePath);
  252. $Sender->StatusMessage = T('Your changes have been saved.');
  253. } catch (Exception $Ex) {
  254. $this->Form->AddError($Ex);
  255. }
  256. }
  257. } elseif ($this->Form->GetFormValue('Copy')) {
  258. $Key = $this->Form->GetFormValue('LocalePackForCopy');
  259. if (!$Key)
  260. $this->Form->AddError('ValidateRequired', 'Locale Pack');
  261. $Path = PATH_ROOT.'/locales/'.$Key;
  262. if (!file_exists($Path))
  263. $this->Form->AddError('Could not find the selected locale pack.');
  264. if ($this->Form->ErrorCount() == 0) {
  265. try {
  266. $LocaleModel->CopyDefinitions($Path, $this->LocalePath.'/copied.php');
  267. $Sender->StatusMessage = T('Your changes have been saved.');
  268. } catch (Exception $Ex) {
  269. $this->Form->AddError($Ex);
  270. }
  271. }
  272. } elseif ($this->Form->GetFormValue('Remove')) {
  273. $Files = SafeGlob($this->LocalePath.'/*');
  274. foreach ($Files as $File) {
  275. $Result = unlink($File);
  276. if (!$Result) {
  277. $this->Form->AddError('@'.sprintf(T('Could not remove %s.'), $File));
  278. }
  279. }
  280. if ($this->Form->ErrorCount() == 0)
  281. $Sender->StatusMessage = T('Your changes have been saved.');
  282. }
  283. } else {
  284. $Values = C('Plugins.LocaleDeveloper');
  285. foreach ($Values as $Key => $Value) {
  286. $this->Form->SetFormValue($Key, $Value);
  287. }
  288. }
  289. $Sender->SetData('LocalePath', $this->LocalePath);
  290. $Sender->Render('', '', 'plugins/LocaleDeveloper');
  291. }
  292. public function WriteInfoArray($fp) {
  293. $Info = C('Plugins.LocaleDeveloper');
  294. // Write the info array.
  295. $InfoArray = $this->GetInfoArray();
  296. $InfoString = self::FormatInfoArray('$LocaleInfo', $InfoArray);
  297. fwrite($fp, $InfoString);
  298. }
  299. public function CreateZip() {
  300. if (!class_exists('ZipArchive')) {
  301. throw new Exception('Your server does not support zipping files.', 400);
  302. }
  303. $Info = $this->GetInfoArray();
  304. $this->EnsureDefinitionFile();
  305. // Get the basename of the locale.
  306. $Key = key($Info);
  307. $ZipPath = PATH_UPLOADS."/$Key.zip";
  308. $TmpPath = PATH_UPLOADS."/tmp_".RandomString(10);
  309. $Zip = new ZipArchive();
  310. $Zip->open($TmpPath, ZIPARCHIVE::CREATE);
  311. // Add all of the files in the locale to the zip.
  312. $Files = SafeGlob(rtrim($this->LocalePath, '/').'/*.*', array('php', 'txt'));
  313. foreach ($Files as $File) {
  314. $LocalPath = $Key.'/'.basename($File);
  315. $Zip->addFile($File, $LocalPath);
  316. }
  317. $Zip->close();
  318. rename($TmpPath, $ZipPath);
  319. return $ZipPath;
  320. }
  321. }