[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/plugins/sampledata/multilang/ -> multilang.php (source)

   1  <?php
   2  
   3  /**
   4   * @package     Joomla.Plugin
   5   * @subpackage  Sampledata.Multilang
   6   *
   7   * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
   8   * @license     GNU General Public License version 2 or later; see LICENSE.txt
   9  
  10   * @phpcs:disable PSR1.Classes.ClassDeclaration.MissingNamespace
  11   */
  12  
  13  use Joomla\CMS\Application\ApplicationHelper;
  14  use Joomla\CMS\Component\ComponentHelper;
  15  use Joomla\CMS\Extension\ExtensionHelper;
  16  use Joomla\CMS\Factory;
  17  use Joomla\CMS\Installer\Installer;
  18  use Joomla\CMS\Language\Language;
  19  use Joomla\CMS\Language\LanguageHelper;
  20  use Joomla\CMS\Language\Text;
  21  use Joomla\CMS\Plugin\CMSPlugin;
  22  use Joomla\CMS\Session\Session;
  23  use Joomla\CMS\Table\Table;
  24  use Joomla\CMS\Workflow\Workflow;
  25  use Joomla\Database\Exception\ExecutionFailureException;
  26  use Joomla\Database\ParameterType;
  27  
  28  // phpcs:disable PSR1.Files.SideEffects
  29  \defined('_JEXEC') or die;
  30  // phpcs:enable PSR1.Files.SideEffects
  31  
  32  /**
  33   * Sampledata - Multilang Plugin
  34   *
  35   * @since  4.0.0
  36   */
  37  class PlgSampledataMultilang extends CMSPlugin
  38  {
  39      /**
  40       * @var     \Joomla\Database\DatabaseDriver
  41       *
  42       * @since   4.0.0
  43       */
  44      protected $db;
  45  
  46      /**
  47       * @var     \Joomla\CMS\Application\CMSApplication
  48       *
  49       * @since   4.0.0
  50       */
  51      protected $app;
  52  
  53      /**
  54       * Affects constructor behavior. If true, language files will be loaded automatically.
  55       *
  56       * @var     boolean
  57       *
  58       * @since   4.0.0
  59       */
  60      protected $autoloadLanguage = true;
  61  
  62      /**
  63       * @var     string
  64       *
  65       * @since   4.0.0
  66       */
  67      protected $path = null;
  68  
  69      /**
  70       * @var    integer Id, author of all generated content.
  71       *
  72       * @since   4.0.0
  73       */
  74      protected $adminId;
  75  
  76      /**
  77       * Get an overview of the proposed sampledata.
  78       *
  79       * @return  stdClass|void  Will be converted into the JSON response to the module.
  80       *
  81       * @since   4.0.0
  82       */
  83      public function onSampledataGetOverview()
  84      {
  85          if (!$this->app->getIdentity()->authorise('core.create', 'com_content')) {
  86              return;
  87          }
  88  
  89          $data              = new stdClass();
  90          $data->name        = $this->_name;
  91          $data->title       = Text::_('PLG_SAMPLEDATA_MULTILANG_OVERVIEW_TITLE');
  92          $data->description = Text::_('PLG_SAMPLEDATA_MULTILANG_OVERVIEW_DESC');
  93          $data->icon        = 'wifi';
  94          $data->steps       = 8;
  95  
  96          return $data;
  97      }
  98  
  99      /**
 100       * First step to enable the Language filter plugin.
 101       *
 102       * @return  array|void  Will be converted into the JSON response to the module.
 103       *
 104       * @since   4.0.0
 105       */
 106      public function onAjaxSampledataApplyStep1()
 107      {
 108          if (!Session::checkToken('get') || $this->app->input->get('type') != $this->_name) {
 109              return;
 110          }
 111  
 112          $languages = LanguageHelper::getContentLanguages(array(0, 1));
 113  
 114          if (count($languages) < 2) {
 115              $response            = array();
 116              $response['success'] = false;
 117              $response['message'] = Text::_('PLG_SAMPLEDATA_MULTILANG_MISSING_LANGUAGE');
 118  
 119              return $response;
 120          }
 121  
 122          if (!$this->enablePlugin('plg_system_languagefilter')) {
 123              $response            = array();
 124              $response['success'] = false;
 125  
 126              $lang = $this->app->getLanguage();
 127              $lang->load('plg_system_languagefilter', JPATH_ADMINISTRATOR);
 128              $message = $lang->_('PLG_SYSTEM_LANGUAGEFILTER');
 129  
 130              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_LANGFILTER', 2, $message);
 131  
 132              return $response;
 133          }
 134  
 135          $response            = [];
 136          $response['success'] = true;
 137          $response['message'] = Text::_('PLG_SAMPLEDATA_MULTILANG_STEP1_SUCCESS');
 138  
 139          return $response;
 140      }
 141  
 142      /**
 143       * Second step to add a language switcher module
 144       *
 145       * @return  array|void  Will be converted into the JSON response to the module.
 146       *
 147       * @since   4.0.0
 148       */
 149      public function onAjaxSampledataApplyStep2()
 150      {
 151          if (!Session::checkToken('get') || $this->app->input->get('type') != $this->_name) {
 152              return;
 153          }
 154  
 155          if (!ComponentHelper::isEnabled('com_modules') || !$this->app->getIdentity()->authorise('core.create', 'com_modules')) {
 156              $response            = array();
 157              $response['success'] = true;
 158              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_STEP_SKIPPED', 2, 'com_modules');
 159  
 160              return $response;
 161          }
 162  
 163          if (!$this->addModuleLanguageSwitcher()) {
 164              $response            = array();
 165              $response['success'] = false;
 166  
 167              $lang = $this->app->getLanguage();
 168              $lang->load('mod_languages', JPATH_SITE);
 169              $message = $lang->_('MOD_LANGUAGES');
 170  
 171              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_SWITCHER', 2, $message);
 172  
 173              return $response;
 174          }
 175  
 176          $response            = [];
 177          $response['success'] = true;
 178          $response['message'] = Text::_('PLG_SAMPLEDATA_MULTILANG_STEP2_SUCCESS');
 179  
 180          return $response;
 181      }
 182  
 183      /**
 184       * Third step to make sure all content languages are published
 185       *
 186       * @return  array|void  Will be converted into the JSON response to the module.
 187       *
 188       * @since   4.0.0
 189       */
 190      public function onAjaxSampledataApplyStep3()
 191      {
 192          if (!Session::checkToken('get') || $this->app->input->get('type') != $this->_name) {
 193              return;
 194          }
 195  
 196          if (!ComponentHelper::isEnabled('com_languages')) {
 197              $response            = array();
 198              $response['success'] = true;
 199              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_STEP_SKIPPED', 3, 'com_languages');
 200  
 201              return $response;
 202          }
 203  
 204          if (!$this->publishContentLanguages()) {
 205              $response            = array();
 206              $response['success'] = false;
 207              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_CONTENTLANGUAGES', 3);
 208  
 209              return $response;
 210          }
 211  
 212          $response            = [];
 213          $response['success'] = true;
 214          $response['message'] = Text::_('PLG_SAMPLEDATA_MULTILANG_STEP3_SUCCESS');
 215  
 216          return $response;
 217      }
 218  
 219      /**
 220       * Fourth step to create Menus and list all categories menu items
 221       *
 222       * @return  array|void  Will be converted into the JSON response to the module.
 223       *
 224       * @since   4.0.0
 225       */
 226      public function onAjaxSampledataApplyStep4()
 227      {
 228          if (!Session::checkToken('get') || $this->app->input->get('type') != $this->_name) {
 229              return;
 230          }
 231  
 232          if (!ComponentHelper::isEnabled('com_menus') || !$this->app->getIdentity()->authorise('core.create', 'com_menus')) {
 233              $response            = array();
 234              $response['success'] = true;
 235              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_STEP_SKIPPED', 4, 'com_menus');
 236  
 237              return $response;
 238          }
 239  
 240          $siteLanguages = $this->getInstalledlangsFrontend();
 241  
 242          foreach ($siteLanguages as $siteLang) {
 243              if (!$this->addMenuGroup($siteLang)) {
 244                  $response            = array();
 245                  $response['success'] = false;
 246                  $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_MENUS', 4, $siteLang->language);
 247  
 248                  return $response;
 249              }
 250  
 251              if (!$tableMenuItem = $this->addAllCategoriesMenuItem($siteLang)) {
 252                  $response            = array();
 253                  $response['success'] = false;
 254                  $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_ALLCATEGORIES', 4, $siteLang->language);
 255  
 256                  return $response;
 257              }
 258  
 259              $groupedAssociations['com_menus.item'][$siteLang->language] = $tableMenuItem->id;
 260          }
 261  
 262          if (!$this->addAssociations($groupedAssociations)) {
 263              $response            = array();
 264              $response['success'] = false;
 265              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_ASSOC_ALLCATEGORIES', 4);
 266  
 267              return $response;
 268          }
 269  
 270          $response            = [];
 271          $response['success'] = true;
 272          $response['message'] = Text::_('PLG_SAMPLEDATA_MULTILANG_STEP4_SUCCESS');
 273  
 274          return $response;
 275      }
 276  
 277      /**
 278       * Fifth step to add menu modules
 279       *
 280       * @return  array|void  Will be converted into the JSON response to the module.
 281       *
 282       * @since   4.0.0
 283       */
 284      public function onAjaxSampledataApplyStep5()
 285      {
 286          if (!Session::checkToken('get') || $this->app->input->get('type') != $this->_name) {
 287              return;
 288          }
 289  
 290          if (!ComponentHelper::isEnabled('com_modules') || !$this->app->getIdentity()->authorise('core.create', 'com_modules')) {
 291              $response            = array();
 292              $response['success'] = true;
 293              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_STEP_SKIPPED', 5, 'com_modules');
 294  
 295              return $response;
 296          }
 297  
 298          $siteLanguages = $this->getInstalledlangsFrontend();
 299  
 300          foreach ($siteLanguages as $siteLang) {
 301              if (!$this->addModuleMenu($siteLang)) {
 302                  $response            = array();
 303                  $response['success'] = false;
 304                  $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_MENUMODULES', 5, $siteLang->language);
 305  
 306                  return $response;
 307              }
 308          }
 309  
 310          $response            = [];
 311          $response['success'] = true;
 312          $response['message'] = Text::_('PLG_SAMPLEDATA_MULTILANG_STEP5_SUCCESS');
 313  
 314          return $response;
 315      }
 316  
 317      /**
 318       * Sixth step to add workflow, categories, articles and blog menu items
 319       *
 320       * @return  array|void  Will be converted into the JSON response to the module.
 321       *
 322       * @since   4.0.0
 323       */
 324      public function onAjaxSampledataApplyStep6()
 325      {
 326          if (!Session::checkToken('get') || $this->app->input->get('type') != $this->_name) {
 327              return;
 328          }
 329  
 330          if (!ComponentHelper::isEnabled('com_content') || !$this->app->getIdentity()->authorise('core.create', 'com_content')) {
 331              $response            = array();
 332              $response['success'] = true;
 333              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_STEP_SKIPPED', 6, 'com_content');
 334  
 335              return $response;
 336          }
 337  
 338          if (!ComponentHelper::isEnabled('com_categories') || !$this->app->getIdentity()->authorise('core.create', 'com_content.category')) {
 339              $response            = array();
 340              $response['success'] = true;
 341              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_STEP_SKIPPED', 6, 'com_categories');
 342  
 343              return $response;
 344          }
 345  
 346          $siteLanguages = $this->getInstalledlangsFrontend();
 347  
 348          ComponentHelper::getParams('com_content')->set('workflow_enabled', 0);
 349  
 350          foreach ($siteLanguages as $siteLang) {
 351              if (!$tableCategory = $this->addCategory($siteLang)) {
 352                  $response            = array();
 353                  $response['success'] = false;
 354                  $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_CATEGORY', 6, $siteLang->language);
 355  
 356                  return $response;
 357              }
 358  
 359              $groupedAssociations['com_categories.item'][$siteLang->language] = $tableCategory->id;
 360  
 361              if (!$tableArticle = $this->addArticle($siteLang, $tableCategory->id)) {
 362                  $response            = array();
 363                  $response['success'] = false;
 364                  $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_ARTICLE', 6, $siteLang->language);
 365  
 366                  return $response;
 367              }
 368  
 369              $groupedAssociations['com_content.item'][$siteLang->language] = $tableArticle->id;
 370  
 371              if (!$tableMenuItem = $this->addBlogMenuItem($siteLang, $tableCategory->id)) {
 372                  $response            = array();
 373                  $response['success'] = false;
 374                  $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_BLOG', 6, $siteLang->language);
 375  
 376                  return $response;
 377              }
 378  
 379              $groupedAssociations['com_menus.item'][$siteLang->language] = $tableMenuItem->id;
 380          }
 381  
 382          if (!$this->addAssociations($groupedAssociations)) {
 383              $response            = array();
 384              $response['success'] = false;
 385              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_ASSOC_VARIOUS', 6);
 386  
 387              return $response;
 388          }
 389  
 390          $response            = [];
 391          $response['success'] = true;
 392          $response['message'] = Text::_('PLG_SAMPLEDATA_MULTILANG_STEP6_SUCCESS');
 393  
 394          return $response;
 395      }
 396  
 397      /**
 398       * Seventh step to disable the mainmenu module whose home page is set to All languages.
 399       *
 400       * @return  array|void  Will be converted into the JSON response to the module.
 401       *
 402       * @since   4.0.0
 403       */
 404      public function onAjaxSampledataApplyStep7()
 405      {
 406          if (!Session::checkToken('get') || $this->app->input->get('type') != $this->_name) {
 407              return;
 408          }
 409  
 410          if (!ComponentHelper::isEnabled('com_modules')) {
 411              $response            = array();
 412              $response['success'] = true;
 413              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_STEP_SKIPPED', 7, 'com_modules');
 414  
 415              return $response;
 416          }
 417  
 418          if (!$this->disableModuleMainMenu()) {
 419              $response            = array();
 420              $response['success'] = false;
 421              $response['message'] = Text::sprintf('PLG_SAMPLEDATA_MULTILANG_ERROR_MAINMENU_MODULE', 7);
 422  
 423              return $response;
 424          }
 425  
 426          $response            = [];
 427          $response['success'] = true;
 428          $response['message'] = Text::_('PLG_SAMPLEDATA_MULTILANG_STEP7_SUCCESS');
 429  
 430          return $response;
 431      }
 432  
 433      /**
 434       * Final step to show completion of sampledata.
 435       *
 436       * @return  array|void  Will be converted into the JSON response to the module.
 437       *
 438       * @since  4.0.0
 439       */
 440      public function onAjaxSampledataApplyStep8()
 441      {
 442          if ($this->app->input->get('type') !== $this->_name) {
 443              return;
 444          }
 445  
 446          $response['success'] = true;
 447          $response['message'] = Text::_('PLG_SAMPLEDATA_MULTILANG_STEP8_SUCCESS');
 448  
 449          return $response;
 450      }
 451  
 452      /**
 453       * Enable a Joomla plugin.
 454       *
 455       * @param   string  $pluginName  The name of plugin.
 456       *
 457       * @return  boolean
 458       *
 459       * @since   4.0.0
 460       */
 461      private function enablePlugin($pluginName)
 462      {
 463          // Create a new db object.
 464          $db    = $this->db;
 465          $query = $db->getQuery(true);
 466  
 467          $query
 468              ->update($db->quoteName('#__extensions'))
 469              ->set($db->quoteName('enabled') . ' = 1')
 470              ->where($db->quoteName('name') . ' = :pluginname')
 471              ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
 472              ->bind(':pluginname', $pluginName);
 473  
 474          $db->setQuery($query);
 475  
 476          try {
 477              $db->execute();
 478          } catch (ExecutionFailureException $e) {
 479              return false;
 480          }
 481  
 482          // Store language filter plugin parameters.
 483          if ($pluginName == 'plg_system_languagefilter') {
 484              $params = '{'
 485                  . '"detect_browser":"0",'
 486                  . '"automatic_change":"1",'
 487                  . '"item_associations":"1",'
 488                  . '"remove_default_prefix":"0",'
 489                  . '"lang_cookie":"0",'
 490                  . '"alternate_meta":"1"'
 491                  . '}';
 492              $query
 493                  ->clear()
 494                  ->update($db->quoteName('#__extensions'))
 495                  ->set($db->quoteName('params') . ' = :params')
 496                  ->where($db->quoteName('name') . ' = ' . $db->quote('plg_system_languagefilter'))
 497                  ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
 498                  ->bind(':params', $params);
 499  
 500              $db->setQuery($query);
 501  
 502              try {
 503                  $db->execute();
 504              } catch (ExecutionFailureException $e) {
 505                  return false;
 506              }
 507          }
 508  
 509          return true;
 510      }
 511  
 512      /**
 513       * Disable Default Main Menu Module.
 514       *
 515       * @return  boolean
 516       *
 517       * @since   4.0.0
 518       */
 519      private function disableModuleMainMenu()
 520      {
 521          // Create a new db object.
 522          $db    = $this->db;
 523          $query = $db->getQuery(true);
 524  
 525          // Disable main menu module with Home set to ALL languages.
 526          $query
 527              ->update($db->quoteName('#__modules'))
 528              ->set($db->quoteName('published') . ' = 0')
 529              ->where(
 530                  [
 531                      $db->quoteName('client_id') . ' = 0',
 532                      $db->quoteName('module') . ' = ' . $db->quote('mod_menu'),
 533                      $db->quoteName('language') . ' = ' . $db->quote('*'),
 534                      $db->quoteName('position') . ' = ' . $db->quote('sidebar-right'),
 535                  ]
 536              );
 537          $db->setQuery($query);
 538  
 539          try {
 540              $db->execute();
 541          } catch (ExecutionFailureException $e) {
 542              return false;
 543          }
 544  
 545          return true;
 546      }
 547  
 548      /**
 549       * Enable the Language Switcher Module.
 550       *
 551       * @return  boolean
 552       *
 553       * @since   4.0.0
 554       */
 555      private function addModuleLanguageSwitcher()
 556      {
 557          $tableModule = Table::getInstance('Module', 'Joomla\\CMS\\Table\\');
 558  
 559          $moduleData  = array(
 560              'id'        => 0,
 561              'title'     => 'Language Switcher',
 562              'note'      => '',
 563              'content'   => '',
 564              'position'  => 'sidebar-right',
 565              'module'    => 'mod_languages',
 566              'access'    => 1,
 567              'showtitle' => 0,
 568              'params'    =>
 569                  '{"header_text":"","footer_text":"","dropdown":"0","image":"1","inline":"1","show_active":"1",'
 570                  . '"full_name":"1","layout":"_:default","moduleclass_sfx":"","cache":"0","cache_time":"900","cachemode":"itemid",'
 571                  . '"module_tag":"div","bootstrap_size":"0","header_tag":"h3","header_class":"","style":"0"}',
 572              'client_id' => 0,
 573              'language'  => '*',
 574              'published' => 1,
 575              'rules'     => array(),
 576          );
 577  
 578          // Bind the data.
 579          if (!$tableModule->bind($moduleData)) {
 580              return false;
 581          }
 582  
 583          // Check the data.
 584          if (!$tableModule->check()) {
 585              return false;
 586          }
 587  
 588          // Store the data.
 589          if (!$tableModule->store()) {
 590              return false;
 591          }
 592  
 593          return $this->addModuleInModuleMenu((int) $tableModule->id);
 594      }
 595  
 596      /**
 597       * Add Module Menu.
 598       *
 599       * @param   stdClass  $itemLanguage  Language Object.
 600       *
 601       * @return  boolean
 602       *
 603       * @since   4.0.0
 604       */
 605      private function addModuleMenu($itemLanguage)
 606      {
 607          $tableModule = Table::getInstance('Module', 'Joomla\\CMS\\Table\\');
 608          $title = 'Main menu ' . $itemLanguage->language;
 609  
 610          $moduleData = array(
 611              'id'        => 0,
 612              'title'     => $title,
 613              'note'      => '',
 614              'content'   => '',
 615              'position'  => 'sidebar-right',
 616              'module'    => 'mod_menu',
 617              'access'    => 1,
 618              'showtitle' => 1,
 619              'params'    => '{"menutype":"mainmenu-' . strtolower($itemLanguage->language)
 620                  . '","startLevel":"0","endLevel":"0","showAllChildren":"0","tag_id":"","class_sfx":"","window_open":"",'
 621                  . '"layout":"","moduleclass_sfx":"","cache":"1","cache_time":"900","cachemode":"itemid"}',
 622              'client_id' => 0,
 623              'language'  => $itemLanguage->language,
 624              'published' => 1,
 625              'rules' => array(),
 626          );
 627  
 628          // Bind the data.
 629          if (!$tableModule->bind($moduleData)) {
 630              return false;
 631          }
 632  
 633          // Check the data.
 634          if (!$tableModule->check()) {
 635              return false;
 636          }
 637  
 638          // Store the data.
 639          if (!$tableModule->store()) {
 640              return false;
 641          }
 642  
 643          return $this->addModuleInModuleMenu((int) $tableModule->id);
 644      }
 645  
 646      /**
 647       * Add Menu Group.
 648       *
 649       * @param   stdClass  $itemLanguage  Language Object.
 650       *
 651       * @return  boolean
 652       *
 653       * @since   4.0.0
 654       */
 655      private function addMenuGroup($itemLanguage)
 656      {
 657          // Add Menu Group.
 658          $menuTable = $this->app->bootComponent('com_menus')->getMVCFactory()->createTable('MenuType', 'Administrator', ['dbo' => $this->db]);
 659  
 660          $menuData = array(
 661              'id'          => 0,
 662              'menutype'    => 'mainmenu-' . strtolower($itemLanguage->language),
 663              'title'       => 'Main Menu (' . $itemLanguage->language . ')',
 664              'description' => 'The main menu for the site in language ' . $itemLanguage->name,
 665          );
 666  
 667          // Bind the data.
 668          if (!$menuTable->bind($menuData)) {
 669              return false;
 670          }
 671  
 672          // Check the data.
 673          if (!$menuTable->check()) {
 674              return false;
 675          }
 676  
 677          // Store the data.
 678          if (!$menuTable->store()) {
 679              return false;
 680          }
 681  
 682          return true;
 683      }
 684  
 685      /**
 686       * Add List All Categories Menu Item for new router.
 687       *
 688       * @param   stdClass  $itemLanguage  Language Object.
 689       *
 690       * @return  Table|boolean Menu Item Object. False otherwise.
 691       *
 692       * @since   4.0.0
 693       */
 694      private function addAllCategoriesMenuItem($itemLanguage)
 695      {
 696          // Add Menu Item.
 697          $tableItem = $this->app->bootComponent('com_menus')->getMVCFactory()->createTable('Menu', 'Administrator', ['dbo' => $this->db]);
 698  
 699          $newlanguage = new Language($itemLanguage->language, false);
 700          $newlanguage->load('joomla', JPATH_ADMINISTRATOR, $itemLanguage->language, true);
 701          $title = $newlanguage->_('JCATEGORIES');
 702          $alias = 'allcategories_' . $itemLanguage->language;
 703  
 704          $menuItem = array(
 705              'title'        => $title,
 706              'alias'        => $alias,
 707              'menutype'     => 'mainmenu-' . strtolower($itemLanguage->language),
 708              'type'         => 'component',
 709              'link'         => 'index.php?option=com_content&view=categories&id=0',
 710              'component_id' => ExtensionHelper::getExtensionRecord('com_content', 'component')->extension_id,
 711              'published'    => 1,
 712              'parent_id'    => 1,
 713              'level'        => 1,
 714              'home'         => 0,
 715              'params'       => '{"show_base_description":"","categories_description":"","maxLevelcat":"",'
 716                  . '"show_empty_categories_cat":"","show_subcat_desc_cat":"","show_cat_num_articles_cat":"",'
 717                  . '"show_category_title":"","show_description":"","show_description_image":"","maxLevel":"",'
 718                  . '"show_empty_categories":"","show_no_articles":"","show_subcat_desc":"","show_cat_num_articles":"",'
 719                  . '"num_leading_articles":"","num_intro_articles":"","num_links":"",'
 720                  . '"show_subcategory_content":"","orderby_pri":"","orderby_sec":"",'
 721                  . '"order_date":"","show_pagination_limit":"","filter_field":"","show_headings":"",'
 722                  . '"list_show_date":"","date_format":"","list_show_hits":"","list_show_author":"","display_num":"10",'
 723                  . '"show_pagination":"","show_pagination_results":"","article_layout":"_:default","show_title":"",'
 724                  . '"link_titles":"","show_intro":"","show_category":"","link_category":"","show_parent_category":"",'
 725                  . '"link_parent_category":"","show_author":"","link_author":"","show_create_date":"",'
 726                  . '"show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_vote":"",'
 727                  . '"show_readmore":"","show_readmore_title":"","show_hits":"","show_noauth":"","show_feed_link":"",'
 728                  . '"feed_summary":"","menu-anchor_title":"","menu-anchor_css":"","menu_image":"","menu_image_css":"",'
 729                  . '"menu_text":1,"menu_show":0,"page_title":"","show_page_heading":"","page_heading":"",'
 730                  . '"pageclass_sfx":"","menu-meta_description":"","robots":""}',
 731              'language'     => $itemLanguage->language,
 732          );
 733  
 734          // Bind the data.
 735          if (!$tableItem->bind($menuItem)) {
 736              return false;
 737          }
 738  
 739          $tableItem->setLocation($menuItem['parent_id'], 'last-child');
 740  
 741          // Check the data.
 742          if (!$tableItem->check()) {
 743              return false;
 744          }
 745  
 746          // Store the data.
 747          if (!$tableItem->store()) {
 748              return false;
 749          }
 750  
 751          // Rebuild the tree path.
 752          if (!$tableItem->rebuildPath($tableItem->id)) {
 753              return false;
 754          }
 755  
 756          return $tableItem;
 757      }
 758  
 759      /**
 760       * Add Blog Menu Item.
 761       *
 762       * @param   stdClass  $itemLanguage  Language Object.
 763       * @param   integer   $categoryId    The id of the category displayed by the blog.
 764       *
 765       * @return  Table|boolean Menu Item Object. False otherwise.
 766       *
 767       * @since   4.0.0
 768       */
 769      private function addBlogMenuItem($itemLanguage, $categoryId)
 770      {
 771          // Add Menu Item.
 772          $tableItem = $this->app->bootComponent('com_menus')->getMVCFactory()->createTable('Menu', 'Administrator', ['dbo' => $this->db]);
 773  
 774          $newlanguage = new Language($itemLanguage->language, false);
 775          $newlanguage->load('com_languages', JPATH_ADMINISTRATOR, $itemLanguage->language, true);
 776          $title = $newlanguage->_('COM_LANGUAGES_HOMEPAGE');
 777          $alias = 'home_' . $itemLanguage->language;
 778  
 779          $menuItem = array(
 780              'title'        => $title,
 781              'alias'        => $alias,
 782              'menutype'     => 'mainmenu-' . strtolower($itemLanguage->language),
 783              'type'         => 'component',
 784              'link'         => 'index.php?option=com_content&view=category&layout=blog&id=' . $categoryId,
 785              'component_id' => ExtensionHelper::getExtensionRecord('com_content', 'component')->extension_id,
 786              'published'    => 1,
 787              'parent_id'    => 1,
 788              'level'        => 1,
 789              'home'         => 1,
 790              'params'       => '{"layout_type":"blog","show_category_heading_title_text":"","show_category_title":"",'
 791                  . '"show_description":"","show_description_image":"","maxLevel":"","show_empty_categories":"",'
 792                  . '"show_no_articles":"","show_subcat_desc":"","show_cat_num_articles":"","show_cat_tags":"",'
 793                  . '"blog_class_leading":"","blog_class":"","num_leading_articles":"1","num_intro_articles":"3",'
 794                  . '"num_links":"0","show_subcategory_content":"","link_intro_image":"","orderby_pri":"",'
 795                  . '"orderby_sec":"front","order_date":"","show_pagination":"2","show_pagination_results":"1",'
 796                  . '"show_featured":"","article_layout":"_:default","show_title":"","link_titles":"","show_intro":"","info_block_position":"",'
 797                  . '"info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"",'
 798                  . '"link_parent_category":"","show_associations":"","show_author":"","link_author":"",'
 799                  . '"show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"",'
 800                  . '"show_vote":"","show_readmore":"","show_readmore_title":"","show_hits":"","show_tags":"",'
 801                  . '"show_noauth":"","show_feed_link":"1","feed_summary":"","menu-anchor_title":"","menu-anchor_css":"",'
 802                  . '"menu_image":"","menu_image_css":"","menu_text":1,"menu_show":1,"page_title":"","show_page_heading":"1",'
 803                  . '"page_heading":"","pageclass_sfx":"","menu-meta_description":"","robots":""}',
 804              'language'     => $itemLanguage->language,
 805          );
 806  
 807          // Bind the data.
 808          if (!$tableItem->bind($menuItem)) {
 809              return false;
 810          }
 811  
 812          $tableItem->setLocation($menuItem['parent_id'], 'last-child');
 813  
 814          // Check the data.
 815          if (!$tableItem->check()) {
 816              return false;
 817          }
 818  
 819          // Store the data.
 820          if (!$tableItem->store()) {
 821              return false;
 822          }
 823  
 824          // Rebuild the tree path.
 825          if (!$tableItem->rebuildPath($tableItem->id)) {
 826              return false;
 827          }
 828  
 829          return $tableItem;
 830      }
 831  
 832      /**
 833       * Create the language associations.
 834       *
 835       * @param   array  $groupedAssociations  Array of language associations for all items.
 836       *
 837       * @return  boolean  True on success.
 838       *
 839       * @since   4.0.0
 840       */
 841      private function addAssociations($groupedAssociations)
 842      {
 843          $db = $this->db;
 844  
 845          foreach ($groupedAssociations as $context => $associations) {
 846              $key   = md5(json_encode($associations));
 847              $query = $db->getQuery(true)
 848                  ->insert($db->quoteName('#__associations'));
 849  
 850              foreach ($associations as $language => $id) {
 851                  $query->values(
 852                      implode(
 853                          ',',
 854                          $query->bindArray(
 855                              [
 856                                  $id,
 857                                  $context,
 858                                  $key,
 859                              ],
 860                              [
 861                                  ParameterType::INTEGER,
 862                                  ParameterType::STRING,
 863                                  ParameterType::STRING,
 864                              ]
 865                          )
 866                      )
 867                  );
 868              }
 869  
 870              $db->setQuery($query);
 871  
 872              try {
 873                  $db->execute();
 874              } catch (\RuntimeException $e) {
 875                  return false;
 876              }
 877          }
 878  
 879          return true;
 880      }
 881  
 882      /**
 883       * Add a Module in Module menus.
 884       *
 885       * @param   integer  $moduleId  The Id of module.
 886       *
 887       * @return  boolean
 888       *
 889       * @since   4.0.0
 890       */
 891      private function addModuleInModuleMenu($moduleId)
 892      {
 893          // Create a new db object.
 894          $db       = $this->db;
 895          $query    = $db->getQuery(true);
 896          $moduleId = (int) $moduleId;
 897  
 898          // Add Module in Module menus.
 899          $query->insert($db->quoteName('#__modules_menu'))
 900              ->columns($db->quoteName(['moduleid', 'menuid']))
 901              ->values(':moduleId, 0')
 902              ->bind(':moduleId', $moduleId, ParameterType::INTEGER);
 903  
 904          $db->setQuery($query);
 905  
 906          try {
 907              $db->execute();
 908          } catch (RuntimeException $e) {
 909              return false;
 910          }
 911  
 912          return true;
 913      }
 914  
 915      /**
 916       * Method to create a category for a specific language.
 917       *
 918       * @param   stdClass  $itemLanguage  Language Object.
 919       *
 920       * @return  Table|boolean Category Object. False otherwise.
 921       *
 922       * @since   4.0.0
 923       */
 924      public function addCategory($itemLanguage)
 925      {
 926          $newlanguage = new Language($itemLanguage->language, false);
 927          $newlanguage->load('joomla', JPATH_ADMINISTRATOR, $itemLanguage->language, true);
 928          $title = $newlanguage->_('JCATEGORY');
 929          $alias = ApplicationHelper::stringURLSafe($title);
 930  
 931          $app = Factory::getApplication();
 932  
 933          // Set unicodeslugs if alias is empty
 934          if (trim(str_replace('-', '', $alias) == '')) {
 935              $unicode = $app->set('unicodeslugs', 1);
 936              $alias   = ApplicationHelper::stringURLSafe($title);
 937              $app->set('unicodeslugs', $unicode);
 938          }
 939  
 940          // Initialize a new category.
 941          $category = $this->app->bootComponent('com_categories')->getMVCFactory()->createTable('Category', 'Administrator', ['dbo' => $this->db]);
 942  
 943          $data = array(
 944              'extension'       => 'com_content',
 945              'title'           => $title . ' (' . strtolower($itemLanguage->language) . ')',
 946              'alias'           => $alias . ' (' . strtolower($itemLanguage->language) . ')',
 947              'description'     => '',
 948              'published'       => 1,
 949              'access'          => 1,
 950              'params'          => '{"target":"","image":""}',
 951              'metadesc'        => '',
 952              'metakey'         => '',
 953              'metadata'        => '{"page_title":"","author":"","robots":""}',
 954              'created_time'    => Factory::getDate()->toSql(),
 955              'created_user_id' => (int) $this->getAdminId(),
 956              'language'        => $itemLanguage->language,
 957              'rules'           => array(),
 958              'parent_id'       => 1,
 959          );
 960  
 961          // Set the location in the tree.
 962          $category->setLocation(1, 'last-child');
 963  
 964          // Bind the data to the table
 965          if (!$category->bind($data)) {
 966              return false;
 967          }
 968  
 969          // Check to make sure our data is valid.
 970          if (!$category->check()) {
 971              return false;
 972          }
 973  
 974          // Store the category.
 975          if (!$category->store(true)) {
 976              return false;
 977          }
 978  
 979          // Build the path for our category.
 980          $category->rebuildPath($category->id);
 981  
 982          return $category;
 983      }
 984  
 985      /**
 986       * Create an article in a specific language.
 987       *
 988       * @param   stdClass  $itemLanguage  Language Object.
 989       * @param   integer   $categoryId    The id of the category where we want to add the article.
 990       *
 991       * @return  Table|boolean Article Object. False otherwise.
 992       *
 993       * @since   4.0.0
 994       */
 995      private function addArticle($itemLanguage, $categoryId)
 996      {
 997          $db = $this->db;
 998  
 999          $newlanguage = new Language($itemLanguage->language, false);
1000          $newlanguage->load('com_content.sys', JPATH_ADMINISTRATOR, $itemLanguage->language, true);
1001          $title       = $newlanguage->_('COM_CONTENT_CONTENT_TYPE_ARTICLE');
1002          $currentDate = Factory::getDate()->toSql();
1003          $alias = ApplicationHelper::stringURLSafe($title);
1004  
1005          // Set unicodeslugs if alias is empty
1006          if (trim(str_replace('-', '', $alias) == '')) {
1007              $unicode = $this->app->set('unicodeslugs', 1);
1008              $alias   = ApplicationHelper::stringURLSafe($title);
1009              $this->app->set('unicodeslugs', $unicode);
1010          }
1011  
1012          // Initialize a new article.
1013          $article = $this->app->bootComponent('com_content')->getMVCFactory()->createTable('Article', 'Administrator', ['dbo' => $this->db]);
1014  
1015          $data = array(
1016              'title'            => $title . ' (' . strtolower($itemLanguage->language) . ')',
1017              'alias'            => $alias . ' (' . strtolower($itemLanguage->language) . ')',
1018              'introtext'        => '<p>Lorem ipsum ad his scripta blandit partiendo, eum fastidii accumsan euripidis'
1019                  . ' in, eum liber hendrerit an. Qui ut wisi vocibus suscipiantur, quo dicit'
1020                  . ' ridens inciderint id. Quo mundi lobortis reformidans eu, legimus senserit'
1021                  . 'definiebas an eos. Eu sit tincidunt incorrupte definitionem, vis mutat'
1022                  . ' affert percipit cu, eirmod consectetuer signiferumque eu per. In usu latine'
1023                  . 'equidem dolores. Quo no falli viris intellegam, ut fugit veritus placerat'
1024                  . 'per. Ius id vidit volumus mandamus, vide veritus democritum te nec, ei eos'
1025                  . 'debet libris consulatu.</p>',
1026              'fulltext'         => '',
1027              'images'           => json_encode(array()),
1028              'urls'             => json_encode(array()),
1029              'created'          => $currentDate,
1030              'created_by'       => (int) $this->getAdminId(),
1031              'created_by_alias' => 'Joomla',
1032              'publish_up'       => $currentDate,
1033              'publish_down'     => null,
1034              'version'          => 1,
1035              'catid'            => $categoryId,
1036              'metadata'         => '{"robots":"","author":"","rights":"","tags":null}',
1037              'metakey'          => '',
1038              'metadesc'         => '',
1039              'language'         => $itemLanguage->language,
1040              'state'            => 1,
1041              'featured'         => 1,
1042              'attribs'          => array(),
1043              'rules'            => array(),
1044          );
1045  
1046          // Bind the data to the table
1047          if (!$article->bind($data)) {
1048              return false;
1049          }
1050  
1051          // Check to make sure our data is valid.
1052          if (!$article->check()) {
1053              return false;
1054          }
1055  
1056          // Now store the category.
1057          if (!$article->store(true)) {
1058              return false;
1059          }
1060  
1061          // Get the new item ID.
1062          $newId = $article->get('id');
1063  
1064          $query = $db->getQuery(true)
1065              ->insert($db->quoteName('#__content_frontpage'))
1066              ->values($newId . ', 0, NULL, NULL');
1067  
1068          $db->setQuery($query);
1069  
1070          try {
1071              $db->execute();
1072          } catch (ExecutionFailureException $e) {
1073              return false;
1074          }
1075  
1076          $workflow = new Workflow('com_content.article');
1077  
1078          try {
1079              $stage_id = $workflow->getDefaultStageByCategory($categoryId);
1080  
1081              if ($stage_id) {
1082                  $workflow->createAssociation($newId, $stage_id);
1083              }
1084          } catch (ExecutionFailureException $e) {
1085              return false;
1086          }
1087  
1088          return $article;
1089      }
1090  
1091      /**
1092       * Publish the Installed Content Languages.
1093       *
1094       * @return  boolean
1095       *
1096       * @since   4.0.0
1097       */
1098      private function publishContentLanguages()
1099      {
1100          // Publish the Content Languages.
1101          $tableLanguage = Table::getInstance('Language');
1102  
1103          $siteLanguages = $this->getInstalledlangs('site');
1104  
1105          // For each content language.
1106          foreach ($siteLanguages as $siteLang) {
1107              if ($tableLanguage->load(array('lang_code' => $siteLang->language, 'published' => 0)) && !$tableLanguage->publish()) {
1108                  $this->app->enqueueMessage(Text::sprintf('INSTL_DEFAULTLANGUAGE_COULD_NOT_CREATE_CONTENT_LANGUAGE', $siteLang->name), 'warning');
1109              }
1110          }
1111  
1112          return true;
1113      }
1114  
1115      /**
1116       * Get Languages item data for the Administrator.
1117       *
1118       * @return  array
1119       *
1120       * @since   4.0.0
1121       */
1122      public function getInstalledlangsAdministrator()
1123      {
1124          return $this->getInstalledlangs('administrator');
1125      }
1126  
1127      /**
1128       * Get Languages item data for the Frontend.
1129       *
1130       * @return  array  List of installed languages in the frontend application.
1131       *
1132       * @since   4.0.0
1133       */
1134      public function getInstalledlangsFrontend()
1135      {
1136          return $this->getInstalledlangs('site');
1137      }
1138  
1139      /**
1140       * Get Installed Languages.
1141       *
1142       * @param   string  $clientName  Name of the cms client.
1143       *
1144       * @return  array
1145       *
1146       * @since   4.0.0
1147       */
1148      protected function getInstalledlangs($clientName = 'administrator')
1149      {
1150          // Get information.
1151          $path     = $this->getPath();
1152          $client   = $this->getClient($clientName);
1153          $langlist = $this->getLanguageList($client->id);
1154  
1155          // Compute all the languages.
1156          $data = array();
1157  
1158          foreach ($langlist as $lang) {
1159              $file = $path . '/' . $lang . '/' . $lang . '.xml';
1160  
1161              if (!is_file($file)) {
1162                  $file = $path . '/' . $lang . '/langmetadata.xml';
1163              }
1164  
1165              $info          = Installer::parseXMLInstallFile($file);
1166              $row           = new stdClass();
1167              $row->language = $lang;
1168  
1169              if (!is_array($info)) {
1170                  continue;
1171              }
1172  
1173              foreach ($info as $key => $value) {
1174                  $row->$key = $value;
1175              }
1176  
1177              // If current then set published.
1178              $params = ComponentHelper::getParams('com_languages');
1179  
1180              if ($params->get($client->name, 'en-GB') == $row->language) {
1181                  $row->published = 1;
1182              } else {
1183                  $row->published = 0;
1184              }
1185  
1186              $row->checked_out = null;
1187              $data[]           = $row;
1188          }
1189  
1190          usort($data, array($this, 'compareLanguages'));
1191  
1192          return $data;
1193      }
1194  
1195      /**
1196       * Get installed languages data.
1197       *
1198       * @param   integer  $clientId  The client ID to retrieve data for.
1199       *
1200       * @return  object  The language data.
1201       *
1202       * @since   4.0.0
1203       */
1204      protected function getLanguageList($clientId = 1)
1205      {
1206          // Create a new db object.
1207          $db    = $this->db;
1208          $query = $db->getQuery(true);
1209  
1210          // Select field element from the extensions table.
1211          $query->select($db->quoteName(['element', 'name']))
1212              ->from($db->quoteName('#__extensions'))
1213              ->where(
1214                  [
1215                      $db->quoteName('type') . ' = ' . $db->quote('language'),
1216                      $db->quoteName('state') . ' = 0',
1217                      $db->quoteName('enabled') . ' = 1',
1218                      $db->quoteName('client_id') . ' = :clientid',
1219                  ]
1220              )
1221              ->bind(':clientid', $clientId, ParameterType::INTEGER);
1222  
1223          $db->setQuery($query);
1224  
1225          $this->langlist = $db->loadColumn();
1226  
1227          return $this->langlist;
1228      }
1229  
1230      /**
1231       * Compare two languages in order to sort them.
1232       *
1233       * @param   object  $lang1  The first language.
1234       * @param   object  $lang2  The second language.
1235       *
1236       * @return  integer
1237       *
1238       * @since   4.0.0
1239       */
1240      protected function compareLanguages($lang1, $lang2)
1241      {
1242          return strcmp($lang1->name, $lang2->name);
1243      }
1244  
1245      /**
1246       * Get the languages folder path.
1247       *
1248       * @return  string  The path to the languages folders.
1249       *
1250       * @since   4.0.0
1251       */
1252      protected function getPath()
1253      {
1254          if ($this->path === null) {
1255              $client     = $this->getClient();
1256              $this->path = LanguageHelper::getLanguagePath($client->path);
1257          }
1258  
1259          return $this->path;
1260      }
1261  
1262      /**
1263       * Get the client object of Administrator or Frontend.
1264       *
1265       * @param   string  $client  Name of the client object.
1266       *
1267       * @return  object
1268       *
1269       * @since   4.0.0
1270       */
1271      protected function getClient($client = 'administrator')
1272      {
1273          $this->client = ApplicationHelper::getClientInfo($client, true);
1274  
1275          return $this->client;
1276      }
1277  
1278      /**
1279       * Retrieve the admin user id.
1280       *
1281       * @return  integer|boolean  One Administrator ID.
1282       *
1283       * @since   4.0.0
1284       */
1285      private function getAdminId()
1286      {
1287          if ($this->adminId) {
1288              // Return local cached admin ID.
1289              return $this->adminId;
1290          }
1291  
1292          $db    = $this->db;
1293          $query = $db->getQuery(true);
1294  
1295          // Select the admin user ID
1296          $query
1297              ->select($db->quoteName('u.id'))
1298              ->from($db->quoteName('#__users', 'u'))
1299              ->join(
1300                  'LEFT',
1301                  $db->quoteName('#__user_usergroup_map', 'map'),
1302                  $db->quoteName('map.user_id') . ' = ' . $db->quoteName('u.id')
1303              )
1304              ->join(
1305                  'LEFT',
1306                  $db->quoteName('#__usergroups', 'g'),
1307                  $db->quoteName('map.group_id') . ' = ' . $db->quoteName('g.id')
1308              )
1309              ->where(
1310                  $db->quoteName('g.title') . ' = ' . $db->quote('Super Users')
1311              );
1312  
1313          $db->setQuery($query);
1314          $id = $db->loadResult();
1315  
1316          if (!$id || $id instanceof Exception) {
1317              return false;
1318          }
1319  
1320          return $id;
1321      }
1322  }


Generated: Wed Sep 7 05:41:13 2022 Chilli.vc Blog - For Webmaster,Blog-Writer,System Admin and Domainer