From 4292a06af6acb77e66ed15c1cbbf9e25eddcdd62 Mon Sep 17 00:00:00 2001 From: Hannes Papenberg Date: Thu, 18 May 2023 18:45:59 +0200 Subject: [PATCH] Switch to PSR-12 --- .editorconfig | 20 + ruleset.xml | 12 +- .../com_weblinks/helpers/weblinks.php | 6 +- .../components/com_weblinks/script.php | 505 ++++++----- .../com_weblinks/services/provider.php | 70 +- .../src/Controller/DisplayController.php | 79 +- .../src/Controller/WeblinkController.php | 177 ++-- .../src/Controller/WeblinksController.php | 36 +- .../src/Extension/WeblinksComponent.php | 199 ++--- .../src/Field/Modal/WeblinkField.php | 460 +++++----- .../src/Helper/AssociationsHelper.php | 320 ++++--- .../src/Helper/WeblinksHelper.php | 7 +- .../com_weblinks/src/Model/WeblinkModel.php | 686 ++++++++------- .../com_weblinks/src/Model/WeblinksModel.php | 448 +++++----- .../src/Service/HTML/AdministratorService.php | 152 ++-- .../com_weblinks/src/Service/HTML/Icon.php | 248 +++--- .../com_weblinks/src/Table/WeblinkTable.php | 426 +++++----- .../src/View/Weblink/HtmlView.php | 234 +++--- .../src/View/Weblinks/HtmlView.php | 282 +++---- .../com_weblinks/tmpl/weblink/edit.php | 151 ++-- .../tmpl/weblink/edit_associations.php | 7 +- .../tmpl/weblink/edit_metadata.php | 7 +- .../com_weblinks/tmpl/weblink/edit_params.php | 39 +- .../com_weblinks/tmpl/weblink/modal.php | 12 +- .../tmpl/weblink/modal_associations.php | 7 +- .../tmpl/weblink/modal_metadata.php | 7 +- .../tmpl/weblink/modal_params.php | 39 +- .../com_weblinks/tmpl/weblinks/default.php | 350 ++++---- .../tmpl/weblinks/default_batch_body.php | 66 +- .../tmpl/weblinks/default_batch_footer.php | 9 +- .../com_weblinks/tmpl/weblinks/emptystate.php | 24 +- .../com_weblinks/tmpl/weblinks/modal.php | 237 +++--- .../manifests/packages/weblinks/script.php | 26 +- src/components/com_weblinks/helpers/icon.php | 74 +- src/components/com_weblinks/helpers/route.php | 7 +- .../src/Controller/DisplayController.php | 93 +-- .../src/Controller/WeblinkController.php | 536 ++++++------ .../src/Helper/AssociationHelper.php | 73 +- .../com_weblinks/src/Helper/RouteHelper.php | 157 ++-- .../src/Model/CategoriesModel.php | 229 +++-- .../com_weblinks/src/Model/CategoryModel.php | 790 +++++++++--------- .../com_weblinks/src/Model/FormModel.php | 173 ++-- .../com_weblinks/src/Model/WeblinkModel.php | 329 ++++---- .../com_weblinks/src/Service/Category.php | 31 +- .../com_weblinks/src/Service/Router.php | 471 +++++------ .../src/View/Categories/HtmlView.php | 27 +- .../src/View/Category/FeedView.php | 16 +- .../src/View/Category/HtmlView.php | 149 ++-- .../com_weblinks/src/View/Form/HtmlView.php | 235 +++--- .../src/View/Weblink/HtmlView.php | 122 ++- .../com_weblinks/tmpl/categories/default.php | 16 +- .../tmpl/categories/default_items.php | 145 ++-- .../com_weblinks/tmpl/category/default.php | 16 +- .../tmpl/category/default_children.php | 83 +- .../tmpl/category/default_items.php | 402 +++++---- .../com_weblinks/tmpl/form/edit.php | 137 +-- .../com_weblinks/tmpl/weblink/default.php | 180 ++-- .../mod_weblinks/services/provider.php | 34 +- .../src/Dispatcher/Dispatcher.php | 38 +- .../src/Helper/WeblinksHelper.php | 190 +++-- src/modules/mod_weblinks/tmpl/default.php | 306 ++++--- .../editors-xtd/weblink/services/provider.php | 52 +- .../weblink/src/Extension/Weblink.php | 117 +-- .../finder/weblinks/services/provider.php | 52 +- .../weblinks/src/Extension/Weblinks.php | 649 +++++++------- .../search/weblinks/services/provider.php | 56 +- .../weblinks/src/Extension/Weblinks.php | 356 ++++---- .../system/weblinks/services/provider.php | 52 +- .../weblinks/src/Extension/Weblinks.php | 168 ++-- 69 files changed, 5877 insertions(+), 6032 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..dd23145 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,20 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style end of lines and a blank line at the end of the file +[*] +indent_style = tab +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.php] +indent_style = space +indent_size = 4 + +[*.{js,json,scss,css,yml,vue}] +indent_style = space +indent_size = 2 diff --git a/ruleset.xml b/ruleset.xml index bbafb75..7d69c2c 100644 --- a/ruleset.xml +++ b/ruleset.xml @@ -18,14 +18,23 @@ - src/administrator/components/com_weblinks/script\.php + src/administrator/components/com_weblinks/script\.php + src/administrator/manifests/packages/weblinks/script\.php + src/administrator/components/com_weblinks/helpers/weblinks\.php + src/components/com_weblinks/helpers/icon\.php + src/components/com_weblinks/helpers/route\.php + src/components/com_weblinks/src/Model/CategoriesModel\.php + src/components/com_weblinks/src/Model/CategoryModel\.php + src/components/com_weblinks/src/Model/WeblinkModel\.php + src/administrator/components/com_weblinks/src/Table/*\.php src/administrator/components/com_weblinks/script\.php + src/administrator/manifests/packages/weblinks/script\.php @@ -34,5 +43,6 @@ src/administrator/components/com_weblinks/script\.php + src/administrator/manifests/packages/weblinks/script\.php diff --git a/src/administrator/components/com_weblinks/helpers/weblinks.php b/src/administrator/components/com_weblinks/helpers/weblinks.php index 8e19ede..46baefc 100644 --- a/src/administrator/components/com_weblinks/helpers/weblinks.php +++ b/src/administrator/components/com_weblinks/helpers/weblinks.php @@ -1,4 +1,5 @@ load(array('extension' => 'com_weblinks', 'title' => 'Uncategorised'))) - { - $category->extension = 'com_weblinks'; - $category->title = 'Uncategorised'; - $category->description = ''; - $category->published = 1; - $category->access = 1; - $category->params = '{"category_layout":"","image":""}'; - $category->metadata = '{"author":"","robots":""}'; - $category->metadesc = ''; - $category->metakey = ''; - $category->language = '*'; - $category->checked_out_time = null; - $category->version = 1; - $category->hits = 0; - $category->modified_user_id = 0; - $category->checked_out = null; + // Check if the Uncategorised category exists before adding it + if (!$category->load(['extension' => 'com_weblinks', 'title' => 'Uncategorised'])) { + $category->extension = 'com_weblinks'; + $category->title = 'Uncategorised'; + $category->description = ''; + $category->published = 1; + $category->access = 1; + $category->params = '{"category_layout":"","image":""}'; + $category->metadata = '{"author":"","robots":""}'; + $category->metadesc = ''; + $category->metakey = ''; + $category->language = '*'; + $category->checked_out_time = null; + $category->version = 1; + $category->hits = 0; + $category->modified_user_id = 0; + $category->checked_out = null; - // Set the location in the tree - $category->setLocation(1, 'last-child'); + // Set the location in the tree + $category->setLocation(1, 'last-child'); - // Check to make sure our data is valid - if (!$category->check()) - { - Factory::getApplication()->enqueueMessage(Text::sprintf('COM_WEBLINKS_ERROR_INSTALL_CATEGORY', $category->getError())); + // Check to make sure our data is valid + if (!$category->check()) { + Factory::getApplication()->enqueueMessage(Text::sprintf('COM_WEBLINKS_ERROR_INSTALL_CATEGORY', $category->getError())); - return; - } + return; + } - // Now store the category - if (!$category->store(true)) - { - Factory::getApplication()->enqueueMessage(Text::sprintf('COM_WEBLINKS_ERROR_INSTALL_CATEGORY', $category->getError())); + // Now store the category + if (!$category->store(true)) { + Factory::getApplication()->enqueueMessage(Text::sprintf('COM_WEBLINKS_ERROR_INSTALL_CATEGORY', $category->getError())); - return; - } + return; + } - // Build the path for our category - $category->rebuildPath($category->id); - } - } + // Build the path for our category + $category->rebuildPath($category->id); + } + } - /** - * Method to run after the install routine. - * - * @param string $type The action being performed - * @param JInstallerAdapterComponent $parent The class calling this method - * - * @return void - * - * @since 3.4.1 - */ - public function postflight($type, $parent) - { - // Only execute database changes on MySQL databases - $dbName = Factory::getDbo()->name; + /** + * Method to run after the install routine. + * + * @param string $type The action being performed + * @param JInstallerAdapterComponent $parent The class calling this method + * + * @return void + * + * @since 3.4.1 + */ + public function postflight($type, $parent) + { + // Only execute database changes on MySQL databases + $dbName = Factory::getDbo()->name; - if (strpos($dbName, 'mysql') !== false) - { - // Add Missing Table Columns if needed - $this->addColumnsIfNeeded(); + if (strpos($dbName, 'mysql') !== false) { + // Add Missing Table Columns if needed + $this->addColumnsIfNeeded(); - // Drop the Table Columns if needed - $this->dropColumnsIfNeeded(); - } + // Drop the Table Columns if needed + $this->dropColumnsIfNeeded(); + } - // Insert missing UCM Records if needed - $this->insertMissingUcmRecords(); - } + // Insert missing UCM Records if needed + $this->insertMissingUcmRecords(); + } - /** - * Method to insert missing records for the UCM tables - * - * @return void - * - * @since 3.4.1 - */ - private function insertMissingUcmRecords() - { - // Insert the rows in the #__content_types table if they don't exist already - $db = Factory::getDbo(); + /** + * Method to insert missing records for the UCM tables + * + * @return void + * + * @since 3.4.1 + */ + private function insertMissingUcmRecords() + { + // Insert the rows in the #__content_types table if they don't exist already + $db = Factory::getDbo(); - // Get the type ID for a Weblink - $query = $db->getQuery(true); - $query->select($db->quoteName('type_id')) - ->from($db->quoteName('#__content_types')) - ->where($db->quoteName('type_alias') . ' = ' . $db->quote('com_weblinks.weblink')); - $db->setQuery($query); + // Get the type ID for a Weblink + $query = $db->getQuery(true); + $query->select($db->quoteName('type_id')) + ->from($db->quoteName('#__content_types')) + ->where($db->quoteName('type_alias') . ' = ' . $db->quote('com_weblinks.weblink')); + $db->setQuery($query); - $weblinkTypeId = $db->loadResult(); + $weblinkTypeId = $db->loadResult(); - // Get the type ID for a Weblink Category - $query->clear('where'); - $query->where($db->quoteName('type_alias') . ' = ' . $db->quote('com_weblinks.category')); - $db->setQuery($query); + // Get the type ID for a Weblink Category + $query->clear('where'); + $query->where($db->quoteName('type_alias') . ' = ' . $db->quote('com_weblinks.category')); + $db->setQuery($query); - $categoryTypeId = $db->loadResult(); + $categoryTypeId = $db->loadResult(); - // Set the table columns to insert table to - $columnsArray = array( - $db->quoteName('type_title'), - $db->quoteName('type_alias'), - $db->quoteName('table'), - $db->quoteName('rules'), - $db->quoteName('field_mappings'), - $db->quoteName('router'), - $db->quoteName('content_history_options'), - ); + // Set the table columns to insert table to + $columnsArray = [ + $db->quoteName('type_title'), + $db->quoteName('type_alias'), + $db->quoteName('table'), + $db->quoteName('rules'), + $db->quoteName('field_mappings'), + $db->quoteName('router'), + $db->quoteName('content_history_options'), + ]; - // If we have no type id for com_weblinks.weblink insert it - if (!$weblinkTypeId) - { - // Insert the data. - $query->clear(); - $query->insert($db->quoteName('#__content_types')); - $query->columns($columnsArray); - $query->values( - $db->quote('Weblink') . ', ' - . $db->quote('com_weblinks.weblink') . ', ' - . $db->quote( - '{"special":{"dbtable":"#__weblinks","key":"id","type":"Weblink","prefix":"WeblinksTable","config":"array()"}, + // If we have no type id for com_weblinks.weblink insert it + if (!$weblinkTypeId) { + // Insert the data. + $query->clear(); + $query->insert($db->quoteName('#__content_types')); + $query->columns($columnsArray); + $query->values( + $db->quote('Weblink') . ', ' + . $db->quote('com_weblinks.weblink') . ', ' + . $db->quote( + '{"special":{"dbtable":"#__weblinks","key":"id","type":"Weblink","prefix":"WeblinksTable","config":"array()"}, "common":{"dbtable":"#__ucm_content","key":"ucm_id","type":"Corecontent","prefix":"JTable","config":"array()"}}' - ) . ', ' - . $db->quote('') . ', ' - . $db->quote( - '{"common":{"core_content_item_id":"id","core_title":"title","core_state":"state","core_alias":"alias", + ) . ', ' + . $db->quote('') . ', ' + . $db->quote( + '{"common":{"core_content_item_id":"id","core_title":"title","core_state":"state","core_alias":"alias", "core_created_time":"created","core_modified_time":"modified","core_body":"description", "core_hits":"hits", "core_publish_up":"publish_up","core_publish_down":"publish_down","core_access":"access", "core_params":"params", "core_featured":"featured", "core_metadata":"metadata", "core_language":"language", "core_images":"images", "core_urls":"url", "core_version":"version", "core_ordering":"ordering", "core_metakey":"metakey", "core_metadesc":"metadesc", "core_catid":"catid", "core_xreference":"xreference", "asset_id":"null"}, "special":{}}' - ) . ', ' - . $db->quote('WeblinksHelperRoute::getWeblinkRoute') . ', ' - . $db->quote( - '{"formFile":"administrator\\/components\\/com_weblinks\\/models\\/forms\\/weblink.xml", + ) . ', ' + . $db->quote('WeblinksHelperRoute::getWeblinkRoute') . ', ' + . $db->quote( + '{"formFile":"administrator\\/components\\/com_weblinks\\/models\\/forms\\/weblink.xml", "hideFields":["asset_id","checked_out","checked_out_time","version","featured","images"], "ignoreChanges":["modified_by", "modified", "checked_out", "checked_out_time", "version", "hits"], "convertToInt":["publish_up", "publish_down", "featured", "ordering"], "displayLookup":[{"sourceColumn":"catid","targetTable":"#__categories","targetColumn":"id","displayColumn":"title"}, {"sourceColumn":"created_by","targetTable":"#__users","targetColumn":"id","displayColumn":"name"}, {"sourceColumn":"access","targetTable":"#__viewlevels","targetColumn":"id","displayColumn":"title"}, {"sourceColumn":"modified_by","targetTable":"#__users","targetColumn":"id","displayColumn":"name"} ]}' - ) - ); + ) + ); - $db->setQuery($query); - $db->execute(); - } + $db->setQuery($query); + $db->execute(); + } - // If we have no type id for com_weblinks.category insert it - if (!$categoryTypeId) - { - // Insert the data. - $query->clear(); - $query->insert($db->quoteName('#__content_types')); - $query->columns($columnsArray); - $query->values( - $db->quote('Weblinks Category') . ', ' - . $db->quote('com_weblinks.category') . ', ' - . $db->quote(' + // If we have no type id for com_weblinks.category insert it + if (!$categoryTypeId) { + // Insert the data. + $query->clear(); + $query->insert($db->quoteName('#__content_types')); + $query->columns($columnsArray); + $query->values( + $db->quote('Weblinks Category') . ', ' + . $db->quote('com_weblinks.category') . ', ' + . $db->quote(' {"special":{"dbtable":"#__categories","key":"id","type":"Category","prefix":"JTable","config":"array()"}, - "common":{"dbtable":"#__ucm_content","key":"ucm_id","type":"Corecontent","prefix":"JTable","config":"array()"}}' - ) . ', ' - . $db->quote('') . ', ' - . $db->quote(' + "common":{"dbtable":"#__ucm_content","key":"ucm_id","type":"Corecontent","prefix":"JTable","config":"array()"}}') . ', ' + . $db->quote('') . ', ' + . $db->quote(' {"common":{"core_content_item_id":"id","core_title":"title","core_state":"published","core_alias":"alias", "core_created_time":"created_time","core_modified_time":"modified_time","core_body":"description", "core_hits":"hits","core_publish_up":"null","core_publish_down":"null","core_access":"access", "core_params":"params", "core_featured":"null", "core_metadata":"metadata", "core_language":"language", "core_images":"null", "core_urls":"null", "core_version":"version", "core_ordering":"null", "core_metakey":"metakey", "core_metadesc":"metadesc", "core_catid":"parent_id", "core_xreference":"null", "asset_id":"asset_id"}, - "special":{"parent_id":"parent_id","lft":"lft","rgt":"rgt","level":"level","path":"path","extension":"extension","note":"note"}}' - ) . ', ' - . $db->quote('WeblinksHelperRoute::getCategoryRoute') . ', ' - . $db->quote(' + "special":{"parent_id":"parent_id","lft":"lft","rgt":"rgt","level":"level","path":"path","extension":"extension","note":"note"}}') . ', ' + . $db->quote('WeblinksHelperRoute::getCategoryRoute') . ', ' + . $db->quote(' {"formFile":"administrator\\/components\\/com_categories\\/models\\/forms\\/category.xml", "hideFields":["asset_id","checked_out","checked_out_time","version","lft","rgt","level","path","extension"], "ignoreChanges":["modified_user_id", "modified_time", "checked_out", "checked_out_time", "version", @@ -277,68 +268,64 @@ class Com_WeblinksInstallerScript "displayColumn":"name"},{"sourceColumn":"access","targetTable":"#__viewlevels","targetColumn":"id", "displayColumn":"title"},{"sourceColumn":"modified_user_id","targetTable":"#__users","targetColumn":"id", "displayColumn":"name"},{"sourceColumn":"parent_id","targetTable":"#__categories","targetColumn":"id", - "displayColumn":"title"}]}' - ) - ); + "displayColumn":"title"}]}') + ); - $db->setQuery($query); - $db->execute(); - } - } + $db->setQuery($query); + $db->execute(); + } + } - /** - * Method to drop colums from #__weblinks if they still there. - * - * @return void - * - * @since 3.4.1 - */ - private function dropColumnsIfNeeded() - { - $oldColumns = array( - 'sid', - 'date', - 'archived', - 'approved', - ); + /** + * Method to drop colums from #__weblinks if they still there. + * + * @return void + * + * @since 3.4.1 + */ + private function dropColumnsIfNeeded() + { + $oldColumns = [ + 'sid', + 'date', + 'archived', + 'approved', + ]; - $db = Factory::getDbo(); - $table = $db->getTableColumns('#__weblinks'); + $db = Factory::getDbo(); + $table = $db->getTableColumns('#__weblinks'); - $columns = array_intersect($oldColumns, array_keys($table)); + $columns = array_intersect($oldColumns, array_keys($table)); - foreach ($columns as $column) - { - $sql = 'ALTER TABLE ' . $db->quoteName('#__weblinks') . ' DROP COLUMN ' . $db->quoteName($column); - $db->setQuery($sql); - $db->execute(); - } - } + foreach ($columns as $column) { + $sql = 'ALTER TABLE ' . $db->quoteName('#__weblinks') . ' DROP COLUMN ' . $db->quoteName($column); + $db->setQuery($sql); + $db->execute(); + } + } - /** - * Method to add colums from #__weblinks if they are missing. - * - * @return void - * - * @since 3.4.1 - */ - private function addColumnsIfNeeded() - { - $db = Factory::getDbo(); - $table = $db->getTableColumns('#__weblinks'); + /** + * Method to add colums from #__weblinks if they are missing. + * + * @return void + * + * @since 3.4.1 + */ + private function addColumnsIfNeeded() + { + $db = Factory::getDbo(); + $table = $db->getTableColumns('#__weblinks'); - if (!array_key_exists('version', $table)) - { - $sql = 'ALTER TABLE ' . $db->quoteName('#__weblinks') . ' ADD COLUMN ' . $db->quoteName('version') . " int unsigned NOT NULL DEFAULT '1'"; - $db->setQuery($sql); - $db->execute(); - } + if (!array_key_exists('version', $table)) { + $sql = 'ALTER TABLE ' . $db->quoteName('#__weblinks') . ' ADD COLUMN ' . $db->quoteName('version') . " int unsigned NOT NULL DEFAULT '1'"; + $db->setQuery($sql); + $db->execute(); + } - if (!array_key_exists('images', $table)) - { - $sql = 'ALTER TABLE ' . $db->quoteName('#__weblinks') . ' ADD COLUMN ' . $db->quoteName('images') . ' text NOT NULL'; - $db->setQuery($sql); - $db->execute(); - } - } + if (!array_key_exists('images', $table)) { + $sql = 'ALTER TABLE ' . $db->quoteName('#__weblinks') . ' ADD COLUMN ' . $db->quoteName('images') . ' text NOT NULL'; + $db->setQuery($sql); + $db->execute(); + } + } } diff --git a/src/administrator/components/com_weblinks/services/provider.php b/src/administrator/components/com_weblinks/services/provider.php index a9470bd..b794e32 100644 --- a/src/administrator/components/com_weblinks/services/provider.php +++ b/src/administrator/components/com_weblinks/services/provider.php @@ -1,4 +1,5 @@ set(AssociationExtensionInterface::class, new AssociationsHelper); - - $componentNamespace = '\\Joomla\\Component\\Weblinks'; - - $container->registerServiceProvider(new CategoryFactory($componentNamespace)); - $container->registerServiceProvider(new MVCFactory($componentNamespace)); - $container->registerServiceProvider(new ComponentDispatcherFactory($componentNamespace)); - $container->registerServiceProvider(new RouterFactory($componentNamespace)); - - $container->set( - ComponentInterface::class, - function (Container $container) { - $component = new WeblinksComponent($container->get(ComponentDispatcherFactoryInterface::class)); - - $component->setRegistry($container->get(Registry::class)); - $component->setMVCFactory($container->get(MVCFactoryInterface::class)); - $component->setCategoryFactory($container->get(CategoryFactoryInterface::class)); - $component->setAssociationExtension($container->get(AssociationExtensionInterface::class)); - $component->setRouterFactory($container->get(RouterFactoryInterface::class)); - - return $component; - } - ); - } +return new class () implements ServiceProviderInterface { + /** + * Registers the service provider with a DI container. + * + * @param Container $container The DI container. + * + * @return void + * + * @since 4.0.0 + */ + public function register(Container $container) + { + $container->set(AssociationExtensionInterface::class, new AssociationsHelper()); + $componentNamespace = '\\Joomla\\Component\\Weblinks'; + $container->registerServiceProvider(new CategoryFactory($componentNamespace)); + $container->registerServiceProvider(new MVCFactory($componentNamespace)); + $container->registerServiceProvider(new ComponentDispatcherFactory($componentNamespace)); + $container->registerServiceProvider(new RouterFactory($componentNamespace)); + $container->set(ComponentInterface::class, function (Container $container) { + $component = new WeblinksComponent($container->get(ComponentDispatcherFactoryInterface::class)); + $component->setRegistry($container->get(Registry::class)); + $component->setMVCFactory($container->get(MVCFactoryInterface::class)); + $component->setCategoryFactory($container->get(CategoryFactoryInterface::class)); + $component->setAssociationExtension($container->get(AssociationExtensionInterface::class)); + $component->setRouterFactory($container->get(RouterFactoryInterface::class)); + return $component; + }); + } }; diff --git a/src/administrator/components/com_weblinks/src/Controller/DisplayController.php b/src/administrator/components/com_weblinks/src/Controller/DisplayController.php index 67fcf1f..813bab9 100644 --- a/src/administrator/components/com_weblinks/src/Controller/DisplayController.php +++ b/src/administrator/components/com_weblinks/src/Controller/DisplayController.php @@ -1,4 +1,5 @@ input->get('view', 'weblinks'); + $layout = $this->input->get('layout', 'default'); + $id = $this->input->getInt('id'); + // Check for edit form. + if ($view == 'weblink' && $layout == 'edit' && !$this->checkEditId('com_weblinks.edit.weblink', $id)) { + // Somehow the person just went to the form - we don't allow that. + if (!\count($this->app->getMessageQueue())) { + $this->setMessage(Text::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $id), 'error'); + } - /** - * Method to display a view. - * - * @param boolean $cacheable If true, the view output will be cached - * @param array $urlparams An array of safe url parameters and their variable types, - * for valid values see {@link JFilterInput::clean()}. - * - * @return BaseController|boolean This object to support chaining. - * - * @since 1.5 - */ - public function display($cacheable = false, $urlparams = false) - { - $view = $this->input->get('view', 'weblinks'); - $layout = $this->input->get('layout', 'default'); - $id = $this->input->getInt('id'); + $this->setRedirect(Route::_('index.php?option=com_weblinks&view=weblinks', false)); + return false; + } - // Check for edit form. - if ($view == 'weblink' && $layout == 'edit' && !$this->checkEditId('com_weblinks.edit.weblink', $id)) - { - // Somehow the person just went to the form - we don't allow that. - if (!\count($this->app->getMessageQueue())) - { - $this->setMessage(Text::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $id), 'error'); - } - - $this->setRedirect(Route::_('index.php?option=com_weblinks&view=weblinks', false)); - - return false; - } - - return parent::display(); - } + return parent::display(); + } } diff --git a/src/administrator/components/com_weblinks/src/Controller/WeblinkController.php b/src/administrator/components/com_weblinks/src/Controller/WeblinkController.php index 6227371..8035403 100644 --- a/src/administrator/components/com_weblinks/src/Controller/WeblinkController.php +++ b/src/administrator/components/com_weblinks/src/Controller/WeblinkController.php @@ -1,4 +1,5 @@ input->getInt('filter_category_id'), 'int'); + /** + * Method override to check if you can add a new record. + * + * @param array $data An array of input data. + * + * @return boolean + * + * @since 1.6 + */ + protected function allowAdd($data = []) + { + $categoryId = ArrayHelper::getValue($data, 'catid', $this->input->getInt('filter_category_id'), 'int'); - if ($categoryId) - { - // If the category has been passed in the URL check it. - return $this->app->getIdentity()->authorise('core.create', $this->option . '.category.' . $categoryId); - } + if ($categoryId) { + // If the category has been passed in the URL check it. + return $this->app->getIdentity()->authorise('core.create', $this->option . '.category.' . $categoryId); + } - // In the absence of better information, revert to the component permissions. - return parent::allowAdd($data); - } + // In the absence of better information, revert to the component permissions. + return parent::allowAdd($data); + } - /** - * Method to check if you can add a new record. - * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key. - * - * @return boolean - * - * @since 1.6 - */ - protected function allowEdit($data = array(), $key = 'id') - { - $recordId = (int) isset($data[$key]) ? $data[$key] : 0; + /** + * Method to check if you can add a new record. + * + * @param array $data An array of input data. + * @param string $key The name of the key for the primary key. + * + * @return boolean + * + * @since 1.6 + */ + protected function allowEdit($data = [], $key = 'id') + { + $recordId = (int) isset($data[$key]) ? $data[$key] : 0; - // Since there is no asset tracking, fallback to the component permissions. - if (!$recordId) - { - return parent::allowEdit($data, $key); - } + // Since there is no asset tracking, fallback to the component permissions. + if (!$recordId) { + return parent::allowEdit($data, $key); + } - // Get the item. - $item = $this->getModel()->getItem($recordId); + // Get the item. + $item = $this->getModel()->getItem($recordId); - // Since there is no item, return false. - if (empty($item)) - { - return false; - } + // Since there is no item, return false. + if (empty($item)) { + return false; + } - $user = $this->app->getIdentity(); + $user = $this->app->getIdentity(); - // Check if can edit own core.edit.own. - $canEditOwn = $user->authorise('core.edit.own', $this->option . '.category.' . (int) $item->catid) && $item->created_by == $user->id; + // Check if can edit own core.edit.own. + $canEditOwn = $user->authorise('core.edit.own', $this->option . '.category.' . (int) $item->catid) && $item->created_by == $user->id; - // Check the category core.edit permissions. - return $canEditOwn || $user->authorise('core.edit', $this->option . '.category.' . (int) $item->catid); - } + // Check the category core.edit permissions. + return $canEditOwn || $user->authorise('core.edit', $this->option . '.category.' . (int) $item->catid); + } - /** - * Method to run batch operations. - * - * @param object $model The model. - * - * @return boolean True if successful, false otherwise and internal error is set. - * - * @since 1.7 - */ - public function batch($model = null) - { - $this->checkToken(); + /** + * Method to run batch operations. + * + * @param object $model The model. + * + * @return boolean True if successful, false otherwise and internal error is set. + * + * @since 1.7 + */ + public function batch($model = null) + { + $this->checkToken(); - // Set the model - $model = $this->getModel('Weblink', 'Administrator', array()); + // Set the model + $model = $this->getModel('Weblink', 'Administrator', []); - // Preset the redirect - $this->setRedirect(Route::_('index.php?option=com_weblinks&view=weblinks' . $this->getRedirectToListAppend(), false)); + // Preset the redirect + $this->setRedirect(Route::_('index.php?option=com_weblinks&view=weblinks' . $this->getRedirectToListAppend(), false)); - return parent::batch($model); - } + return parent::batch($model); + } - /** - * Function that allows child controller access to model data after the data has been saved. - * - * @param \Joomla\CMS\MVC\Model\BaseDatabaseModel $model The data model object. - * @param array $validData The validated data. - * - * @return void - * - * @since 1.6 - */ - protected function postSaveHook(BaseDatabaseModel $model, $validData = []) - { - $task = $this->getTask(); + /** + * Function that allows child controller access to model data after the data has been saved. + * + * @param \Joomla\CMS\MVC\Model\BaseDatabaseModel $model The data model object. + * @param array $validData The validated data. + * + * @return void + * + * @since 1.6 + */ + protected function postSaveHook(BaseDatabaseModel $model, $validData = []) + { + $task = $this->getTask(); - if ($task == 'save') - { - $this->setRedirect(Route::_('index.php?option=com_weblinks&view=weblinks', false)); - } - } + if ($task == 'save') { + $this->setRedirect(Route::_('index.php?option=com_weblinks&view=weblinks', false)); + } + } } diff --git a/src/administrator/components/com_weblinks/src/Controller/WeblinksController.php b/src/administrator/components/com_weblinks/src/Controller/WeblinksController.php index 9508b7a..f325805 100644 --- a/src/administrator/components/com_weblinks/src/Controller/WeblinksController.php +++ b/src/administrator/components/com_weblinks/src/Controller/WeblinksController.php @@ -1,4 +1,5 @@ true)) - { - return parent::getModel($name, $prefix, $config); - } + /** + * Proxy for getModel + * + * @param string $name The model name. Optional. + * @param string $prefix The class prefix. Optional. + * @param array $config The array of possible config values. Optional. + * + * @return object The model. + * + * @since 1.6 + */ + public function getModel($name = 'Weblink', $prefix = 'Administrator', $config = ['ignore_request' => true]) + { + return parent::getModel($name, $prefix, $config); + } } diff --git a/src/administrator/components/com_weblinks/src/Extension/WeblinksComponent.php b/src/administrator/components/com_weblinks/src/Extension/WeblinksComponent.php index 937cba4..877847f 100644 --- a/src/administrator/components/com_weblinks/src/Extension/WeblinksComponent.php +++ b/src/administrator/components/com_weblinks/src/Extension/WeblinksComponent.php @@ -1,4 +1,5 @@ getRegistry()->register('weblinksadministrator', new AdministratorService); - $this->getRegistry()->register('weblinkicon', new Icon($container->get(SiteApplication::class))); - } - - /** - * Returns a valid section for the given section. If it is not valid then null - * is returned. - * - * @param string $section The section to get the mapping for - * @param object $item The item - * - * @return string|null The new section - * - * @since 4.0.0 - */ - public function validateSection($section, $item = null) - { - if ($section != 'weblink') - { - // We don't know other sections - return null; - } - - return $section; - } - - /** - * Returns valid contexts - * - * @return array - * - * @since 4.0.0 - */ - public function getContexts(): array - { - Factory::getLanguage()->load('com_weblinks', JPATH_ADMINISTRATOR); - - $contexts = array( - 'com_weblinks.weblink' => Text::_('COM_WEBLINKS'), - ); - - return $contexts; - } + /** + * Booting the extension. This is the function to set up the environment of the extension like + * registering new class loaders, etc. + * + * If required, some initial set up can be done from services of the container, eg. + * registering HTML services. + * + * @param ContainerInterface $container The container + * + * @return void + * + * @since 4.0.0 + */ - /** - * Returns the table for the count items functions for the given section. - * - * @param string $section The section - * - * @return string|null - * - * @since 4.0.0 - */ - protected function getTableNameForSection(string $section = null) - { - return ($section === 'category' ? 'categories' : 'weblinks'); - } + public function boot(ContainerInterface $container) + { + $this->getRegistry()->register('weblinksadministrator', new AdministratorService()); + $this->getRegistry()->register('weblinkicon', new Icon($container->get(SiteApplication::class))); + } - /** - * Returns the state column for the count items functions for the given section. - * - * @param string $section The section - * - * @return string|null - * - * @since 4.0.0 - */ - protected function getStateColumnForSection(string $section = null) - { - return 'state'; - } + /** + * Returns a valid section for the given section. If it is not valid then null + * is returned. + * + * @param string $section The section to get the mapping for + * @param object $item The item + * + * @return string|null The new section + * + * @since 4.0.0 + */ + public function validateSection($section, $item = null) + { + if ($section != 'weblink') { + // We don't know other sections + return null; + } + + return $section; + } + + /** + * Returns valid contexts + * + * @return array + * + * @since 4.0.0 + */ + public function getContexts(): array + { + Factory::getLanguage()->load('com_weblinks', JPATH_ADMINISTRATOR); + $contexts = [ + 'com_weblinks.weblink' => Text::_('COM_WEBLINKS'), + ]; + return $contexts; + } + + + /** + * Returns the table for the count items functions for the given section. + * + * @param string $section The section + * + * @return string|null + * + * @since 4.0.0 + */ + protected function getTableNameForSection(string $section = null) + { + return ($section === 'category' ? 'categories' : 'weblinks'); + } + + /** + * Returns the state column for the count items functions for the given section. + * + * @param string $section The section + * + * @return string|null + * + * @since 4.0.0 + */ + protected function getStateColumnForSection(string $section = null) + { + return 'state'; + } } diff --git a/src/administrator/components/com_weblinks/src/Field/Modal/WeblinkField.php b/src/administrator/components/com_weblinks/src/Field/Modal/WeblinkField.php index 07bf11b..f4ad905 100644 --- a/src/administrator/components/com_weblinks/src/Field/Modal/WeblinkField.php +++ b/src/administrator/components/com_weblinks/src/Field/Modal/WeblinkField.php @@ -1,4 +1,5 @@ element['new'] == 'true'); + $allowEdit = ((string) $this->element['edit'] == 'true'); + $allowClear = ((string) $this->element['clear'] != 'false'); + $allowSelect = ((string) $this->element['select'] != 'false'); + // Load language + Factory::getLanguage()->load('com_weblinks', JPATH_ADMINISTRATOR); + // The active weblink id field. + $value = (int) $this->value > 0 ? (int) $this->value : ''; + // Create the modal id. + $modalId = 'Weblink_' . $this->id; + /** @var \Joomla\CMS\WebAsset\WebAssetManager $wa */ + $wa = Factory::getApplication()->getDocument()->getWebAssetManager(); + // Add the modal field script to the document head. + $wa->useScript('field.modal-fields'); + // Script to proxy the select modal function to the modal-fields.js file. + if ($allowSelect) { + static $scriptSelect = null; + if (is_null($scriptSelect)) { + $scriptSelect = []; + } - /** - * Method to get the field input markup. - * - * @return string The field input markup. - * - * @since __DEPLOY_VERSION__ - */ - protected function getInput() - { - $allowNew = ((string) $this->element['new'] == 'true'); - $allowEdit = ((string) $this->element['edit'] == 'true'); - $allowClear = ((string) $this->element['clear'] != 'false'); - $allowSelect = ((string) $this->element['select'] != 'false'); - - // Load language - Factory::getLanguage()->load('com_weblinks', JPATH_ADMINISTRATOR); - - // The active weblink id field. - $value = (int) $this->value > 0 ? (int) $this->value : ''; - - // Create the modal id. - $modalId = 'Weblink_' . $this->id; - - /** @var \Joomla\CMS\WebAsset\WebAssetManager $wa */ - $wa = Factory::getApplication()->getDocument()->getWebAssetManager(); - - // Add the modal field script to the document head. - $wa->useScript('field.modal-fields'); - - // Script to proxy the select modal function to the modal-fields.js file. - if ($allowSelect) - { - static $scriptSelect = null; - - if (is_null($scriptSelect)) - { - $scriptSelect = array(); - } - - if (!isset($scriptSelect[$this->id])) - { - $wa->addInlineScript(" + if (!isset($scriptSelect[$this->id])) { + $wa->addInlineScript( + " window.jSelectWeblink_" . $this->id . " = function (id, title, catid, object, url, language) { window.processModalSelect('Article', '" . $this->id . "', id, title, catid, object, url, language); }", - [], - ['type' => 'module'] - ); + [], + ['type' => 'module'] + ); + Text::script('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED'); + $scriptSelect[$this->id] = true; + } + } - Text::script('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED'); + // Setup variables for display. + $linkWeblinks = 'index.php?option=com_weblinks&view=weblinks&layout=modal&tmpl=component&' . Session::getFormToken() . '=1'; + $linkWeblink = 'index.php?option=com_weblinks&view=weblink&layout=modal&tmpl=component&' . Session::getFormToken() . '=1'; + $modalTitle = Text::_('COM_WEBLINKS_CHANGE_WEBLINK'); + if (isset($this->element['language'])) { + $linkWeblinks .= '&forcedLanguage=' . $this->element['language']; + $linkWeblink .= '&forcedLanguage=' . $this->element['language']; + $modalTitle .= ' — ' . $this->element['label']; + } - $scriptSelect[$this->id] = true; - } - } + $urlSelect = $linkWeblinks . '&function=jSelectWeblink_' . $this->id; + $urlEdit = $linkWeblink . '&task=weblink.edit&id=\' + document.getElementById("' . $this->id . '_id").value + \''; + $urlNew = $linkWeblink . '&task=weblink.add'; + if ($value) { + $db = Factory::getDbo(); + $query = $db->getQuery(true) + ->select($db->quoteName('title')) + ->from($db->quoteName('#__weblinks')) + ->where($db->quoteName('id') . ' = :id') + ->bind(':id', $value, ParameterType::INTEGER); + $db->setQuery($query); + try { + $title = $db->loadResult(); + } catch (\RuntimeException $e) { + Factory::getApplication()->enqueueMessage($e->getMessage(), 'error'); + } + } - // Setup variables for display. - $linkWeblinks = 'index.php?option=com_weblinks&view=weblinks&layout=modal&tmpl=component&' . Session::getFormToken() . '=1'; - $linkWeblink = 'index.php?option=com_weblinks&view=weblink&layout=modal&tmpl=component&' . Session::getFormToken() . '=1'; - $modalTitle = Text::_('COM_WEBLINKS_CHANGE_WEBLINK'); + $title = empty($title) ? Text::_('COM_WEBLINKS_SELECT_A_WEBLINK') : htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); + // The current weblink display field. + $html = ''; + if ($allowSelect || $allowNew || $allowEdit || $allowClear) { + $html .= ''; + } - if (isset($this->element['language'])) - { - $linkWeblinks .= '&forcedLanguage=' . $this->element['language']; - $linkWeblink .= '&forcedLanguage=' . $this->element['language']; - $modalTitle .= ' — ' . $this->element['label']; - } + $html .= ''; + // Select weblink button + if ($allowSelect) { + $html .= '' + . ' ' . Text::_('JSELECT') + . ''; + } - $urlSelect = $linkWeblinks . '&function=jSelectWeblink_' . $this->id; - $urlEdit = $linkWeblink . '&task=weblink.edit&id=\' + document.getElementById("' . $this->id . '_id").value + \''; - $urlNew = $linkWeblink . '&task=weblink.add'; + // New weblink button + if ($allowNew) { + $html .= '' + . ' ' . Text::_('JACTION_CREATE') + . ''; + } - if ($value) - { - $db = Factory::getDbo(); - $query = $db->getQuery(true) - ->select($db->quoteName('title')) - ->from($db->quoteName('#__weblinks')) - ->where($db->quoteName('id') . ' = :id') - ->bind(':id', $value, ParameterType::INTEGER); - $db->setQuery($query); + // Edit weblink button + if ($allowEdit) { + $html .= '' + . ' ' . Text::_('JACTION_EDIT') + . ''; + } - try - { - $title = $db->loadResult(); - } - catch (\RuntimeException $e) - { - Factory::getApplication()->enqueueMessage($e->getMessage(), 'error'); - } - } + // Clear weblink button + if ($allowClear) { + $html .= '' + . ' ' . Text::_('JCLEAR') + . ''; + } - $title = empty($title) ? Text::_('COM_WEBLINKS_SELECT_A_WEBLINK') : htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); + if ($allowSelect || $allowNew || $allowEdit || $allowClear) { + $html .= ''; + } - // The current weblink display field. - $html = ''; + // Select weblink modal + if ($allowSelect) { + $html .= HTMLHelper::_('bootstrap.renderModal', 'ModalSelect' . $modalId, [ + 'title' => $modalTitle, + 'url' => $urlSelect, + 'height' => '400px', + 'width' => '800px', + 'bodyHeight' => 70, + 'modalWidth' => 80, + 'footer' => '', + ]); + } - if ($allowSelect || $allowNew || $allowEdit || $allowClear) - { - $html .= ''; - } + $closeButtonClick = "window.processModalEdit(this, '$this->id', 'add', 'weblink', 'cancel', 'weblink-form'); return false;"; + $saveButtonClick = "window.processModalEdit(this, '$this->id', 'add', 'weblink', 'save', 'weblink-form'); return false;"; + $applyButtonClick = "window.processModalEdit(this, '$this->id', 'add', 'weblink', 'apply', 'weblink-form'); return false;"; + // New weblink modal + if ($allowNew) { + $html .= HTMLHelper::_('bootstrap.renderModal', 'ModalNew' . $modalId, [ + 'title' => Text::_('COM_WEBLINKS_NEW_WEBLINK'), + 'backdrop' => 'static', + 'keyboard' => false, + 'closeButton' => false, + 'url' => $urlNew, + 'height' => '400px', + 'width' => '800px', + 'bodyHeight' => '70', + 'modalWidth' => '80', + 'footer' => '' + . '' + . '', + ]); + } - $html .= ''; + // Edit weblink modal + if ($allowEdit) { + $html .= HTMLHelper::_('bootstrap.renderModal', 'ModalEdit' . $modalId, [ + 'title' => Text::_('COM_WEBLINKS_EDIT_WEBLINK'), + 'backdrop' => 'static', + 'keyboard' => false, + 'closeButton' => false, + 'url' => $urlEdit, + 'height' => '400px', + 'width' => '800px', + 'bodyHeight' => '70', + 'modalWidth' => '80', + 'footer' => '' + . '' + . '', + ]); + } - // Select weblink button - if ($allowSelect) - { - $html .= '' - . ' ' . Text::_('JSELECT') - . ''; - } + // Note: class='required' for client side validation. + $class = $this->required ? ' class="required modal-value"' : ''; + $html .= ''; + return $html; + } - // New weblink button - if ($allowNew) - { - $html .= '' - . ' ' . Text::_('JACTION_CREATE') - . ''; - } - - // Edit weblink button - if ($allowEdit) - { - $html .= '' - . ' ' . Text::_('JACTION_EDIT') - . ''; - } - - // Clear weblink button - if ($allowClear) - { - $html .= '' - . ' ' . Text::_('JCLEAR') - . ''; - } - - if ($allowSelect || $allowNew || $allowEdit || $allowClear) - { - $html .= ''; - } - - // Select weblink modal - if ($allowSelect) - { - $html .= HTMLHelper::_( - 'bootstrap.renderModal', - 'ModalSelect' . $modalId, - array( - 'title' => $modalTitle, - 'url' => $urlSelect, - 'height' => '400px', - 'width' => '800px', - 'bodyHeight' => 70, - 'modalWidth' => 80, - 'footer' => '', - ) - ); - } - - $closeButtonClick = "window.processModalEdit(this, '$this->id', 'add', 'weblink', 'cancel', 'weblink-form'); return false;"; - $saveButtonClick = "window.processModalEdit(this, '$this->id', 'add', 'weblink', 'save', 'weblink-form'); return false;"; - $applyButtonClick = "window.processModalEdit(this, '$this->id', 'add', 'weblink', 'apply', 'weblink-form'); return false;"; - - // New weblink modal - if ($allowNew) - { - $html .= HTMLHelper::_( - 'bootstrap.renderModal', - 'ModalNew' . $modalId, - array( - 'title' => Text::_('COM_WEBLINKS_NEW_WEBLINK'), - 'backdrop' => 'static', - 'keyboard' => false, - 'closeButton' => false, - 'url' => $urlNew, - 'height' => '400px', - 'width' => '800px', - 'bodyHeight' => '70', - 'modalWidth' => '80', - 'footer' => '' - . '' - . '', - ) - ); - } - - // Edit weblink modal - if ($allowEdit) - { - $html .= HTMLHelper::_( - 'bootstrap.renderModal', - 'ModalEdit' . $modalId, - array( - 'title' => Text::_('COM_WEBLINKS_EDIT_WEBLINK'), - 'backdrop' => 'static', - 'keyboard' => false, - 'closeButton' => false, - 'url' => $urlEdit, - 'height' => '400px', - 'width' => '800px', - 'bodyHeight' => '70', - 'modalWidth' => '80', - 'footer' => '' - . '' - . '', - ) - ); - } - - // Note: class='required' for client side validation. - $class = $this->required ? ' class="required modal-value"' : ''; - $html .= ''; - - return $html; - } - - /** - * Method to get the field label markup. - * - * @return string The field label markup. - * - * @since __DEPLOY_VERSION__ - */ - protected function getLabel() - { - return str_replace($this->id, $this->id . '_name', parent::getLabel()); - } + /** + * Method to get the field label markup. + * + * @return string The field label markup. + * + * @since __DEPLOY_VERSION__ + */ + protected function getLabel() + { + return str_replace($this->id, $this->id . '_name', parent::getLabel()); + } } diff --git a/src/administrator/components/com_weblinks/src/Helper/AssociationsHelper.php b/src/administrator/components/com_weblinks/src/Helper/AssociationsHelper.php index 45d4129..5ee4d89 100644 --- a/src/administrator/components/com_weblinks/src/Helper/AssociationsHelper.php +++ b/src/administrator/components/com_weblinks/src/Helper/AssociationsHelper.php @@ -1,4 +1,5 @@ getType($typeName); + /** + * Get the associated items for an item + * + * @param string $typeName The item type + * @param int $id The id of item for which we need the associated items + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public function getAssociations($typeName, $id) + { + $type = $this->getType($typeName); + $context = $this->extension . '.item'; + $catidField = 'catid'; + if ($typeName === 'category') { + $context = 'com_categories.item'; + $catidField = ''; + } - $context = $this->extension . '.item'; - $catidField = 'catid'; + // Get the associations. + $associations = Associations::getAssociations($this->extension, $type['tables']['a'], $context, $id, 'id', 'alias', $catidField); + return $associations; + } - if ($typeName === 'category') - { - $context = 'com_categories.item'; - $catidField = ''; - } + /** + * Get item information + * + * @param string $typeName The item type + * @param int $id The id of item for which we need the associated items + * + * @return Table|null + * + * @since __DEPLOY_VERSION__ + */ + public function getItem($typeName, $id) + { + if (empty($id)) { + return null; + } - // Get the associations. - $associations = Associations::getAssociations( - $this->extension, - $type['tables']['a'], - $context, - $id, - 'id', - 'alias', - $catidField - ); + $table = null; + switch ($typeName) { + case 'weblink': + $table = Table::getInstance('WeblinkTable', 'Joomla\\Component\\Weblinks\\Administrator\\Table\\'); - return $associations; - } + break; + case 'category': + $table = Table::getInstance('Category', 'Joomla\\CMS\\Table\\'); - /** - * Get item information - * - * @param string $typeName The item type - * @param int $id The id of item for which we need the associated items - * - * @return Table|null - * - * @since __DEPLOY_VERSION__ - */ - public function getItem($typeName, $id) - { - if (empty($id)) - { - return null; - } + break; + } - $table = null; + if (empty($table)) { + return null; + } - switch ($typeName) - { - case 'weblink': - $table = Table::getInstance('WeblinkTable', 'Joomla\\Component\\Weblinks\\Administrator\\Table\\'); - break; + $table->load($id); + return $table; + } - case 'category': - $table = Table::getInstance('Category', 'Joomla\\CMS\\Table\\'); - break; - } + /** + * Get information about the type + * + * @param string $typeName The item type + * + * @return array Array of item types + * + * @since __DEPLOY_VERSION__ + */ + public function getType($typeName = '') + { + $fields = $this->getFieldsTemplate(); + $tables = []; + $joins = []; + $support = $this->getSupportTemplate(); + $title = ''; + if (in_array($typeName, $this->itemTypes)) { + switch ($typeName) { + case 'weblink': + $support['state'] = true; + $support['acl'] = true; + $support['checkout'] = true; + $support['category'] = true; + $support['save2copy'] = true; + $tables = [ + 'a' => '#__weblinks', + ]; + $title = 'weblink'; - if (empty($table)) - { - return null; - } + break; + case 'category': + $fields['created_user_id'] = 'a.created_user_id'; + $fields['ordering'] = 'a.lft'; + $fields['level'] = 'a.level'; + $fields['catid'] = ''; + $fields['state'] = 'a.published'; + $support['state'] = true; + $support['acl'] = true; + $support['checkout'] = true; + $support['level'] = true; + $tables = [ + 'a' => '#__categories', + ]; + $title = 'category'; - $table->load($id); + break; + } + } - return $table; - } - - /** - * Get information about the type - * - * @param string $typeName The item type - * - * @return array Array of item types - * - * @since __DEPLOY_VERSION__ - */ - public function getType($typeName = '') - { - $fields = $this->getFieldsTemplate(); - $tables = array(); - $joins = array(); - $support = $this->getSupportTemplate(); - $title = ''; - - if (in_array($typeName, $this->itemTypes)) - { - switch ($typeName) - { - case 'weblink': - - $support['state'] = true; - $support['acl'] = true; - $support['checkout'] = true; - $support['category'] = true; - $support['save2copy'] = true; - - $tables = array( - 'a' => '#__weblinks', - ); - - $title = 'weblink'; - break; - - case 'category': - $fields['created_user_id'] = 'a.created_user_id'; - $fields['ordering'] = 'a.lft'; - $fields['level'] = 'a.level'; - $fields['catid'] = ''; - $fields['state'] = 'a.published'; - - $support['state'] = true; - $support['acl'] = true; - $support['checkout'] = true; - $support['level'] = true; - - $tables = array( - 'a' => '#__categories', - ); - - $title = 'category'; - break; - } - } - - return array( - 'fields' => $fields, - 'support' => $support, - 'tables' => $tables, - 'joins' => $joins, - 'title' => $title, - ); - } + return [ + 'fields' => $fields, + 'support' => $support, + 'tables' => $tables, + 'joins' => $joins, + 'title' => $title, + ]; + } } diff --git a/src/administrator/components/com_weblinks/src/Helper/WeblinksHelper.php b/src/administrator/components/com_weblinks/src/Helper/WeblinksHelper.php index 823b8c7..816b207 100644 --- a/src/administrator/components/com_weblinks/src/Helper/WeblinksHelper.php +++ b/src/administrator/components/com_weblinks/src/Helper/WeblinksHelper.php @@ -1,4 +1,5 @@ id) || $record->state != -2) - { - return false; - } + /** + * Method to test whether a record can be deleted. + * + * @param object $record A record object. + * + * @return boolean True if allowed to delete the record. Defaults to the permission for the component. + * + * @since 1.6 + */ + protected function canDelete($record) + { + if (empty($record->id) || $record->state != -2) { + return false; + } - return $this->getCurrentUser()->authorise('core.delete', 'com_weblinks.category.' . (int) $record->catid); - } + return $this->getCurrentUser()->authorise('core.delete', 'com_weblinks.category.' . (int) $record->catid); + } - /** - * Method to test whether a record can be deleted. - * - * @param object $record A record object. - * - * @return boolean True if allowed to change the state of the record. Defaults to the permission for the component. - * - * @since 1.6 - */ - protected function canEditState($record) - { - if (!empty($record->catid)) - { - return $this->getCurrentUser()->authorise('core.edit.state', 'com_weblinks.category.' . (int) $record->catid); - } + /** + * Method to test whether a record can be deleted. + * + * @param object $record A record object. + * + * @return boolean True if allowed to change the state of the record. Defaults to the permission for the component. + * + * @since 1.6 + */ + protected function canEditState($record) + { + if (!empty($record->catid)) { + return $this->getCurrentUser()->authorise('core.edit.state', 'com_weblinks.category.' . (int) $record->catid); + } - return parent::canEditState($record); - } + return parent::canEditState($record); + } - /** - * Abstract method for getting the form from the model. - * - * @param array $data Data for the form. - * @param boolean $loadData True if the form is to load its own data (default case), false if not. - * - * @return mixed A JForm object on success, false on failure - * - * @since 1.6 - */ - public function getForm($data = array(), $loadData = true) - { - // Get the form. - $form = $this->loadForm('com_weblinks.weblink', 'weblink', array('control' => 'jform', 'load_data' => $loadData)); + /** + * Abstract method for getting the form from the model. + * + * @param array $data Data for the form. + * @param boolean $loadData True if the form is to load its own data (default case), false if not. + * + * @return mixed A JForm object on success, false on failure + * + * @since 1.6 + */ + public function getForm($data = [], $loadData = true) + { + // Get the form. + $form = $this->loadForm('com_weblinks.weblink', 'weblink', ['control' => 'jform', 'load_data' => $loadData]); - if (empty($form)) - { - return false; - } + if (empty($form)) { + return false; + } - // Determine correct permissions to check. - if ($this->getState('weblink.id')) - { - // Existing record. Can only edit in selected categories. - $form->setFieldAttribute('catid', 'action', 'core.edit'); - } - else - { - // New record. Can only create in selected categories. - $form->setFieldAttribute('catid', 'action', 'core.create'); - } + // Determine correct permissions to check. + if ($this->getState('weblink.id')) { + // Existing record. Can only edit in selected categories. + $form->setFieldAttribute('catid', 'action', 'core.edit'); + } else { + // New record. Can only create in selected categories. + $form->setFieldAttribute('catid', 'action', 'core.create'); + } - // Modify the form based on access controls. - if (!$this->canEditState((object) $data)) - { - // Disable fields for display. - $form->setFieldAttribute('ordering', 'disabled', 'true'); - $form->setFieldAttribute('state', 'disabled', 'true'); - $form->setFieldAttribute('publish_up', 'disabled', 'true'); - $form->setFieldAttribute('publish_down', 'disabled', 'true'); + // Modify the form based on access controls. + if (!$this->canEditState((object) $data)) { + // Disable fields for display. + $form->setFieldAttribute('ordering', 'disabled', 'true'); + $form->setFieldAttribute('state', 'disabled', 'true'); + $form->setFieldAttribute('publish_up', 'disabled', 'true'); + $form->setFieldAttribute('publish_down', 'disabled', 'true'); - // Disable fields while saving. - // The controller has already verified this is a record you can edit. - $form->setFieldAttribute('ordering', 'filter', 'unset'); - $form->setFieldAttribute('state', 'filter', 'unset'); - $form->setFieldAttribute('publish_up', 'filter', 'unset'); - $form->setFieldAttribute('publish_down', 'filter', 'unset'); - } + // Disable fields while saving. + // The controller has already verified this is a record you can edit. + $form->setFieldAttribute('ordering', 'filter', 'unset'); + $form->setFieldAttribute('state', 'filter', 'unset'); + $form->setFieldAttribute('publish_up', 'filter', 'unset'); + $form->setFieldAttribute('publish_down', 'filter', 'unset'); + } - // Don't allow to change the created_by user if not allowed to access com_users. - if (!$this->getCurrentUser()->authorise('core.manage', 'com_users')) - { - $form->setFieldAttribute('created_by', 'filter', 'unset'); - } + // Don't allow to change the created_by user if not allowed to access com_users. + if (!$this->getCurrentUser()->authorise('core.manage', 'com_users')) { + $form->setFieldAttribute('created_by', 'filter', 'unset'); + } - return $form; - } + return $form; + } - /** - * Method to get the data that should be injected in the form. - * - * @return array The default data is an empty array. - * - * @since 1.6 - */ - protected function loadFormData() - { - $app = Factory::getApplication(); + /** + * Method to get the data that should be injected in the form. + * + * @return array The default data is an empty array. + * + * @since 1.6 + */ + protected function loadFormData() + { + $app = Factory::getApplication(); - // Check the session for previously entered form data. - $data = $app->getUserState('com_weblinks.edit.weblink.data', array()); + // Check the session for previously entered form data. + $data = $app->getUserState('com_weblinks.edit.weblink.data', []); - if (empty($data)) - { - $data = $this->getItem(); + if (empty($data)) { + $data = $this->getItem(); - // Prime some default values. - if ($this->getState('weblink.id') == 0) - { - $data->set('catid', $app->input->get('catid', $app->getUserState('com_weblinks.weblinks.filter.category_id'), 'int')); - } - } + // Prime some default values. + if ($this->getState('weblink.id') == 0) { + $data->set('catid', $app->input->get('catid', $app->getUserState('com_weblinks.weblinks.filter.category_id'), 'int')); + } + } - $this->preprocessData('com_weblinks.weblink', $data); + $this->preprocessData('com_weblinks.weblink', $data); - return $data; - } + return $data; + } - /** - * Method to get a single record. - * - * @param integer $pk The id of the primary key. - * - * @return mixed Object on success, false on failure. - * - * @since 1.6 - */ - public function getItem($pk = null) - { - if ($item = parent::getItem($pk)) - { - // Convert the metadata field to an array. - $registry = new Registry($item->metadata ?? ''); - $item->metadata = $registry->toArray(); + /** + * Method to get a single record. + * + * @param integer $pk The id of the primary key. + * + * @return mixed Object on success, false on failure. + * + * @since 1.6 + */ + public function getItem($pk = null) + { + if ($item = parent::getItem($pk)) { + // Convert the metadata field to an array. + $registry = new Registry($item->metadata ?? ''); + $item->metadata = $registry->toArray(); - // Convert the images field to an array. - $registry = new Registry($item->images ?? ''); - $item->images = $registry->toArray(); + // Convert the images field to an array. + $registry = new Registry($item->images ?? ''); + $item->images = $registry->toArray(); - // Load associated web links items - $assoc = Associations::isEnabled(); + // Load associated web links items + $assoc = Associations::isEnabled(); - if ($assoc) - { - $item->associations = array(); + if ($assoc) { + $item->associations = []; - if ($item->id != null) - { - $associations = Associations::getAssociations('com_weblinks', '#__weblinks', 'com_weblinks.item', $item->id); + if ($item->id != null) { + $associations = Associations::getAssociations('com_weblinks', '#__weblinks', 'com_weblinks.item', $item->id); - foreach ($associations as $tag => $association) - { - $item->associations[$tag] = $association->id; - } - } - } + foreach ($associations as $tag => $association) { + $item->associations[$tag] = $association->id; + } + } + } - if (!empty($item->id)) - { - $item->tags = new TagsHelper; - $item->tags->getTagIds($item->id, 'com_weblinks.weblink'); - $item->metadata['tags'] = $item->tags; - } - } + if (!empty($item->id)) { + $item->tags = new TagsHelper(); + $item->tags->getTagIds($item->id, 'com_weblinks.weblink'); + $item->metadata['tags'] = $item->tags; + } + } - return $item; - } + return $item; + } - /** - * Prepare and sanitise the table data prior to saving. - * - * @param \Joomla\CMS\Table\Table $table A reference to a JTable object. - * - * @return void - * - * @since 1.6 - */ - protected function prepareTable($table) - { - $date = Factory::getDate(); - $user = $this->getCurrentUser(); + /** + * Prepare and sanitise the table data prior to saving. + * + * @param \Joomla\CMS\Table\Table $table A reference to a JTable object. + * + * @return void + * + * @since 1.6 + */ + protected function prepareTable($table) + { + $date = Factory::getDate(); + $user = $this->getCurrentUser(); - $table->title = htmlspecialchars_decode($table->title, ENT_QUOTES); - $table->alias = ApplicationHelper::stringURLSafe($table->alias); + $table->title = htmlspecialchars_decode($table->title, ENT_QUOTES); + $table->alias = ApplicationHelper::stringURLSafe($table->alias); - if (empty($table->alias)) - { - $table->alias = ApplicationHelper::stringURLSafe($table->title); - } + if (empty($table->alias)) { + $table->alias = ApplicationHelper::stringURLSafe($table->title); + } - if (empty($table->id)) - { - // Set the values + if (empty($table->id)) { + // Set the values - // Set ordering to the last item if not set - if (empty($table->ordering)) - { - $db = $this->getDatabase(); - $query = $db->getQuery(true) - ->select('MAX(ordering)') - ->from($db->quoteName('#__weblinks')); + // Set ordering to the last item if not set + if (empty($table->ordering)) { + $db = $this->getDatabase(); + $query = $db->getQuery(true) + ->select('MAX(ordering)') + ->from($db->quoteName('#__weblinks')); - $db->setQuery($query); - $max = $db->loadResult(); + $db->setQuery($query); + $max = $db->loadResult(); - $table->ordering = $max + 1; - } - else - { - // Set the values - $table->modified = $date->toSql(); - $table->modified_by = $user->id; - } - } + $table->ordering = $max + 1; + } else { + // Set the values + $table->modified = $date->toSql(); + $table->modified_by = $user->id; + } + } - // Increment the weblink version number. - $table->version++; - } + // Increment the weblink version number. + $table->version++; + } - /** - * A protected method to get a set of ordering conditions. - * - * @param \Joomla\CMS\Table\Table $table A JTable object. - * - * @return array An array of conditions to add to ordering queries. - * - * @since 1.6 - */ - protected function getReorderConditions($table) - { - $condition = array(); - $condition[] = 'catid = ' . (int) $table->catid; + /** + * A protected method to get a set of ordering conditions. + * + * @param \Joomla\CMS\Table\Table $table A JTable object. + * + * @return array An array of conditions to add to ordering queries. + * + * @since 1.6 + */ + protected function getReorderConditions($table) + { + $condition = []; + $condition[] = 'catid = ' . (int) $table->catid; - return $condition; - } + return $condition; + } - /** - * Method to save the form data. - * - * @param array $data The form data. - * - * @return boolean True on success. - * - * @since 3.1 - */ - public function save($data) - { - $app = Factory::getApplication(); + /** + * Method to save the form data. + * + * @param array $data The form data. + * + * @return boolean True on success. + * + * @since 3.1 + */ + public function save($data) + { + $app = Factory::getApplication(); - // Cast catid to integer for comparison - $catid = (int) $data['catid']; + // Cast catid to integer for comparison + $catid = (int) $data['catid']; - // Check if New Category exists - if ($catid > 0) - { - $catid = CategoriesHelper::validateCategoryId($data['catid'], 'com_weblinks'); - } + // Check if New Category exists + if ($catid > 0) { + $catid = CategoriesHelper::validateCategoryId($data['catid'], 'com_weblinks'); + } - // Save New Category - if ($catid == 0 && $this->canCreateCategory()) - { - $table = array(); - $table['title'] = $data['catid']; - $table['parent_id'] = 1; - $table['extension'] = 'com_weblinks'; - $table['language'] = $data['language']; - $table['published'] = 1; + // Save New Category + if ($catid == 0 && $this->canCreateCategory()) { + $table = []; + $table['title'] = $data['catid']; + $table['parent_id'] = 1; + $table['extension'] = 'com_weblinks'; + $table['language'] = $data['language']; + $table['published'] = 1; - // Create new category and get catid back - $data['catid'] = CategoriesHelper::createCategory($table); - } + // Create new category and get catid back + $data['catid'] = CategoriesHelper::createCategory($table); + } - // Alter the title for save as copy - if ($app->input->get('task') == 'save2copy') - { - [$name, $alias] = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']); - $data['title'] = $name; - $data['alias'] = $alias; - $data['state'] = 0; - } + // Alter the title for save as copy + if ($app->input->get('task') == 'save2copy') { + [$name, $alias] = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']); + $data['title'] = $name; + $data['alias'] = $alias; + $data['state'] = 0; + } - return parent::save($data); - } + return parent::save($data); + } - /** - * Method to change the title & alias. - * - * @param integer $category_id The id of the parent. - * @param string $alias The alias. - * @param string $name The title. - * - * @return array Contains the modified title and alias. - * - * @since 3.1 - */ - protected function generateNewTitle($category_id, $alias, $name) - { - // Alter the title & alias - $table = $this->getTable(); + /** + * Method to change the title & alias. + * + * @param integer $category_id The id of the parent. + * @param string $alias The alias. + * @param string $name The title. + * + * @return array Contains the modified title and alias. + * + * @since 3.1 + */ + protected function generateNewTitle($category_id, $alias, $name) + { + // Alter the title & alias + $table = $this->getTable(); - while ($table->load(array('alias' => $alias, 'catid' => $category_id))) - { - if ($name == $table->title) - { - $name = StringHelper::increment($name); - } + while ($table->load(['alias' => $alias, 'catid' => $category_id])) { + if ($name == $table->title) { + $name = StringHelper::increment($name); + } - $alias = StringHelper::increment($alias, 'dash'); - } + $alias = StringHelper::increment($alias, 'dash'); + } - return array($name, $alias); - } + return [$name, $alias]; + } - /** - * Allows preprocessing of the JForm object. - * - * @param \JForm $form The form object - * @param array $data The data to be merged into the form object - * @param string $group The plugin group to be executed - * - * @return void - * - * @since 3.6.0 - */ - protected function preprocessForm(\JForm $form, $data, $group = 'content') - { - if ($this->canCreateCategory()) - { - $form->setFieldAttribute('catid', 'allowAdd', 'true'); - } + /** + * Allows preprocessing of the JForm object. + * + * @param \JForm $form The form object + * @param array $data The data to be merged into the form object + * @param string $group The plugin group to be executed + * + * @return void + * + * @since 3.6.0 + */ + protected function preprocessForm(\JForm $form, $data, $group = 'content') + { + if ($this->canCreateCategory()) { + $form->setFieldAttribute('catid', 'allowAdd', 'true'); + } - // Association weblinks items - if (Associations::isEnabled()) - { - $languages = LanguageHelper::getContentLanguages(false, false, null, 'ordering', 'asc'); + // Association weblinks items + if (Associations::isEnabled()) { + $languages = LanguageHelper::getContentLanguages(false, false, null, 'ordering', 'asc'); - if (count($languages) > 1) - { - $addform = new \SimpleXMLElement('
'); - $fields = $addform->addChild('fields'); - $fields->addAttribute('name', 'associations'); - $fieldset = $fields->addChild('fieldset'); - $fieldset->addAttribute('name', 'item_associations'); + if (count($languages) > 1) { + $addform = new \SimpleXMLElement(''); + $fields = $addform->addChild('fields'); + $fields->addAttribute('name', 'associations'); + $fieldset = $fields->addChild('fieldset'); + $fieldset->addAttribute('name', 'item_associations'); - foreach ($languages as $language) - { - $field = $fieldset->addChild('field'); - $field->addAttribute('name', $language->lang_code); - $field->addAttribute('type', 'modal_weblink'); - $field->addAttribute('language', $language->lang_code); - $field->addAttribute('label', $language->title); - $field->addAttribute('translate_label', 'false'); - $field->addAttribute('select', 'true'); - $field->addAttribute('new', 'true'); - $field->addAttribute('edit', 'true'); - $field->addAttribute('clear', 'true'); - $field->addAttribute('addfieldprefix', 'Joomla\\Component\\Weblinks\\Administrator\\Field'); - } + foreach ($languages as $language) { + $field = $fieldset->addChild('field'); + $field->addAttribute('name', $language->lang_code); + $field->addAttribute('type', 'modal_weblink'); + $field->addAttribute('language', $language->lang_code); + $field->addAttribute('label', $language->title); + $field->addAttribute('translate_label', 'false'); + $field->addAttribute('select', 'true'); + $field->addAttribute('new', 'true'); + $field->addAttribute('edit', 'true'); + $field->addAttribute('clear', 'true'); + $field->addAttribute('addfieldprefix', 'Joomla\\Component\\Weblinks\\Administrator\\Field'); + } - $form->load($addform, false); - } - } + $form->load($addform, false); + } + } - parent::preprocessForm($form, $data, $group); - } + parent::preprocessForm($form, $data, $group); + } - /** - * Is the user allowed to create an on the fly category? - * - * @return bool - * - * @since 3.6.0 - */ - private function canCreateCategory() - { - return $this->getCurrentUser()->authorise('core.create', 'com_weblinks'); - } + /** + * Is the user allowed to create an on the fly category? + * + * @return bool + * + * @since 3.6.0 + */ + private function canCreateCategory() + { + return $this->getCurrentUser()->authorise('core.create', 'com_weblinks'); + } } diff --git a/src/administrator/components/com_weblinks/src/Model/WeblinksModel.php b/src/administrator/components/com_weblinks/src/Model/WeblinksModel.php index 6a127f6..33339a8 100644 --- a/src/administrator/components/com_weblinks/src/Model/WeblinksModel.php +++ b/src/administrator/components/com_weblinks/src/Model/WeblinksModel.php @@ -1,4 +1,5 @@ input->get('forcedLanguage', '', 'cmd'); + $forcedLanguage = $app->input->get('forcedLanguage', '', 'cmd'); - // Adjust the context to support modal layouts. - if ($layout = $app->input->get('layout')) - { - $this->context .= '.' . $layout; - } + // Adjust the context to support modal layouts. + if ($layout = $app->input->get('layout')) { + $this->context .= '.' . $layout; + } - // Adjust the context to support forced languages. - if ($forcedLanguage) - { - $this->context .= '.' . $forcedLanguage; - } + // Adjust the context to support forced languages. + if ($forcedLanguage) { + $this->context .= '.' . $forcedLanguage; + } - // Load the parameters. - $params = ComponentHelper::getParams('com_weblinks'); - $this->setState('params', $params); + // Load the parameters. + $params = ComponentHelper::getParams('com_weblinks'); + $this->setState('params', $params); - // Force a language. - if (!empty($forcedLanguage)) - { - $this->setState('filter.language', $forcedLanguage); - } + // Force a language. + if (!empty($forcedLanguage)) { + $this->setState('filter.language', $forcedLanguage); + } - // List state information. - parent::populateState($ordering, $direction); - } + // List state information. + parent::populateState($ordering, $direction); + } - /** - * Method to get a store id based on model configuration state. - * - * This is necessary because the model is used by the component and - * different modules that might need different sets of data or different - * ordering requirements. - * - * @param string $id A prefix for the store id. - * - * @return string A store id. - * - * @since 1.6 - */ - protected function getStoreId($id = '') - { - // Compile the store id. - $id .= ':' . $this->getState('filter.search'); - $id .= ':' . $this->getState('filter.access'); - $id .= ':' . $this->getState('filter.published'); - $id .= ':' . $this->getState('filter.category_id'); - $id .= ':' . $this->getState('filter.language'); - $id .= ':' . $this->getState('filter.tag'); - $id .= ':' . $this->getState('filter.level'); + /** + * Method to get a store id based on model configuration state. + * + * This is necessary because the model is used by the component and + * different modules that might need different sets of data or different + * ordering requirements. + * + * @param string $id A prefix for the store id. + * + * @return string A store id. + * + * @since 1.6 + */ + protected function getStoreId($id = '') + { + // Compile the store id. + $id .= ':' . $this->getState('filter.search'); + $id .= ':' . $this->getState('filter.access'); + $id .= ':' . $this->getState('filter.published'); + $id .= ':' . $this->getState('filter.category_id'); + $id .= ':' . $this->getState('filter.language'); + $id .= ':' . $this->getState('filter.tag'); + $id .= ':' . $this->getState('filter.level'); - return parent::getStoreId($id); - } + return parent::getStoreId($id); + } - /** - * Build an SQL query to load the list data. - * - * @return \JDatabaseQuery - * - * @since 1.6 - */ - protected function getListQuery() - { - // Create a new query object. - $db = $this->getDatabase(); - $query = $db->getQuery(true); - $user = $this->getCurrentUser(); + /** + * Build an SQL query to load the list data. + * + * @return \JDatabaseQuery + * + * @since 1.6 + */ + protected function getListQuery() + { + // Create a new query object. + $db = $this->getDatabase(); + $query = $db->getQuery(true); + $user = $this->getCurrentUser(); - // Select the required fields from the table. - $query->select( - $this->getState( - 'list.select', - 'a.id, a.title, a.alias, a.checked_out, a.checked_out_time, a.catid, a.created, a.created_by, ' . - 'a.hits, a.state, a.access, a.ordering, a.language, a.publish_up, a.publish_down' - ) - ); - $query->from($db->quoteName('#__weblinks', 'a')); + // Select the required fields from the table. + $query->select( + $this->getState( + 'list.select', + 'a.id, a.title, a.alias, a.checked_out, a.checked_out_time, a.catid, a.created, a.created_by, ' . + 'a.hits, a.state, a.access, a.ordering, a.language, a.publish_up, a.publish_down' + ) + ); + $query->from($db->quoteName('#__weblinks', 'a')); - // Join over the language - $query->select($db->quoteName('l.title', 'language_title')) - ->select($db->quoteName('l.image', 'language_image')) - ->join('LEFT', $db->quoteName('#__languages', 'l') . ' ON ' . $db->qn('l.lang_code') . ' = ' . $db->qn('a.language')); + // Join over the language + $query->select($db->quoteName('l.title', 'language_title')) + ->select($db->quoteName('l.image', 'language_image')) + ->join('LEFT', $db->quoteName('#__languages', 'l') . ' ON ' . $db->qn('l.lang_code') . ' = ' . $db->qn('a.language')); - // Join over the users for the checked out user. - $query->select($db->quoteName('uc.name', 'editor')) - ->join('LEFT', $db->quoteName('#__users', 'uc') . ' ON ' . $db->qn('uc.id') . ' = ' . $db->qn('a.checked_out')); + // Join over the users for the checked out user. + $query->select($db->quoteName('uc.name', 'editor')) + ->join('LEFT', $db->quoteName('#__users', 'uc') . ' ON ' . $db->qn('uc.id') . ' = ' . $db->qn('a.checked_out')); - // Join over the asset groups. - $query->select($db->quoteName('ag.title', 'access_level')) - ->join('LEFT', $db->quoteName('#__viewlevels', 'ag') . ' ON ' . $db->qn('ag.id') . ' = ' . $db->qn('a.access')); + // Join over the asset groups. + $query->select($db->quoteName('ag.title', 'access_level')) + ->join('LEFT', $db->quoteName('#__viewlevels', 'ag') . ' ON ' . $db->qn('ag.id') . ' = ' . $db->qn('a.access')); - // Join over the categories. - $query->select('c.title AS category_title') - ->join('LEFT', $db->quoteName('#__categories', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('a.catid')); + // Join over the categories. + $query->select('c.title AS category_title') + ->join('LEFT', $db->quoteName('#__categories', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('a.catid')); - // Join over the associations. - $assoc = Associations::isEnabled(); + // Join over the associations. + $assoc = Associations::isEnabled(); - if ($assoc) - { - $query->select('COUNT(asso2.id)>1 AS association') - ->join('LEFT', $db->quoteName('#__associations', 'asso') . ' ON asso.id = a.id AND asso.context = ' . $db->quote('com_weblinks.item')) - ->join('LEFT', $db->quoteName('#__associations', 'asso2') . ' ON asso2.key = asso.key') - ->group('a.id, l.title, l.image, uc.name, ag.title, c.title'); - } + if ($assoc) { + $query->select('COUNT(asso2.id)>1 AS association') + ->join('LEFT', $db->quoteName('#__associations', 'asso') . ' ON asso.id = a.id AND asso.context = ' . $db->quote('com_weblinks.item')) + ->join('LEFT', $db->quoteName('#__associations', 'asso2') . ' ON asso2.key = asso.key') + ->group('a.id, l.title, l.image, uc.name, ag.title, c.title'); + } - // Filter by access level. - if ($access = $this->getState('filter.access')) - { - $query->where($db->quoteName('a.access') . ' = :access') - ->bind(':access', $access, ParameterType::INTEGER); - } + // Filter by access level. + if ($access = $this->getState('filter.access')) { + $query->where($db->quoteName('a.access') . ' = :access') + ->bind(':access', $access, ParameterType::INTEGER); + } - // Implement View Level Access - if (!$user->authorise('core.admin')) - { - $query->whereIn($db->quoteName('a.access'), $user->getAuthorisedViewLevels()); - } + // Implement View Level Access + if (!$user->authorise('core.admin')) { + $query->whereIn($db->quoteName('a.access'), $user->getAuthorisedViewLevels()); + } - // Filter by published state - $published = (string) $this->getState('filter.published'); + // Filter by published state + $published = (string) $this->getState('filter.published'); - if (is_numeric($published)) - { - $query->where($db->quoteName('a.state') . ' = :state') - ->bind(':state', $published, ParameterType::INTEGER); - } - elseif ($published === '') - { - $query->whereIn($db->quoteName('a.state'), [0, 1]); - } + if (is_numeric($published)) { + $query->where($db->quoteName('a.state') . ' = :state') + ->bind(':state', $published, ParameterType::INTEGER); + } elseif ($published === '') { + $query->whereIn($db->quoteName('a.state'), [0, 1]); + } - // Filter by category. - $categoryId = $this->getState('filter.category_id'); + // Filter by category. + $categoryId = $this->getState('filter.category_id'); - if (is_numeric($categoryId)) - { - $query->where($db->quoteName('a.catid') . ' = :catid') - ->bind(':catid', $categoryId, ParameterType::INTEGER); - } + if (is_numeric($categoryId)) { + $query->where($db->quoteName('a.catid') . ' = :catid') + ->bind(':catid', $categoryId, ParameterType::INTEGER); + } - // Filter on the level. - if ($level = $this->getState('filter.level')) - { - $query->where($db->quoteName('c.level') . ' <= :level') - ->bind(':level', $level, ParameterType::INTEGER); - } + // Filter on the level. + if ($level = $this->getState('filter.level')) { + $query->where($db->quoteName('c.level') . ' <= :level') + ->bind(':level', $level, ParameterType::INTEGER); + } - // Filter by search in title - $search = $this->getState('filter.search'); + // Filter by search in title + $search = $this->getState('filter.search'); - if (!empty($search)) - { - if (stripos($search, 'id:') === 0) - { - $search = substr($search, 3); - $query->where($db->quoteName('a.id') . ' = :id') - ->bind(':id', $search, ParameterType::INTEGER); - } - else - { - $search = '%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'); - $query->where('(' . $db->quoteName('a.title') . ' LIKE :title OR ' . $db->quoteName('a.alias') . ' LIKE :alias)') - ->bind(':title', $search) - ->bind(':alias', $search); - } - } + if (!empty($search)) { + if (stripos($search, 'id:') === 0) { + $search = substr($search, 3); + $query->where($db->quoteName('a.id') . ' = :id') + ->bind(':id', $search, ParameterType::INTEGER); + } else { + $search = '%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'); + $query->where('(' . $db->quoteName('a.title') . ' LIKE :title OR ' . $db->quoteName('a.alias') . ' LIKE :alias)') + ->bind(':title', $search) + ->bind(':alias', $search); + } + } - // Filter on the language. - if ($language = $this->getState('filter.language')) - { - $query->where($db->quoteName('a.language') . ' = :language') - ->bind(':language', $language); - } + // Filter on the language. + if ($language = $this->getState('filter.language')) { + $query->where($db->quoteName('a.language') . ' = :language') + ->bind(':language', $language); + } - $tagId = $this->getState('filter.tag'); + $tagId = $this->getState('filter.tag'); - // Filter by a single tag. - if (is_numeric($tagId)) - { - $query->where($db->quoteName('tagmap.tag_id') . ' = :tagId') - ->bind(':tagId', $tagId, ParameterType::INTEGER) - ->join( - 'LEFT', $db->quoteName('#__contentitem_tag_map', 'tagmap') - . ' ON ' . $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id') - . ' AND ' . $db->quoteName('tagmap.type_alias') . ' = ' . $db->quote('com_weblinks.weblink') - ); - } + // Filter by a single tag. + if (is_numeric($tagId)) { + $query->where($db->quoteName('tagmap.tag_id') . ' = :tagId') + ->bind(':tagId', $tagId, ParameterType::INTEGER) + ->join( + 'LEFT', + $db->quoteName('#__contentitem_tag_map', 'tagmap') + . ' ON ' . $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id') + . ' AND ' . $db->quoteName('tagmap.type_alias') . ' = ' . $db->quote('com_weblinks.weblink') + ); + } - // Add the list ordering clause. - $orderCol = $this->state->get('list.ordering', 'a.title'); - $orderDirn = $this->state->get('list.direction', 'ASC'); + // Add the list ordering clause. + $orderCol = $this->state->get('list.ordering', 'a.title'); + $orderDirn = $this->state->get('list.direction', 'ASC'); - if ($orderCol == 'a.ordering' || $orderCol == 'category_title') - { - $orderCol = 'c.title ' . $orderDirn . ', a.ordering'; - } + if ($orderCol == 'a.ordering' || $orderCol == 'category_title') { + $orderCol = 'c.title ' . $orderDirn . ', a.ordering'; + } - $query->order($db->escape($orderCol . ' ' . $orderDirn)); + $query->order($db->escape($orderCol . ' ' . $orderDirn)); - return $query; - } + return $query; + } } diff --git a/src/administrator/components/com_weblinks/src/Service/HTML/AdministratorService.php b/src/administrator/components/com_weblinks/src/Service/HTML/AdministratorService.php index 98c560e..8d0944e 100644 --- a/src/administrator/components/com_weblinks/src/Service/HTML/AdministratorService.php +++ b/src/administrator/components/com_weblinks/src/Service/HTML/AdministratorService.php @@ -1,4 +1,5 @@ $associated) { + $associations[$tag] = (int) $associated->id; + } - // Get the associations - if ($associations = Associations::getAssociations('com_weblinks', '#__weblinks', 'com_weblinks.item', $weblinkid)) - { - foreach ($associations as $tag => $associated) - { - $associations[$tag] = (int) $associated->id; - } + // Get the associated contact items + $db = Factory::getDbo(); + $query = $db->getQuery(true) + ->select([ + $db->quoteName('c.id'), + $db->quoteName('c.title', 'title'), + $db->quoteName('l.sef', 'lang_sef'), + $db->quoteName('lang_code'), + $db->quoteName('cat.title', 'category_title'), + $db->quoteName('l.image'), + $db->quoteName('l.title', 'language_title'), + ]) + ->from($db->quoteName('#__weblinks', 'c')) + ->join('LEFT', $db->quoteName('#__categories', 'cat'), $db->quoteName('cat.id') . ' = ' . $db->quoteName('c.catid')) + ->join('LEFT', $db->quoteName('#__languages', 'l'), $db->quoteName('c.language') . ' = ' . $db->quoteName('l.lang_code')) + ->whereIn($db->quoteName('c.id'), array_values($associations)) + ->where($db->quoteName('c.id') . ' != :id') + ->bind(':id', $weblinkid, ParameterType::INTEGER); + $db->setQuery($query); + try { + $items = $db->loadObjectList('id'); + } catch (\RuntimeException $e) { + throw new \Exception($e->getMessage(), 500, $e); + } - // Get the associated contact items - $db = Factory::getDbo(); - $query = $db->getQuery(true) - ->select( - [ - $db->quoteName('c.id'), - $db->quoteName('c.title', 'title'), - $db->quoteName('l.sef', 'lang_sef'), - $db->quoteName('lang_code'), - $db->quoteName('cat.title', 'category_title'), - $db->quoteName('l.image'), - $db->quoteName('l.title', 'language_title'), - ] - ) - ->from($db->quoteName('#__weblinks', 'c')) - ->join('LEFT', $db->quoteName('#__categories', 'cat'), $db->quoteName('cat.id') . ' = ' . $db->quoteName('c.catid')) - ->join('LEFT', $db->quoteName('#__languages', 'l'), $db->quoteName('c.language') . ' = ' . $db->quoteName('l.lang_code')) - ->whereIn($db->quoteName('c.id'), array_values($associations)) - ->where($db->quoteName('c.id') . ' != :id') - ->bind(':id', $weblinkid, ParameterType::INTEGER); - $db->setQuery($query); + if ($items) { + $app = Factory::getApplication(); + $languages = LanguageHelper::getContentLanguages([0, 1]); + $content_languages = array_column($languages, 'lang_code'); + foreach ($items as &$item) { + if (in_array($item->lang_code, $content_languages)) { + $text = $item->lang_code; + $url = Route::_('index.php?option=com_weblinks&task=weblink.edit&id=' . (int) $item->id); + $tooltip = '' . htmlspecialchars($item->language_title, ENT_QUOTES, 'UTF-8') . '
' + . htmlspecialchars($item->title, ENT_QUOTES, 'UTF-8') + . '
' . Text::sprintf('JCATEGORY_SPRINTF', $item->category_title); + $classes = 'badge bg-secondary'; + $item->link = '' . $text . '' + . ''; + } else { + // Display warning if Content Language is trashed or deleted + $app->enqueueMessage(Text::sprintf('JGLOBAL_ASSOCIATIONS_CONTENTLANGUAGE_WARNING', $item->lang_code), 'warning'); + } + } + } - try - { - $items = $db->loadObjectList('id'); - } - catch (\RuntimeException $e) - { - throw new \Exception($e->getMessage(), 500, $e); - } + $html = LayoutHelper::render('joomla.content.associations', $items); + } - if ($items) - { - $app = Factory::getApplication(); - $languages = LanguageHelper::getContentLanguages(array(0, 1)); - $content_languages = array_column($languages, 'lang_code'); - - foreach ($items as &$item) - { - if (in_array($item->lang_code, $content_languages)) - { - $text = $item->lang_code; - $url = Route::_('index.php?option=com_weblinks&task=weblink.edit&id=' . (int) $item->id); - $tooltip = '' . htmlspecialchars($item->language_title, ENT_QUOTES, 'UTF-8') . '
' - . htmlspecialchars($item->title, ENT_QUOTES, 'UTF-8') - . '
' . Text::sprintf('JCATEGORY_SPRINTF', $item->category_title); - $classes = 'badge bg-secondary'; - - $item->link = '' . $text . '' - . ''; - } - else - { - // Display warning if Content Language is trashed or deleted - $app->enqueueMessage(Text::sprintf('JGLOBAL_ASSOCIATIONS_CONTENTLANGUAGE_WARNING', $item->lang_code), 'warning'); - } - } - } - - $html = LayoutHelper::render('joomla.content.associations', $items); - } - - return $html; - } + return $html; + } } diff --git a/src/administrator/components/com_weblinks/src/Service/HTML/Icon.php b/src/administrator/components/com_weblinks/src/Service/HTML/Icon.php index 35ece5b..a209017 100644 --- a/src/administrator/components/com_weblinks/src/Service/HTML/Icon.php +++ b/src/administrator/components/com_weblinks/src/Service/HTML/Icon.php @@ -1,4 +1,5 @@ application = $application; + } - /** - * Service constructor - * - * @param CMSApplication $application The application - * - * @since 4.0.0 - */ - public function __construct(CMSApplication $application) - { - $this->application = $application; - } + /** + * Method to generate a link to the create item page for the given category + * + * @param object $category The category information + * @param Registry $params The item parameters + * @param array $attribs Optional attributes for the link + * + * @return string The HTML markup for the create item link + * + * @since 4.0.0 + */ + public static function create($category, $params, $attribs = []) + { + $uri = Uri::getInstance(); + $url = 'index.php?option=com_weblinks&task=weblink.add&return=' . base64_encode($uri) . '&w_id=0&catid=' . $category->id; + $text = LayoutHelper::render('joomla.content.icons.create', ['params' => $params, 'legacy' => false]); + // Add the button classes to the attribs array + if (isset($attribs['class'])) { + $attribs['class'] .= ' btn btn-primary'; + } else { + $attribs['class'] = 'btn btn-primary'; + } - /** - * Method to generate a link to the create item page for the given category - * - * @param object $category The category information - * @param Registry $params The item parameters - * @param array $attribs Optional attributes for the link - * - * @return string The HTML markup for the create item link - * - * @since 4.0.0 - */ - public static function create($category, $params, $attribs = array()) - { - $uri = Uri::getInstance(); + $button = HTMLHelper::_('link', Route::_($url), $text, $attribs); + $output = '' . $button . ''; + return $output; + } - $url = 'index.php?option=com_weblinks&task=weblink.add&return=' . base64_encode($uri) . '&w_id=0&catid=' . $category->id; + /** + * Display an edit icon for the weblink. + * + * This icon will not display in a popup window, nor if the weblink is trashed. + * Edit access checks must be performed in the calling code. + * + * @param object $weblink The weblink information + * @param Registry $params The item parameters + * @param array $attribs Optional attributes for the link + * @param boolean $legacy True to use legacy images, false to use icomoon based graphic + * + * @return string The HTML for the weblink edit icon. + * + * @since 4.0.0 + */ + public static function edit($weblink, $params, $attribs = [], $legacy = false) + { + $user = Factory::getApplication()->getIdentity(); + $uri = Uri::getInstance(); + // Ignore if in a popup window. + if ($params && $params->get('popup')) { + return ''; + } - $text = LayoutHelper::render('joomla.content.icons.create', array('params' => $params, 'legacy' => false)); + // Ignore if the state is negative (trashed). + if ($weblink->state < 0) { + return ''; + } - // Add the button classes to the attribs array - if (isset($attribs['class'])) - { - $attribs['class'] .= ' btn btn-primary'; - } - else - { - $attribs['class'] = 'btn btn-primary'; - } + // Show checked_out icon if the contact is checked out by a different user + if ( + property_exists($weblink, 'checked_out') + && property_exists($weblink, 'checked_out_time') + && $weblink->checked_out + && $weblink->checked_out !== $user->get('id') + ) { + $checkoutUser = Factory::getUser($weblink->checked_out); + $date = HTMLHelper::_('date', $weblink->checked_out_time); + $tooltip = Text::sprintf('COM_WEBLINKS_CHECKED_OUT_BY', $checkoutUser->name) + . '
' . $date; + $text = LayoutHelper::render('joomla.content.icons.edit_lock', ['contact' => $weblink, 'tooltip' => $tooltip, 'legacy' => $legacy]); + $attribs['aria-describedby'] = 'editweblink-' . (int) $weblink->id; + $output = HTMLHelper::_('link', '#', $text, $attribs); + return $output; + } - $button = HTMLHelper::_('link', Route::_($url), $text, $attribs); + $weblinkUrl = RouteHelper::getWeblinkRoute($weblink->slug, $weblink->catid, $weblink->language); + $url = $weblinkUrl . '&task=weblink.edit&w_id=' . $weblink->id . '&return=' . base64_encode($uri); + if ((int) $weblink->state === 0) { + $tooltip = Text::_('COM_WEBLINKS_EDIT_UNPUBLISHED_WEBLINK'); + } else { + $tooltip = Text::_('COM_WEBLINKS_EDIT_PUBLISHED_WEBLINK'); + } - $output = '' . $button . ''; + $nowDate = strtotime(Factory::getDate()); + $icon = $weblink->state ? 'edit' : 'eye-slash'; - return $output; - } + if ( + ($weblink->publish_up !== null && strtotime($weblink->publish_up) > $nowDate) + || ($weblink->publish_down !== null && strtotime($weblink->publish_down) < $nowDate + && $weblink->publish_down !== Factory::getDbo()->getNullDate()) + ) { + $icon = 'eye-slash'; + } - /** - * Display an edit icon for the weblink. - * - * This icon will not display in a popup window, nor if the weblink is trashed. - * Edit access checks must be performed in the calling code. - * - * @param object $weblink The weblink information - * @param Registry $params The item parameters - * @param array $attribs Optional attributes for the link - * @param boolean $legacy True to use legacy images, false to use icomoon based graphic - * - * @return string The HTML for the weblink edit icon. - * - * @since 4.0.0 - */ - public static function edit($weblink, $params, $attribs = array(), $legacy = false) - { - $user = Factory::getApplication()->getIdentity(); - $uri = Uri::getInstance(); - - // Ignore if in a popup window. - if ($params && $params->get('popup')) - { - return ''; - } - - // Ignore if the state is negative (trashed). - if ($weblink->state < 0) - { - return ''; - } - - // Show checked_out icon if the contact is checked out by a different user - if (property_exists($weblink, 'checked_out') - && property_exists($weblink, 'checked_out_time') - && $weblink->checked_out - && $weblink->checked_out !== $user->get('id')) - { - $checkoutUser = Factory::getUser($weblink->checked_out); - $date = HTMLHelper::_('date', $weblink->checked_out_time); - $tooltip = Text::sprintf('COM_WEBLINKS_CHECKED_OUT_BY', $checkoutUser->name) - . '
' . $date; - - $text = LayoutHelper::render('joomla.content.icons.edit_lock', array('contact' => $weblink, 'tooltip' => $tooltip, 'legacy' => $legacy)); - - $attribs['aria-describedby'] = 'editweblink-' . (int) $weblink->id; - $output = HTMLHelper::_('link', '#', $text, $attribs); - - return $output; - } - - $weblinkUrl = RouteHelper::getWeblinkRoute($weblink->slug, $weblink->catid, $weblink->language); - $url = $weblinkUrl . '&task=weblink.edit&w_id=' . $weblink->id . '&return=' . base64_encode($uri); - - if ((int) $weblink->state === 0) - { - $tooltip = Text::_('COM_WEBLINKS_EDIT_UNPUBLISHED_WEBLINK'); - } - else - { - $tooltip = Text::_('COM_WEBLINKS_EDIT_PUBLISHED_WEBLINK'); - } - - $nowDate = strtotime(Factory::getDate()); - $icon = $weblink->state ? 'edit' : 'eye-slash'; - - if (($weblink->publish_up !== null && strtotime($weblink->publish_up) > $nowDate) - || ($weblink->publish_down !== null && strtotime($weblink->publish_down) < $nowDate - && $weblink->publish_down !== Factory::getDbo()->getNullDate())) - { - $icon = 'eye-slash'; - } - - $aria_described = 'editweblink-' . (int) $weblink->id; - - $text = ''; - $text .= Text::_('JGLOBAL_EDIT'); - $text .= ''; - - $attribs['aria-describedby'] = $aria_described; - $output = HTMLHelper::_('link', Route::_($url), $text, $attribs); - - return $output; - } + $aria_described = 'editweblink-' . (int) $weblink->id; + $text = ''; + $text .= Text::_('JGLOBAL_EDIT'); + $text .= ''; + $attribs['aria-describedby'] = $aria_described; + $output = HTMLHelper::_('link', Route::_($url), $text, $attribs); + return $output; + } } diff --git a/src/administrator/components/com_weblinks/src/Table/WeblinkTable.php b/src/administrator/components/com_weblinks/src/Table/WeblinkTable.php index b43612b..b23d59b 100644 --- a/src/administrator/components/com_weblinks/src/Table/WeblinkTable.php +++ b/src/administrator/components/com_weblinks/src/Table/WeblinkTable.php @@ -1,4 +1,5 @@ typeAlias = 'com_weblinks.weblink'; + protected $_supportNullValue = true; + /** + * Ensure the params and metadata in json encoded in the bind method + * + * @var array + * @since 3.4 + */ + protected $_jsonEncode = ['params', 'metadata', 'images']; + /** + * Constructor + * + * @param \JDatabaseDriver &$db A database connector object + * + * @since 1.5 + */ + public function __construct($db) + { + $this->typeAlias = 'com_weblinks.weblink'; + parent::__construct('#__weblinks', 'id', $db); + // Set the published column alias + $this->setColumnAlias('published', 'state'); + } - parent::__construct('#__weblinks', 'id', $db); + /** + * Overload the store method for the Weblinks table. + * + * @param boolean $updateNulls Toggle whether null values should be updated. + * + * @return boolean True on success, false on failure. + * + * @since 1.6 + */ + public function store($updateNulls = true) + { + $date = Factory::getDate()->toSql(); + $user = Factory::getApplication()->getIdentity(); + $this->modified = $date; + if ($this->id) { + // Existing item + $this->modified_by = $user->id; + $this->modified = $date; + } else { + // New weblink. A weblink created and created_by field can be set by the user, + // so we don't touch either of these if they are set. + if (!(int) $this->created) { + $this->created = $date; + } - // Set the published column alias - $this->setColumnAlias('published', 'state'); - } + if (empty($this->created_by)) { + $this->created_by = $user->id; + } - /** - * Overload the store method for the Weblinks table. - * - * @param boolean $updateNulls Toggle whether null values should be updated. - * - * @return boolean True on success, false on failure. - * - * @since 1.6 - */ - public function store($updateNulls = true) - { - $date = Factory::getDate()->toSql(); - $user = Factory::getApplication()->getIdentity(); + if (!(int) $this->modified) { + $this->modified = $date; + } - $this->modified = $date; + if (empty($this->modified_by)) { + $this->modified_by = $user->id; + } - if ($this->id) - { - // Existing item - $this->modified_by = $user->id; - $this->modified = $date; - } - else - { - // New weblink. A weblink created and created_by field can be set by the user, - // so we don't touch either of these if they are set. - if (!(int) $this->created) - { - $this->created = $date; - } + if (empty($this->hits)) { + $this->hits = 0; + } + } - if (empty($this->created_by)) - { - $this->created_by = $user->id; - } + // Set publish_up to null if not set + if (!$this->publish_up) { + $this->publish_up = null; + } - if (!(int) $this->modified) - { - $this->modified = $date; - } + // Set publish_down to null if not set + if (!$this->publish_down) { + $this->publish_down = null; + } - if (empty($this->modified_by)) - { - $this->modified_by = $user->id; - } + // Verify that the alias is unique + $table = new WeblinkTable($this->getDbo()); - if (empty($this->hits)) - { - $this->hits = 0; - } - } + if ( + $table->load(['language' => $this->language, 'alias' => $this->alias, 'catid' => (int) $this->catid]) + && ($table->id != $this->id || $this->id == 0) + ) { + $this->setError(Text::_('COM_WEBLINKS_ERROR_UNIQUE_ALIAS')); + return false; + } - // Set publish_up to null if not set - if (!$this->publish_up) - { - $this->publish_up = null; - } + // Convert IDN urls to punycode + $this->url = PunycodeHelper::urlToPunycode($this->url); + return parent::store($updateNulls); + } - // Set publish_down to null if not set - if (!$this->publish_down) - { - $this->publish_down = null; - } + /** + * Overloaded check method to ensure data integrity. + * + * @return boolean True on success. + * + * @since 1.5 + */ + public function check() + { + if (InputFilter::checkAttribute(['href', $this->url])) { + $this->setError(Text::_('COM_WEBLINKS_ERR_TABLES_PROVIDE_URL')); + return false; + } - // Verify that the alias is unique - $table = new WeblinkTable($this->getDbo()); + // Check for valid name + if (trim($this->title) == '') { + $this->setError(Text::_('COM_WEBLINKS_ERR_TABLES_TITLE')); + return false; + } - if ($table->load(array('language' => $this->language, 'alias' => $this->alias, 'catid' => (int) $this->catid)) - && ($table->id != $this->id || $this->id == 0)) - { - $this->setError(Text::_('COM_WEBLINKS_ERROR_UNIQUE_ALIAS')); + // Check for existing name + $db = $this->getDbo(); + $query = $db->getQuery(true) + ->select($db->quoteName('id')) + ->from($db->quoteName('#__weblinks')) + ->where($db->quoteName('title') . ' = :title') + ->where($db->quoteName('language') . ' = :language') + ->where($db->quoteName('catid') . ' = :catid') + ->bind(':title', $this->title) + ->bind(':language', $this->language) + ->bind(':catid', $this->catid, ParameterType::INTEGER); + $db->setQuery($query); + $xid = (int) $db->loadResult(); + if ($xid && $xid != (int) $this->id) { + $this->setError(Text::_('COM_WEBLINKS_ERR_TABLES_NAME')); + return false; + } - return false; - } + if (empty($this->alias)) { + $this->alias = $this->title; + } - // Convert IDN urls to punycode - $this->url = PunycodeHelper::urlToPunycode($this->url); + $this->alias = ApplicationHelper::stringURLSafe($this->alias, $this->language); + if (trim(str_replace('-', '', $this->alias)) == '') { + $this->alias = Factory::getDate()->format("Y-m-d-H-i-s"); + } - return parent::store($updateNulls); - } + // Check the publish down date is not earlier than publish up. + if ((int) $this->publish_down > 0 && $this->publish_down < $this->publish_up) { + $this->setError(Text::_('JGLOBAL_START_PUBLISH_AFTER_FINISH')); + return false; + } - /** - * Overloaded check method to ensure data integrity. - * - * @return boolean True on success. - * - * @since 1.5 - */ - public function check() - { - if (InputFilter::checkAttribute(array('href', $this->url))) - { - $this->setError(Text::_('COM_WEBLINKS_ERR_TABLES_PROVIDE_URL')); + /* + * Clean up keywords -- eliminate extra spaces between phrases + * and cr (\r) and lf (\n) characters from string + */ + if (!empty($this->metakey)) { + // Array of characters to remove + $bad_characters = ["\n", "\r", "\"", "<", ">"]; + $after_clean = StringHelper::str_ireplace($bad_characters, "", $this->metakey); + $keys = explode(',', $after_clean); + $clean_keys = []; + foreach ($keys as $key) { + // Ignore blank keywords + if (trim($key)) { + $clean_keys[] = trim($key); + } + } - return false; - } + // Put array back together delimited by ", " + $this->metakey = implode(", ", $clean_keys); + } - // Check for valid name - if (trim($this->title) == '') - { - $this->setError(Text::_('COM_WEBLINKS_ERR_TABLES_TITLE')); + /** + * Ensure any new items have compulsory fields set. This is needed for things like + * frontend editing where we don't show all the fields or using some kind of API + */ + if (!$this->id) { + if (!isset($this->xreference)) { + $this->xreference = ''; + } - return false; - } + if (!isset($this->metakey)) { + $this->metakey = ''; + } - // Check for existing name - $db = $this->getDbo(); + if (!isset($this->metadesc)) { + $this->metadesc = ''; + } - $query = $db->getQuery(true) - ->select($db->quoteName('id')) - ->from($db->quoteName('#__weblinks')) - ->where($db->quoteName('title') . ' = :title') - ->where($db->quoteName('language') . ' = :language') - ->where($db->quoteName('catid') . ' = :catid') - ->bind(':title', $this->title) - ->bind(':language', $this->language) - ->bind(':catid', $this->catid, ParameterType::INTEGER); - $db->setQuery($query); + if (!isset($this->images)) { + $this->images = '{}'; + } - $xid = (int) $db->loadResult(); + if (!isset($this->metadata)) { + $this->metadata = '{}'; + } - if ($xid && $xid != (int) $this->id) - { - $this->setError(Text::_('COM_WEBLINKS_ERR_TABLES_NAME')); + if (!isset($this->params)) { + $this->params = '{}'; + } + } - return false; - } + return parent::check(); + } - if (empty($this->alias)) - { - $this->alias = $this->title; - } - - $this->alias = ApplicationHelper::stringURLSafe($this->alias, $this->language); - - if (trim(str_replace('-', '', $this->alias)) == '') - { - $this->alias = Factory::getDate()->format("Y-m-d-H-i-s"); - } - - // Check the publish down date is not earlier than publish up. - if ((int) $this->publish_down > 0 && $this->publish_down < $this->publish_up) - { - $this->setError(Text::_('JGLOBAL_START_PUBLISH_AFTER_FINISH')); - - return false; - } - - /* - * Clean up keywords -- eliminate extra spaces between phrases - * and cr (\r) and lf (\n) characters from string - */ - if (!empty($this->metakey)) - { - // Array of characters to remove - $bad_characters = array("\n", "\r", "\"", "<", ">"); - $after_clean = StringHelper::str_ireplace($bad_characters, "", $this->metakey); - $keys = explode(',', $after_clean); - $clean_keys = array(); - - foreach ($keys as $key) - { - // Ignore blank keywords - if (trim($key)) - { - $clean_keys[] = trim($key); - } - } - - // Put array back together delimited by ", " - $this->metakey = implode(", ", $clean_keys); - } - - /** - * Ensure any new items have compulsory fields set. This is needed for things like - * frontend editing where we don't show all the fields or using some kind of API - */ - if (!$this->id) - { - if (!isset($this->xreference)) - { - $this->xreference = ''; - } - - if (!isset($this->metakey)) - { - $this->metakey = ''; - } - - if (!isset($this->metadesc)) - { - $this->metadesc = ''; - } - - if (!isset($this->images)) - { - $this->images = '{}'; - } - - if (!isset($this->metadata)) - { - $this->metadata = '{}'; - } - - if (!isset($this->params)) - { - $this->params = '{}'; - } - } - - return parent::check(); - } - - /** - * Get the type alias for the history table - * - * @return string The alias as described above - * - * @since 4.0.0 - */ - public function getTypeAlias() - { - return $this->typeAlias; - } + /** + * Get the type alias for the history table + * + * @return string The alias as described above + * + * @since 4.0.0 + */ + public function getTypeAlias() + { + return $this->typeAlias; + } } diff --git a/src/administrator/components/com_weblinks/src/View/Weblink/HtmlView.php b/src/administrator/components/com_weblinks/src/View/Weblink/HtmlView.php index 0eb467c..ce3826c 100644 --- a/src/administrator/components/com_weblinks/src/View/Weblink/HtmlView.php +++ b/src/administrator/components/com_weblinks/src/View/Weblink/HtmlView.php @@ -1,4 +1,5 @@ state = $this->get('State'); - $this->item = $this->get('Item'); - $this->form = $this->get('Form'); + /** + * Display the view. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise an Error object. + */ + public function display($tpl = null) + { + $this->state = $this->get('State'); + $this->item = $this->get('Item'); + $this->form = $this->get('Form'); - // Check for errors. - if (count($errors = $this->get('Errors'))) - { - throw new GenericDataException(implode("\n", $errors), 500); - } + // Check for errors. + if (count($errors = $this->get('Errors'))) { + throw new GenericDataException(implode("\n", $errors), 500); + } - // If we are forcing a language in modal (used for associations). - if ($this->getLayout() === 'modal' && $forcedLanguage = Factory::getApplication()->input->get('forcedLanguage', '', 'cmd')) - { - // Set the language field to the forcedLanguage and disable changing it. - $this->form->setValue('language', null, $forcedLanguage); - $this->form->setFieldAttribute('language', 'readonly', 'true'); + // If we are forcing a language in modal (used for associations). + if ($this->getLayout() === 'modal' && $forcedLanguage = Factory::getApplication()->input->get('forcedLanguage', '', 'cmd')) { + // Set the language field to the forcedLanguage and disable changing it. + $this->form->setValue('language', null, $forcedLanguage); + $this->form->setFieldAttribute('language', 'readonly', 'true'); - // Only allow to select categories with All language or with the forced language. - $this->form->setFieldAttribute('catid', 'language', '*,' . $forcedLanguage); + // Only allow to select categories with All language or with the forced language. + $this->form->setFieldAttribute('catid', 'language', '*,' . $forcedLanguage); - // Only allow to select tags with All language or with the forced language. - $this->form->setFieldAttribute('tags', 'language', '*,' . $forcedLanguage); - } + // Only allow to select tags with All language or with the forced language. + $this->form->setFieldAttribute('tags', 'language', '*,' . $forcedLanguage); + } - $this->addToolbar(); + $this->addToolbar(); - parent::display($tpl); - } + parent::display($tpl); + } - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - */ - protected function addToolbar() - { - $app = Factory::getApplication(); - $app->input->set('hidemainmenu', true); + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 1.6 + */ + protected function addToolbar() + { + $app = Factory::getApplication(); + $app->input->set('hidemainmenu', true); - $user = $this->getCurrentUser(); - $isNew = ($this->item->id == 0); - $checkedOut = $this->item->checked_out && $this->item->checked_out !== $user->get('id'); + $user = $this->getCurrentUser(); + $isNew = ($this->item->id == 0); + $checkedOut = $this->item->checked_out && $this->item->checked_out !== $user->get('id'); - // Since we don't track these assets at the item level, use the category id. - $canDo = ContentHelper::getActions('com_weblinks', 'category', $this->item->catid); + // Since we don't track these assets at the item level, use the category id. + $canDo = ContentHelper::getActions('com_weblinks', 'category', $this->item->catid); - ToolbarHelper::title($isNew ? Text::_('COM_WEBLINKS_MANAGER_WEBLINK_NEW') : Text::_('COM_WEBLINKS_MANAGER_WEBLINK_EDIT'), 'link weblinks'); + ToolbarHelper::title($isNew ? Text::_('COM_WEBLINKS_MANAGER_WEBLINK_NEW') : Text::_('COM_WEBLINKS_MANAGER_WEBLINK_EDIT'), 'link weblinks'); - // Build the actions for new and existing records. - if ($isNew) - { - // For new records, check the create permission. - if (count($user->getAuthorisedCategories('com_weblinks', 'core.create')) > 0) - { - ToolbarHelper::apply('weblink.apply'); + // Build the actions for new and existing records. + if ($isNew) { + // For new records, check the create permission. + if (count($user->getAuthorisedCategories('com_weblinks', 'core.create')) > 0) { + ToolbarHelper::apply('weblink.apply'); - ToolbarHelper::saveGroup( - [ - ['save', 'weblink.save'], - ['save2new', 'weblink.save2new'] - ], - 'btn-success' - ); - } + ToolbarHelper::saveGroup( + [ + ['save', 'weblink.save'], + ['save2new', 'weblink.save2new'], + ], + 'btn-success' + ); + } - ToolbarHelper::cancel('weblink.cancel'); - } - else - { - // Since it's an existing record, check the edit permission, or fall back to edit own if the owner. - $itemEditable = $canDo->get('core.edit') || ($canDo->get('core.edit.own') && $this->item->created_by == $user->id); + ToolbarHelper::cancel('weblink.cancel'); + } else { + // Since it's an existing record, check the edit permission, or fall back to edit own if the owner. + $itemEditable = $canDo->get('core.edit') || ($canDo->get('core.edit.own') && $this->item->created_by == $user->id); - $toolbarButtons = []; + $toolbarButtons = []; - // Can't save the record if it's checked out and editable - if (!$checkedOut && $itemEditable) - { - ToolbarHelper::apply('weblink.apply'); + // Can't save the record if it's checked out and editable + if (!$checkedOut && $itemEditable) { + ToolbarHelper::apply('weblink.apply'); - $toolbarButtons[] = ['save', 'weblink.save']; + $toolbarButtons[] = ['save', 'weblink.save']; - // We can save this record, but check the create permission to see if we can return to make a new one. - if ($canDo->get('core.create')) - { - $toolbarButtons[] = ['save2new', 'weblink.save2new']; - } - } + // We can save this record, but check the create permission to see if we can return to make a new one. + if ($canDo->get('core.create')) { + $toolbarButtons[] = ['save2new', 'weblink.save2new']; + } + } - // If checked out, we can still save - if ($canDo->get('core.create')) - { - $toolbarButtons[] = ['save2copy', 'weblink.save2copy']; - } + // If checked out, we can still save + if ($canDo->get('core.create')) { + $toolbarButtons[] = ['save2copy', 'weblink.save2copy']; + } - ToolbarHelper::saveGroup( - $toolbarButtons, - 'btn-success' - ); + ToolbarHelper::saveGroup( + $toolbarButtons, + 'btn-success' + ); - ToolbarHelper::cancel('weblink.cancel', 'JTOOLBAR_CLOSE'); + ToolbarHelper::cancel('weblink.cancel', 'JTOOLBAR_CLOSE'); - if (ComponentHelper::isEnabled('com_contenthistory') && $this->state->params->get('save_history', 0) && $itemEditable) - { - ToolbarHelper::versions('com_weblinks.weblink', $this->item->id); - } + if (ComponentHelper::isEnabled('com_contenthistory') && $this->state->params->get('save_history', 0) && $itemEditable) { + ToolbarHelper::versions('com_weblinks.weblink', $this->item->id); + } - if (Associations::isEnabled() && ComponentHelper::isEnabled('com_associations')) - { - ToolbarHelper::custom('weblink.editAssociations', 'contract', '', 'JTOOLBAR_ASSOCIATIONS', false, false); - } - } + if (Associations::isEnabled() && ComponentHelper::isEnabled('com_associations')) { + ToolbarHelper::custom('weblink.editAssociations', 'contract', '', 'JTOOLBAR_ASSOCIATIONS', false, false); + } + } - ToolbarHelper::help('Components_Weblinks_Links_Edit'); - } + ToolbarHelper::help('Components_Weblinks_Links_Edit'); + } } diff --git a/src/administrator/components/com_weblinks/src/View/Weblinks/HtmlView.php b/src/administrator/components/com_weblinks/src/View/Weblinks/HtmlView.php index ce87434..9d2d036 100644 --- a/src/administrator/components/com_weblinks/src/View/Weblinks/HtmlView.php +++ b/src/administrator/components/com_weblinks/src/View/Weblinks/HtmlView.php @@ -1,4 +1,5 @@ state = $this->get('State'); - $this->items = $this->get('Items'); - $this->pagination = $this->get('Pagination'); - $this->filterForm = $this->get('FilterForm'); - $this->activeFilters = $this->get('ActiveFilters'); + /** + * Display the view. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise an Error object. + */ + public function display($tpl = null) + { + $this->state = $this->get('State'); + $this->items = $this->get('Items'); + $this->pagination = $this->get('Pagination'); + $this->filterForm = $this->get('FilterForm'); + $this->activeFilters = $this->get('ActiveFilters'); - // Check for errors. - if (count($errors = $this->get('Errors'))) - { - throw new GenericDataException(implode("\n", $errors), 500); - } + // Check for errors. + if (count($errors = $this->get('Errors'))) { + throw new GenericDataException(implode("\n", $errors), 500); + } - if (!\count($this->items) && $this->isEmptyState = $this->get('IsEmptyState')) - { - $this->setLayout('emptystate'); - } + if (!\count($this->items) && $this->isEmptyState = $this->get('IsEmptyState')) { + $this->setLayout('emptystate'); + } - // We don't need toolbar in the modal layout. - if ($this->getLayout() !== 'modal') - { - $this->addToolbar(); - } - else - { - // In article associations modal we need to remove language filter if forcing a language. - // We also need to change the category filter to show show categories with All or the forced language. - if ($forcedLanguage = Factory::getApplication()->input->get('forcedLanguage', '', 'CMD')) - { - // If the language is forced we can't allow to select the language, so transform the language selector filter into an hidden field. - $languageXml = new \SimpleXMLElement(''); - $this->filterForm->setField($languageXml, 'filter', true); + // We don't need toolbar in the modal layout. + if ($this->getLayout() !== 'modal') { + $this->addToolbar(); + } else { + // In article associations modal we need to remove language filter if forcing a language. + // We also need to change the category filter to show show categories with All or the forced language. + if ($forcedLanguage = Factory::getApplication()->input->get('forcedLanguage', '', 'CMD')) { + // If the language is forced we can't allow to select the language, so transform the language selector filter into an hidden field. + $languageXml = new \SimpleXMLElement(''); + $this->filterForm->setField($languageXml, 'filter', true); - // Also, unset the active language filter so the search tools is not open by default with this filter. - unset($this->activeFilters['language']); + // Also, unset the active language filter so the search tools is not open by default with this filter. + unset($this->activeFilters['language']); - // One last changes needed is to change the category filter to just show categories with All language or with the forced language. - $this->filterForm->setFieldAttribute('category_id', 'language', '*,' . $forcedLanguage, 'filter'); - } - } + // One last changes needed is to change the category filter to just show categories with All language or with the forced language. + $this->filterForm->setFieldAttribute('category_id', 'language', '*,' . $forcedLanguage, 'filter'); + } + } - parent::display($tpl); - } + parent::display($tpl); + } - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - */ - protected function addToolbar() - { - $canDo = ContentHelper::getActions('com_weblinks', 'category', $this->state->get('filter.category_id')); - $user = $this->getCurrentUser(); + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 1.6 + */ + protected function addToolbar() + { + $canDo = ContentHelper::getActions('com_weblinks', 'category', $this->state->get('filter.category_id')); + $user = $this->getCurrentUser(); - // Get the toolbar object instance - $toolbar = Toolbar::getInstance('toolbar'); + // Get the toolbar object instance + $toolbar = Toolbar::getInstance('toolbar'); - ToolbarHelper::title(Text::_('COM_WEBLINKS_MANAGER_WEBLINKS'), 'link weblinks'); + ToolbarHelper::title(Text::_('COM_WEBLINKS_MANAGER_WEBLINKS'), 'link weblinks'); - if ($canDo->get('core.create') || \count($user->getAuthorisedCategories('com_weblinks', 'core.create')) > 0) - { - ToolbarHelper::addNew('weblink.add'); - } + if ($canDo->get('core.create') || \count($user->getAuthorisedCategories('com_weblinks', 'core.create')) > 0) { + ToolbarHelper::addNew('weblink.add'); + } - if (!$this->isEmptyState && $canDo->get('core.edit.state')) - { - $dropdown = $toolbar->dropdownButton('status-group') - ->text('JTOOLBAR_CHANGE_STATUS') - ->toggleSplit(false) - ->icon('icon-ellipsis-h') - ->buttonClass('btn btn-action') - ->listCheck(true); + if (!$this->isEmptyState && $canDo->get('core.edit.state')) { + $dropdown = $toolbar->dropdownButton('status-group') + ->text('JTOOLBAR_CHANGE_STATUS') + ->toggleSplit(false) + ->icon('icon-ellipsis-h') + ->buttonClass('btn btn-action') + ->listCheck(true); - $childBar = $dropdown->getChildToolbar(); + $childBar = $dropdown->getChildToolbar(); - $childBar->publish('weblinks.publish')->listCheck(true); + $childBar->publish('weblinks.publish')->listCheck(true); - $childBar->unpublish('weblinks.unpublish')->listCheck(true); + $childBar->unpublish('weblinks.unpublish')->listCheck(true); - $childBar->archive('weblinks.archive')->listCheck(true); + $childBar->archive('weblinks.archive')->listCheck(true); - if ($user->authorise('core.admin')) - { - $childBar->checkin('weblinks.checkin')->listCheck(true); - } + if ($user->authorise('core.admin')) { + $childBar->checkin('weblinks.checkin')->listCheck(true); + } - if ($this->state->get('filter.published') != -2) - { - $childBar->trash('weblinks.trash')->listCheck(true); - } + if ($this->state->get('filter.published') != -2) { + $childBar->trash('weblinks.trash')->listCheck(true); + } - // Add a batch button - if ($user->authorise('core.create', 'com_weblinks') - && $user->authorise('core.edit', 'com_weblinks') - && $user->authorise('core.edit.state', 'com_weblinks')) - { - $childBar->popupButton('batch') - ->text('JTOOLBAR_BATCH') - ->selector('collapseModal') - ->listCheck(true); - } - } + // Add a batch button + if ( + $user->authorise('core.create', 'com_weblinks') + && $user->authorise('core.edit', 'com_weblinks') + && $user->authorise('core.edit.state', 'com_weblinks') + ) { + $childBar->popupButton('batch') + ->text('JTOOLBAR_BATCH') + ->selector('collapseModal') + ->listCheck(true); + } + } - if (!$this->isEmptyState && $this->state->get('filter.published') == -2 && $canDo->get('core.delete')) - { - $toolbar->delete('weblinks.delete') - ->text('JTOOLBAR_EMPTY_TRASH') - ->message('JGLOBAL_CONFIRM_DELETE') - ->listCheck(true); - } + if (!$this->isEmptyState && $this->state->get('filter.published') == -2 && $canDo->get('core.delete')) { + $toolbar->delete('weblinks.delete') + ->text('JTOOLBAR_EMPTY_TRASH') + ->message('JGLOBAL_CONFIRM_DELETE') + ->listCheck(true); + } - if ($user->authorise('core.admin', 'com_weblinks') || $user->authorise('core.options', 'com_weblinks')) - { - ToolbarHelper::preferences('com_weblinks'); - } + if ($user->authorise('core.admin', 'com_weblinks') || $user->authorise('core.options', 'com_weblinks')) { + ToolbarHelper::preferences('com_weblinks'); + } - ToolbarHelper::help('Components_Weblinks_Links'); - } + ToolbarHelper::help('Components_Weblinks_Links'); + } } diff --git a/src/administrator/components/com_weblinks/tmpl/weblink/edit.php b/src/administrator/components/com_weblinks/tmpl/weblink/edit.php index fff3838..4d1b292 100644 --- a/src/administrator/components/com_weblinks/tmpl/weblink/edit.php +++ b/src/administrator/components/com_weblinks/tmpl/weblink/edit.php @@ -1,4 +1,5 @@ input; - $assoc = Associations::isEnabled(); - // Fieldsets to not automatically render by /layouts/joomla/edit/params.php $this->ignore_fieldsets = array('details', 'images', 'item_associations', 'jmetadata'); $this->useCoreUI = true; - // In case of modal $isModal = $input->get('layout') == 'modal' ? true : false; $layout = $isModal ? 'modal' : 'edit'; @@ -35,81 +32,87 @@ $tmpl = $isModal || $input->get('tmpl', '', 'cmd') === 'component' ? '&tmpl=c - + -
- 'details')); ?> +
+ 'details')); ?> - item->id) ? Text::_('COM_WEBLINKS_NEW_WEBLINK', true) : Text::_('COM_WEBLINKS_EDIT_WEBLINK', true)); ?> -
-
-
-
-
- form->renderField('url'); ?> - form->renderField('description'); ?> -
-
-
-
-
- -
-
- + item->id) ? Text::_('COM_WEBLINKS_NEW_WEBLINK', true) : Text::_('COM_WEBLINKS_EDIT_WEBLINK', true)); ?> +
+
+
+
+
+ form->renderField('url'); ?> + form->renderField('description'); ?> +
+
+
+
+
+ +
+
+ - -
-
-
- -
- form->renderField('imaJGLOBAL_FIELDSET_IMAGE_OPTIONSges'); ?> - form->getGroup('images') as $field) : ?> - renderField(); ?> - -
-
-
-
+ +
+
+
+ +
+ form->renderField('imaJGLOBAL_FIELDSET_IMAGE_OPTIONSges'); ?> + form->getGroup('images') as $field) : + ?> + renderField(); ?> + +
+
+
+
- + - -
-
-
- - -
-
-
-
- - -
-
-
- + +
+
+
+ + +
+
+
+
+ + +
+
+
+ - + - - -
- - -
- - - - + + +
+ + +
+ + + + - + -
+
- - - + + + diff --git a/src/administrator/components/com_weblinks/tmpl/weblink/edit_associations.php b/src/administrator/components/com_weblinks/tmpl/weblink/edit_associations.php index 731f5d3..4c9be9f 100644 --- a/src/administrator/components/com_weblinks/tmpl/weblink/edit_associations.php +++ b/src/administrator/components/com_weblinks/tmpl/weblink/edit_associations.php @@ -1,4 +1,5 @@ form->getFieldsets('params'); ?> - $fieldSet) : ?> -
- description) && trim($fieldSet->description)) : ?> - ' . $this->escape(Text::_($fieldSet->description)) . '

'; ?> - - form->getFieldset($name) as $field) : ?> -
-
label; ?>
-
input; ?>
-
- -
- + $fieldSet) : + ?> +
+ description) && trim($fieldSet->description)) : + ?> + ' . $this->escape(Text::_($fieldSet->description)) . '

'; ?> + + form->getFieldset($name) as $field) : + ?> +
+
label; ?>
+
input; ?>
+
+ +
+ diff --git a/src/administrator/components/com_weblinks/tmpl/weblink/modal.php b/src/administrator/components/com_weblinks/tmpl/weblink/modal.php index 0dbf7be..dbb905f 100644 --- a/src/administrator/components/com_weblinks/tmpl/weblink/modal.php +++ b/src/administrator/components/com_weblinks/tmpl/weblink/modal.php @@ -1,4 +1,5 @@ 'bottom')); - // @deprecated 4.0 the function parameter, the inline js and the buttons are not needed since 3.7.0. $function = Factory::getApplication()->input->getCmd('function', 'jEditWeblink_' . (int) $this->item->id); - // Function to update input title when changed Factory::getDocument()->addScriptDeclaration(' function jEditWeblinkModal() { @@ -30,6 +30,6 @@ Factory::getDocument()->addScriptDeclaration('
- setLayout('edit'); ?> - loadTemplate(); ?> + setLayout('edit'); ?> + loadTemplate(); ?>
diff --git a/src/administrator/components/com_weblinks/tmpl/weblink/modal_associations.php b/src/administrator/components/com_weblinks/tmpl/weblink/modal_associations.php index 731f5d3..4c9be9f 100644 --- a/src/administrator/components/com_weblinks/tmpl/weblink/modal_associations.php +++ b/src/administrator/components/com_weblinks/tmpl/weblink/modal_associations.php @@ -1,4 +1,5 @@ form->getFieldsets('params'); ?> - $fieldSet) : ?> -
- description) && trim($fieldSet->description)) : ?> - ' . $this->escape(Text::_($fieldSet->description)) . '

'; ?> - - form->getFieldset($name) as $field) : ?> -
-
label; ?>
-
input; ?>
-
- -
- + $fieldSet) : + ?> +
+ description) && trim($fieldSet->description)) : + ?> + ' . $this->escape(Text::_($fieldSet->description)) . '

'; ?> + + form->getFieldset($name) as $field) : + ?> +
+
label; ?>
+
input; ?>
+
+ +
+ diff --git a/src/administrator/components/com_weblinks/tmpl/weblinks/default.php b/src/administrator/components/com_weblinks/tmpl/weblinks/default.php index f0a9e62..b423595 100644 --- a/src/administrator/components/com_weblinks/tmpl/weblinks/default.php +++ b/src/administrator/components/com_weblinks/tmpl/weblinks/default.php @@ -1,4 +1,5 @@ getIdentity(); $userId = $user->get('id'); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $saveOrder = $listOrder == 'a.ordering'; $assoc = Associations::isEnabled(); - -if ($saveOrder && !empty($this->items)) -{ - $saveOrderingUrl = 'index.php?option=com_weblinks&task=weblinks.saveOrderAjax&tmpl=component'; - HTMLHelper::_('draggablelist.draggable'); +if ($saveOrder && !empty($this->items)) { + $saveOrderingUrl = 'index.php?option=com_weblinks&task=weblinks.saveOrderAjax&tmpl=component'; + HTMLHelper::_('draggablelist.draggable'); } ?>
-
-
-
- $this]); - ?> - items)) : ?> -
- - -
- - - - - - - - - - - - - - - - - - - - - class="js-draggable" data-url="" data-direction="" data-nested="true"> - items as $i => $item) : ?> - cat_link = Route::_('index.php?option=com_categories&extension=com_weblinks&task=edit&type=other&cid[]=' . $item->catid); ?> - authorise('core.create', 'com_weblinks.category.' . $item->catid); ?> - authorise('core.edit', 'com_weblinks.category.' . $item->catid); ?> - authorise('core.manage', 'com_checkin') || $item->checked_out == $user->id || !$item->checked_out; ?> - authorise('core.edit.own', 'com_weblinks.category.' . $item->catid) && $item->created_by == $user->id; ?> - authorise('core.edit.state', 'com_weblinks.category.' . $item->catid) && $canCheckin; ?> - - - - - - - - - - - - - - - - - - +
+
+
+ $this]); + ?> + items)) : + ?> +
+ + +
+ + + + + + + + + + + + + + + + + + + + + class="js-draggable" data-url="" data-direction="" data-nested="true"> + items as $i => $item) : + ?> + cat_link = Route::_('index.php?option=com_categories&extension=com_weblinks&task=edit&type=other&cid[]=' . $item->catid); ?> + authorise('core.create', 'com_weblinks.category.' . $item->catid); ?> + authorise('core.edit', 'com_weblinks.category.' . $item->catid); ?> + authorise('core.manage', 'com_checkin') || $item->checked_out == $user->id || !$item->checked_out; ?> + authorise('core.edit.own', 'com_weblinks.category.' . $item->catid) && $item->created_by == $user->id; ?> + authorise('core.edit.state', 'com_weblinks.category.' . $item->catid) && $canCheckin; ?> + + + + + + + + + + + + + + + + + + - - pagination->getListFooter(); ?> + + pagination->getListFooter(); ?> - - authorise('core.create', 'com_weblinks') - && $user->authorise('core.edit', 'com_weblinks') - && $user->authorise('core.edit.state', 'com_weblinks')) : ?> - Text::_('COM_WEBLINKS_BATCH_OPTIONS'), - 'footer' => $this->loadTemplate('batch_footer') - ], - $this->loadTemplate('batch_body') - ); ?> - - + + authorise('core.create', 'com_weblinks') + && $user->authorise('core.edit', 'com_weblinks') + && $user->authorise('core.edit.state', 'com_weblinks') +) : + ?> + Text::_('COM_WEBLINKS_BATCH_OPTIONS'), + 'footer' => $this->loadTemplate('batch_footer') + ], $this->loadTemplate('batch_body')); ?> + + - - - -
-
-
+ + + +
+
+
diff --git a/src/administrator/components/com_weblinks/tmpl/weblinks/default_batch_body.php b/src/administrator/components/com_weblinks/tmpl/weblinks/default_batch_body.php index 6b5dab6..e0f8e31 100644 --- a/src/administrator/components/com_weblinks/tmpl/weblinks/default_batch_body.php +++ b/src/administrator/components/com_weblinks/tmpl/weblinks/default_batch_body.php @@ -1,4 +1,5 @@ state->get('filter.published'); ?>
-
- -
-
- -
-
- -
-
- -
-
-
-
- = 0) : ?> -
-
- 'com_weblinks']); ?> -
-
- -
-
- -
-
-
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+
+ = 0) : + ?> +
+
+ 'com_weblinks']); ?> +
+
+ +
+
+ +
+
+
diff --git a/src/administrator/components/com_weblinks/tmpl/weblinks/default_batch_footer.php b/src/administrator/components/com_weblinks/tmpl/weblinks/default_batch_footer.php index 05744dc..51fcc78 100644 --- a/src/administrator/components/com_weblinks/tmpl/weblinks/default_batch_footer.php +++ b/src/administrator/components/com_weblinks/tmpl/weblinks/default_batch_footer.php @@ -1,4 +1,5 @@ diff --git a/src/administrator/components/com_weblinks/tmpl/weblinks/emptystate.php b/src/administrator/components/com_weblinks/tmpl/weblinks/emptystate.php index 8091dd2..5820930 100644 --- a/src/administrator/components/com_weblinks/tmpl/weblinks/emptystate.php +++ b/src/administrator/components/com_weblinks/tmpl/weblinks/emptystate.php @@ -1,4 +1,5 @@ 'COM_WEBLINKS', - 'formURL' => 'index.php?option=com_weblinks', - 'helpURL' => 'https://docs.joomla.org/Special:MyLanguage/Help4.x:Weblinks', - 'icon' => 'icon-globe weblink', + 'textPrefix' => 'COM_WEBLINKS', + 'formURL' => 'index.php?option=com_weblinks', + 'helpURL' => 'https://docs.joomla.org/Special:MyLanguage/Help4.x:Weblinks', + 'icon' => 'icon-globe weblink', ]; - $user = Factory::getApplication()->getIdentity(); - -if ($user->authorise('core.create', 'com_weblinks') || count($user->getAuthorisedCategories('com_weblinks', 'core.create')) > 0) -{ - $displayData['createURL'] = 'index.php?option=com_weblinks&task=weblink.add'; +if ($user->authorise('core.create', 'com_weblinks') || count($user->getAuthorisedCategories('com_weblinks', 'core.create')) > 0) { + $displayData['createURL'] = 'index.php?option=com_weblinks&task=weblink.add'; } -echo LayoutHelper::render('joomla.content.emptystate', $displayData); \ No newline at end of file +echo LayoutHelper::render('joomla.content.emptystate', $displayData); diff --git a/src/administrator/components/com_weblinks/tmpl/weblinks/modal.php b/src/administrator/components/com_weblinks/tmpl/weblinks/modal.php index 05081f4..82c76d9 100644 --- a/src/administrator/components/com_weblinks/tmpl/weblinks/modal.php +++ b/src/administrator/components/com_weblinks/tmpl/weblinks/modal.php @@ -1,4 +1,5 @@ isClient('site')) -{ - Session::checkToken('get') or die(Text::_('JINVALID_TOKEN')); +if ($app->isClient('site')) { + Session::checkToken('get') or die(Text::_('JINVALID_TOKEN')); } HTMLHelper::_('behavior.multiselect'); - $this->document->getWebAssetManager() - ->registerAndUseScript('com_weblinks.admin-weblinks-modal', 'media/com_weblinks/js/admin-weblinks-modal.js', [], ['defer' => true], ['core']); - + ->registerAndUseScript('com_weblinks.admin-weblinks-modal', 'media/com_weblinks/js/admin-weblinks-modal.js', [], ['defer' => true], ['core']); $function = $app->input->getCmd('function', 'jSelectWeblink'); $editor = $app->input->getCmd('editor', ''); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $onclick = $this->escape($function); $multilang = Multilanguage::isEnabled(); - -if (!empty($editor)) -{ - // This view is used also in com_menus. Load the xtd script only if the editor is set! - $this->document->addScriptOptions('xtd-weblinks', array('editor' => $editor)); - $onclick = "jSelectWeblink"; +if (!empty($editor)) { +// This view is used also in com_menus. Load the xtd script only if the editor is set! + $this->document->addScriptOptions('xtd-weblinks', array('editor' => $editor)); + $onclick = "jSelectWeblink"; } $iconStates = array( - -2 => 'icon-trash', - 0 => 'icon-unpublish', - 1 => 'icon-publish', - 2 => 'icon-archive', + -2 => 'icon-trash', + 0 => 'icon-unpublish', + 1 => 'icon-publish', + 2 => 'icon-archive', ); ?>
-
+ - $this)); ?> + $this)); ?> - items)) : ?> -
- -
- - - - - - - - - - - - - - - - - items as $i => $item) : ?> - - language && $multilang) : ?> - language); ?> - - language, 0, 2); ?> - - language, 0, 3); ?> - - - - - - - - - - - - - - -
- , - , - -
- - - - - - - - - - - -
- - - escape($onclick) . '"' - . ' data-id="' . $item->id . '"' - . ' data-title="' . $this->escape(addslashes($item->title)) . '"' - . ' data-cat-id="' . $this->escape($item->catid) . '"' - . ' data-uri="' . $this->escape(RouteHelper::getWeblinkRoute($item->id, $item->catid, $item->language)) . '"' - . ' data-language="' . $this->escape($lang) . '"'; - ?> - > - escape($item->title); ?> - -
- escape($item->category_title); ?> -
-
- escape($item->access_level); ?> - - - - created, Text::_('DATE_FORMAT_LC4')); ?> - - id; ?> -
- + items)) : + ?> +
+ +
+ + + + + + + + + + + + + + + + + items as $i => $item) : + ?> + + language && $multilang) : + ?> + language); ?> + + language, 0, 2); ?> + + language, 0, 3); ?> + + + + + + + + + + + + + + +
+ , + , + +
+ + + + + + + + + + + +
+ + + escape($onclick) . '"' + . ' data-id="' . $item->id . '"' + . ' data-title="' . $this->escape(addslashes($item->title)) . '"' + . ' data-cat-id="' . $this->escape($item->catid) . '"' + . ' data-uri="' . $this->escape(RouteHelper::getWeblinkRoute($item->id, $item->catid, $item->language)) . '"' + . ' data-language="' . $this->escape($lang) . '"'; + ?> + > + escape($item->title); ?> + +
+ escape($item->category_title); ?> +
+
+ escape($item->access_level); ?> + + + + created, Text::_('DATE_FORMAT_LC4')); ?> + + id; ?> +
+ - - pagination->getListFooter(); ?> + + pagination->getListFooter(); ?> - - - - + + + + -
+
diff --git a/src/administrator/manifests/packages/weblinks/script.php b/src/administrator/manifests/packages/weblinks/script.php index e9a8179..99ab66a 100644 --- a/src/administrator/manifests/packages/weblinks/script.php +++ b/src/administrator/manifests/packages/weblinks/script.php @@ -1,4 +1,5 @@ minimumJoomla = '3.6.3'; - $this->minimumPhp = JOOMLA_MINIMUM_PHP; - } + /** + * Extension script constructor. + * + * @since __DEPLOY_VERSION__ + */ + public function __construct() + { + $this->minimumJoomla = '3.6.3'; + $this->minimumPhp = JOOMLA_MINIMUM_PHP; + } } diff --git a/src/components/com_weblinks/helpers/icon.php b/src/components/com_weblinks/helpers/icon.php index 6150446..567974d 100644 --- a/src/components/com_weblinks/helpers/icon.php +++ b/src/components/com_weblinks/helpers/icon.php @@ -1,4 +1,5 @@ create($category, $params); - } + /** + * Create a link to create a new weblink + * + * @param object $category The category information + * @param \Joomla\Registry\Registry $params The item parameters + * + * @return string + */ + public static function create($category, $params) + { + return self::getIcon()->create($category, $params); + } - /** - * Create a link to edit an existing weblink - * - * @param object $weblink Weblink data - * @param \Joomla\Registry\Registry $params Item params - * @param array $attribs Unused - * - * @return string - */ - public static function edit($weblink, $params, $attribs = array()) - { - return self::getIcon()->edit($weblink, $params, $attribs); - } + /** + * Create a link to edit an existing weblink + * + * @param object $weblink Weblink data + * @param \Joomla\Registry\Registry $params Item params + * @param array $attribs Unused + * + * @return string + */ + public static function edit($weblink, $params, $attribs = []) + { + return self::getIcon()->edit($weblink, $params, $attribs); + } - /** - * Creates an icon instance. - * - * @return \Joomla\Component\Weblinks\Administrator\Service\HTML\Icon - */ - private static function getIcon() - { - return (new \Joomla\Component\Weblinks\Administrator\Service\HTML\Icon(Joomla\CMS\Factory::getApplication())); - } + /** + * Creates an icon instance. + * + * @return \Joomla\Component\Weblinks\Administrator\Service\HTML\Icon + */ + private static function getIcon() + { + return (new \Joomla\Component\Weblinks\Administrator\Service\HTML\Icon(Joomla\CMS\Factory::getApplication())); + } } diff --git a/src/components/com_weblinks/helpers/route.php b/src/components/com_weblinks/helpers/route.php index c239da3..432bcc3 100644 --- a/src/components/com_weblinks/helpers/route.php +++ b/src/components/com_weblinks/helpers/route.php @@ -1,4 +1,5 @@ input->getInt('w_id'); + $vName = $this->input->get('view', 'categories'); + $this->input->set('view', $vName); + if ($this->app->getIdentity()->id || ($this->input->getMethod() == 'POST' && $vName == 'categories')) { + $cacheable = false; + } - /** - * Set the default view name and format from the Request. - * Note we are using w_id to avoid collisions with the router and the return page. - * Frontend is a bit messier than the backend. - */ - $id = $this->input->getInt('w_id'); - $vName = $this->input->get('view', 'categories'); - $this->input->set('view', $vName); + $safeurlparams = [ + 'id' => 'INT', + 'limit' => 'UINT', + 'limitstart' => 'UINT', + 'filter_order' => 'CMD', + 'filter_order_Dir' => 'CMD', + 'lang' => 'CMD', + ]; + // Check for edit form. + if ($vName == 'form' && !$this->checkEditId('com_weblinks.edit.weblink', $id)) { + // Somehow the person just went to the form - we don't allow that. + throw new \Exception(Text::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $id), 403); + } - if ($this->app->getIdentity()->id ||($this->input->getMethod() == 'POST' && $vName == 'categories')) - { - $cacheable = false; - } - - $safeurlparams = array( - 'id' => 'INT', - 'limit' => 'UINT', - 'limitstart' => 'UINT', - 'filter_order' => 'CMD', - 'filter_order_Dir' => 'CMD', - 'lang' => 'CMD' - ); - - // Check for edit form. - if ($vName == 'form' && !$this->checkEditId('com_weblinks.edit.weblink', $id)) - { - // Somehow the person just went to the form - we don't allow that. - throw new \Exception(Text::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $id), 403); - } - - return parent::display($cacheable, $safeurlparams); - } + return parent::display($cacheable, $safeurlparams); + } } diff --git a/src/components/com_weblinks/src/Controller/WeblinkController.php b/src/components/com_weblinks/src/Controller/WeblinkController.php index 85f0d4f..404829a 100644 --- a/src/components/com_weblinks/src/Controller/WeblinkController.php +++ b/src/components/com_weblinks/src/Controller/WeblinkController.php @@ -1,4 +1,5 @@ setRedirect($this->getReturnPage()); + return false; + } - /** - * The URL view list variable. - * - * @var string - * @since 1.6 - */ - protected $view_list = 'categories'; + return true; + } - /** - * The URL edit variable. - * - * @var string - * @since 3.2 - */ - protected $urlVar = 'a.id'; + /** + * Method override to check if you can add a new record. + * + * @param array $data An array of input data. + * + * @return boolean + * + * @since 1.6 + */ + protected function allowAdd($data = []) + { + $categoryId = ArrayHelper::getValue($data, 'catid', $this->input->getInt('id'), 'int'); + if ($categoryId) { + // If the category has been passed in the URL check it. + return $this->app->getIdentity()->authorise('core.create', $this->option . '.category.' . $categoryId); + } - /** - * Method to add a new record. - * - * @return boolean True if the article can be added, false if not. - * - * @since 1.6 - */ - public function add() - { - if (!parent::add()) - { - // Redirect to the return page. - $this->setRedirect($this->getReturnPage()); + // In the absence of better information, revert to the component permissions. + return parent::allowAdd($data); + } - return false; - } + /** + * Method to check if you can add a new record. + * + * @param array $data An array of input data. + * @param string $key The name of the key for the primary key. + * + * @return boolean + * + * @since 1.6 + */ + protected function allowEdit($data = [], $key = 'id') + { + $recordId = (int) isset($data[$key]) ? $data[$key] : 0; + if (!$recordId) { + return false; + } - return true; - } + $record = $this->getModel()->getItem($recordId); + $categoryId = (int) $record->catid; + if ($categoryId) { + // The category has been set. Check the category permissions. + $user = $this->app->getIdentity(); + // First, check edit permission + if ($user->authorise('core.edit', $this->option . '.category.' . $categoryId)) { + return true; + } - /** - * Method override to check if you can add a new record. - * - * @param array $data An array of input data. - * - * @return boolean - * - * @since 1.6 - */ - protected function allowAdd($data = array()) - { - $categoryId = ArrayHelper::getValue($data, 'catid', $this->input->getInt('id'), 'int'); + // Fallback on edit.own + if ($user->authorise('core.edit.own', $this->option . '.category.' . $categoryId) && $record->created_by == $user->id) { + return true; + } - if ($categoryId) - { - // If the category has been passed in the URL check it. - return $this->app->getIdentity()->authorise('core.create', $this->option . '.category.' . $categoryId); - } + return false; + } - // In the absence of better information, revert to the component permissions. - return parent::allowAdd($data); - } + // Since there is no asset tracking, revert to the component permissions. + return parent::allowEdit($data, $key); + } - /** - * Method to check if you can add a new record. - * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key. - * - * @return boolean - * - * @since 1.6 - */ - protected function allowEdit($data = array(), $key = 'id') - { - $recordId = (int) isset($data[$key]) ? $data[$key] : 0; + /** + * Method to cancel an edit. + * + * @param string $key The name of the primary key of the URL variable. + * + * @return boolean True if access level checks pass, false otherwise. + * + * @since 1.6 + */ + public function cancel($key = 'w_id') + { + $return = parent::cancel($key); + // Redirect to the return page. + $this->setRedirect($this->getReturnPage()); + return $return; + } - if (!$recordId) - { - return false; - } + /** + * Method to edit an existing record. + * + * @param string $key The name of the primary key of the URL variable. + * @param string $urlVar The name of the URL variable if different from the primary key (sometimes required to avoid router collisions). + * + * @return boolean True if access level check and checkout passes, false otherwise. + * + * @since 1.6 + */ + public function edit($key = null, $urlVar = 'w_id') + { + return parent::edit($key, $urlVar); + } - $record = $this->getModel()->getItem($recordId); - $categoryId = (int) $record->catid; + /** + * Method to get a model object, loading it if required. + * + * @param string $name The model name. Optional. + * @param string $prefix The class prefix. Optional. + * @param array $config Configuration array for model. Optional. + * + * @return object The model. + * + * @since 1.5 + */ + public function getModel($name = 'form', $prefix = 'Site', $config = ['ignore_request' => true]) + { + return parent::getModel($name, $prefix, $config); + } - if ($categoryId) - { - // The category has been set. Check the category permissions. - $user = $this->app->getIdentity(); + /** + * Gets the URL arguments to append to an item redirect. + * + * @param integer $recordId The primary key id for the item. + * @param string $urlVar The name of the URL variable for the id. + * + * @return string The arguments to append to the redirect URL. + * + * @since 1.6 + */ + protected function getRedirectToItemAppend($recordId = null, $urlVar = null) + { + $append = parent::getRedirectToItemAppend($recordId, $urlVar); + $itemId = $this->input->getInt('Itemid'); + $return = $this->getReturnPage(); + if ($itemId) { + $append .= '&Itemid=' . $itemId; + } - // First, check edit permission - if ($user->authorise('core.edit', $this->option . '.category.' . $categoryId)) - { - return true; - } + if ($return) { + $append .= '&return=' . base64_encode($return); + } - // Fallback on edit.own - if ($user->authorise('core.edit.own', $this->option . '.category.' . $categoryId) && $record->created_by == $user->id) - { - return true; - } + return $append; + } - return false; - } + /** + * Get the return URL if a "return" variable has been passed in the request + * + * @return string The return URL. + * + * @since 1.6 + */ + protected function getReturnPage() + { + $return = $this->input->get('return', null, 'base64'); + if (empty($return) || !Uri::isInternal(base64_decode($return))) { + return Uri::base(); + } - // Since there is no asset tracking, revert to the component permissions. - return parent::allowEdit($data, $key); - } + return base64_decode($return); + } - /** - * Method to cancel an edit. - * - * @param string $key The name of the primary key of the URL variable. - * - * @return boolean True if access level checks pass, false otherwise. - * - * @since 1.6 - */ - public function cancel($key = 'w_id') - { - $return = parent::cancel($key); + /** + * Method to save a record. + * + * @param string $key The name of the primary key of the URL variable. + * @param string $urlVar The name of the URL variable if different from the primary key (sometimes required to avoid router collisions). + * + * @return boolean True if successful, false otherwise. + * + * @since 1.6 + */ + public function save($key = null, $urlVar = 'w_id') + { + // Get the application + $app = $this->app; + // Get the data from POST + $data = $this->input->post->get('jform', [], 'array'); + // Save the data in the session. + $app->setUserState('com_weblinks.edit.weblink.data', $data); + $result = parent::save($key, $urlVar); + // If ok, redirect to the return page. + if ($result) { + // Flush the data from the session + $app->setUserState('com_weblinks.edit.weblink.data', null); + $this->setRedirect($this->getReturnPage()); + } - // Redirect to the return page. - $this->setRedirect($this->getReturnPage()); + return $result; + } - return $return; - } + /** + * Go to a weblink + * + * @return void + * + * @throws \Exception + * + * @since 1.6 + */ + public function go() + { + // Get the ID from the request + $id = $this->input->getInt('id'); + // Get the model, requiring published items + $modelLink = $this->getModel('Weblink'); + $modelLink->setState('filter.published', 1); + // Get the item + $link = $modelLink->getItem($id); + // Make sure the item was found. + if (empty($link)) { + throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_NOT_FOUND'), 404); + } - /** - * Method to edit an existing record. - * - * @param string $key The name of the primary key of the URL variable. - * @param string $urlVar The name of the URL variable if different from the primary key (sometimes required to avoid router collisions). - * - * @return boolean True if access level check and checkout passes, false otherwise. - * - * @since 1.6 - */ - public function edit($key = null, $urlVar = 'w_id') - { - return parent::edit($key, $urlVar); - } + // Check whether item access level allows access. + $groups = $this->app->getIdentity()->getAuthorisedViewLevels(); + if (!in_array($link->access, $groups)) { + throw new \Exception(Text::_('JERROR_ALERTNOAUTHOR'), 403); + } - /** - * Method to get a model object, loading it if required. - * - * @param string $name The model name. Optional. - * @param string $prefix The class prefix. Optional. - * @param array $config Configuration array for model. Optional. - * - * @return object The model. - * - * @since 1.5 - */ - public function getModel($name = 'form', $prefix = 'Site', $config = array('ignore_request' => true)) - { - return parent::getModel($name, $prefix, $config); - } + // Check whether category access level allows access. + $modelCat = $this->getModel('Category', 'Site', ['ignore_request' => true]); + $modelCat->setState('filter.published', 1); + // Get the category + $category = $modelCat->getCategory($link->catid); + // Make sure the category was found. + if (empty($category)) { + throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_NOT_FOUND'), 404); + } - /** - * Gets the URL arguments to append to an item redirect. - * - * @param integer $recordId The primary key id for the item. - * @param string $urlVar The name of the URL variable for the id. - * - * @return string The arguments to append to the redirect URL. - * - * @since 1.6 - */ - protected function getRedirectToItemAppend($recordId = null, $urlVar = null) - { - $append = parent::getRedirectToItemAppend($recordId, $urlVar); - $itemId = $this->input->getInt('Itemid'); - $return = $this->getReturnPage(); + // Check whether item access level allows access. + if (!in_array($category->access, $groups)) { + throw new \Exception(Text::_('JERROR_ALERTNOAUTHOR'), 403); + } - if ($itemId) - { - $append .= '&Itemid=' . $itemId; - } + // Redirect to the URL + if ($link->url) { + $modelLink->hit($id); + $this->app->redirect($link->url, 301); + } - if ($return) - { - $append .= '&return=' . base64_encode($return); - } - - return $append; - } - - /** - * Get the return URL if a "return" variable has been passed in the request - * - * @return string The return URL. - * - * @since 1.6 - */ - protected function getReturnPage() - { - $return = $this->input->get('return', null, 'base64'); - - if (empty($return) || !Uri::isInternal(base64_decode($return))) - { - return Uri::base(); - } - - return base64_decode($return); - } - - /** - * Method to save a record. - * - * @param string $key The name of the primary key of the URL variable. - * @param string $urlVar The name of the URL variable if different from the primary key (sometimes required to avoid router collisions). - * - * @return boolean True if successful, false otherwise. - * - * @since 1.6 - */ - public function save($key = null, $urlVar = 'w_id') - { - // Get the application - $app = $this->app; - - // Get the data from POST - $data = $this->input->post->get('jform', array(), 'array'); - - // Save the data in the session. - $app->setUserState('com_weblinks.edit.weblink.data', $data); - $result = parent::save($key, $urlVar); - - // If ok, redirect to the return page. - if ($result) - { - // Flush the data from the session - $app->setUserState('com_weblinks.edit.weblink.data', null); - $this->setRedirect($this->getReturnPage()); - } - - return $result; - } - - /** - * Go to a weblink - * - * @return void - * - * @throws \Exception - * - * @since 1.6 - */ - public function go() - { - // Get the ID from the request - $id = $this->input->getInt('id'); - - // Get the model, requiring published items - $modelLink = $this->getModel('Weblink'); - $modelLink->setState('filter.published', 1); - - // Get the item - $link = $modelLink->getItem($id); - - // Make sure the item was found. - if (empty($link)) - { - throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_NOT_FOUND'), 404); - } - - // Check whether item access level allows access. - $groups = $this->app->getIdentity()->getAuthorisedViewLevels(); - - if (!in_array($link->access, $groups)) - { - throw new \Exception(Text::_('JERROR_ALERTNOAUTHOR'), 403); - } - - // Check whether category access level allows access. - $modelCat = $this->getModel('Category', 'Site', array('ignore_request' => true)); - $modelCat->setState('filter.published', 1); - - // Get the category - $category = $modelCat->getCategory($link->catid); - - // Make sure the category was found. - if (empty($category)) - { - throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_NOT_FOUND'), 404); - } - - // Check whether item access level allows access. - if (!in_array($category->access, $groups)) - { - throw new \Exception(Text::_('JERROR_ALERTNOAUTHOR'), 403); - } - - // Redirect to the URL - if ($link->url) - { - $modelLink->hit($id); - $this->app->redirect($link->url, 301); - } - - throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_URL_INVALID'), 404); - } + throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_URL_INVALID'), 404); + } } diff --git a/src/components/com_weblinks/src/Helper/AssociationHelper.php b/src/components/com_weblinks/src/Helper/AssociationHelper.php index 279bc37..6f73064 100644 --- a/src/components/com_weblinks/src/Helper/AssociationHelper.php +++ b/src/components/com_weblinks/src/Helper/AssociationHelper.php @@ -1,4 +1,5 @@ input; - $view = is_null($view) ? $input->get('view') : $view; - $id = empty($id) ? $input->getInt('id') : $id; + /** + * Method to get the associations for a given item + * + * @param integer $id Id of the item + * @param string $view Name of the view + * + * @return array Array of associations for the item + * + * @since 3.0 + */ + public static function getAssociations($id = 0, $view = null) + { + $input = Factory::getApplication()->input; + $view = is_null($view) ? $input->get('view') : $view; + $id = empty($id) ? $input->getInt('id') : $id; + if ($view === 'weblink') { + if ($id) { + $associations = Associations::getAssociations('com_weblinks', '#__weblinks', 'com_weblinks.item', $id); + $return = []; + foreach ($associations as $tag => $item) { + $return[$tag] = RouteHelper::getWeblinkRoute($item->id, (int) $item->catid, $item->language); + } - if ($view === 'weblink') - { - if ($id) - { - $associations = Associations::getAssociations('com_weblinks', '#__weblinks', 'com_weblinks.item', $id); + return $return; + } + } - $return = array(); + if ($view == 'category' || $view == 'categories') { + return self::getCategoryAssociations($id, 'com_weblinks'); + } - foreach ($associations as $tag => $item) - { - $return[$tag] = RouteHelper::getWeblinkRoute($item->id, (int) $item->catid, $item->language); - } - - return $return; - } - } - - if ($view == 'category' || $view == 'categories') - { - return self::getCategoryAssociations($id, 'com_weblinks'); - } - - return array(); - } + return []; + } } diff --git a/src/components/com_weblinks/src/Helper/RouteHelper.php b/src/components/com_weblinks/src/Helper/RouteHelper.php index c85a2a2..f3b4cfa 100644 --- a/src/components/com_weblinks/src/Helper/RouteHelper.php +++ b/src/components/com_weblinks/src/Helper/RouteHelper.php @@ -1,4 +1,5 @@ 1) { + $link .= '&catid=' . $catid; + } - if ($catid > 1) - { - $link .= '&catid=' . $catid; - } + if ($language && $language !== '*' && Multilanguage::isEnabled()) { + $link .= '&lang=' . $language; + } - if ($language && $language !== '*' && Multilanguage::isEnabled()) - { - $link .= '&lang=' . $language; - } + return $link; + } - return $link; - } + /** + * Ge the form route + * + * @param integer $id The id of the weblink. + * @param string $return The return page variable. + * + * @return string + */ + public static function getFormRoute($id, $return = null) + { + // Create the link. + if ($id) { + $link = 'index.php?option=com_weblinks&task=weblink.edit&w_id=' . $id; + } else { + $link = 'index.php?option=com_weblinks&task=weblink.add&w_id=0'; + } - /** - * Ge the form route - * - * @param integer $id The id of the weblink. - * @param string $return The return page variable. - * - * @return string - */ - public static function getFormRoute($id, $return = null) - { - // Create the link. - if ($id) - { - $link = 'index.php?option=com_weblinks&task=weblink.edit&w_id=' . $id; - } - else - { - $link = 'index.php?option=com_weblinks&task=weblink.add&w_id=0'; - } + if ($return) { + $link .= '&return=' . $return; + } - if ($return) - { - $link .= '&return=' . $return; - } + return $link; + } - return $link; - } + /** + * Get the Category Route + * + * @param CategoryNode|string|integer $catid JCategoryNode object or category ID + * @param integer $language Language code + * + * @return string + */ + public static function getCategoryRoute($catid, $language = 0) + { + if ($catid instanceof CategoryNode) { + $id = $catid->id; + } else { + $id = (int) $catid; + } - /** - * Get the Category Route - * - * @param CategoryNode|string|integer $catid JCategoryNode object or category ID - * @param integer $language Language code - * - * @return string - */ - public static function getCategoryRoute($catid, $language = 0) - { - if ($catid instanceof CategoryNode) - { - $id = $catid->id; - } - else - { - $id = (int) $catid; - } + if ($id < 1) { + $link = ''; + } else { + // Create the link + $link = 'index.php?option=com_weblinks&view=category&id=' . $id; + if ($language && $language !== '*' && Multilanguage::isEnabled()) { + $link .= '&lang=' . $language; + } + } - if ($id < 1) - { - $link = ''; - } - else - { - // Create the link - $link = 'index.php?option=com_weblinks&view=category&id=' . $id; - - if ($language && $language !== '*' && Multilanguage::isEnabled()) - { - $link .= '&lang=' . $language; - } - } - - return $link; - } + return $link; + } } diff --git a/src/components/com_weblinks/src/Model/CategoriesModel.php b/src/components/com_weblinks/src/Model/CategoriesModel.php index a3cc4bf..4744d68 100644 --- a/src/components/com_weblinks/src/Model/CategoriesModel.php +++ b/src/components/com_weblinks/src/Model/CategoriesModel.php @@ -1,4 +1,5 @@ setState('filter.extension', $this->_extension); + // Get the parent id if defined. + $parentId = $app->input->getInt('id'); + $this->setState('filter.parentId', $parentId); + $params = $app->getParams(); + $this->setState('params', $params); + $this->setState('filter.published', 1); + $this->setState('filter.access', true); + } - /** - * The category context (allows other extensions to derived from this model). - * - * @var string - */ - protected $_extension = 'com_weblinks'; + /** + * Method to get a store id based on model configuration state. + * + * This is necessary because the model is used by the component and + * different modules that might need different sets of data or different + * ordering requirements. + * + * @param string $id A prefix for the store id. + * + * @return string A store id. + */ + protected function getStoreId($id = '') + { + // Compile the store id. + $id .= ':' . $this->getState('filter.extension'); + $id .= ':' . $this->getState('filter.published'); + $id .= ':' . $this->getState('filter.access'); + $id .= ':' . $this->getState('filter.parentId'); + return parent::getStoreId($id); + } - /** - * Parent category - * - * @var CategoryNode|null - */ - private $_parent = null; + /** + * Redefine the function and add some properties to make the styling more easy + * + * @return mixed An array of data items on success, false on failure. + */ + public function getItems() + { + if ($this->_items === null) { + $params = $this->getState('params', new Registry()); + $options = []; + $options['access'] = $this->getState('filter.access'); + $options['published'] = $this->getState('filter.published'); + $options['countItems'] = $params->get('show_cat_num_links', 1) || !$params->get('show_empty_categories_cat', 0); + $categories = Categories::getInstance('Weblinks', $options); + $this->_parent = $categories->get($this->getState('filter.parentId', 'root')); + if (is_object($this->_parent)) { + $this->_items = $this->_parent->getChildren(); + } else { + $this->_items = false; + } + } - /** - * Categories data - * - * @var false|array - */ - private $_items = null; + return $this->_items; + } - /** - * Method to auto-populate the model state. - * - * Note. Calling getState in this method will result in recursion. - * - * @param string $ordering An optional ordering field. - * @param string $direction An optional direction (asc|desc). - * - * @return void - * - * @since 1.6 - */ - protected function populateState($ordering = null, $direction = null) - { - $app = Factory::getApplication(); - $this->setState('filter.extension', $this->_extension); + /** + * Get the parent + * + * @return mixed An array of data items on success, false on failure. + */ + public function getParent() + { + if (!is_object($this->_parent)) { + $this->getItems(); + } - // Get the parent id if defined. - $parentId = $app->input->getInt('id'); - $this->setState('filter.parentId', $parentId); - - $params = $app->getParams(); - $this->setState('params', $params); - - $this->setState('filter.published', 1); - $this->setState('filter.access', true); - } - - /** - * Method to get a store id based on model configuration state. - * - * This is necessary because the model is used by the component and - * different modules that might need different sets of data or different - * ordering requirements. - * - * @param string $id A prefix for the store id. - * - * @return string A store id. - */ - protected function getStoreId($id = '') - { - // Compile the store id. - $id .= ':' . $this->getState('filter.extension'); - $id .= ':' . $this->getState('filter.published'); - $id .= ':' . $this->getState('filter.access'); - $id .= ':' . $this->getState('filter.parentId'); - - return parent::getStoreId($id); - } - - /** - * Redefine the function and add some properties to make the styling more easy - * - * @return mixed An array of data items on success, false on failure. - */ - public function getItems() - { - if ($this->_items === null) - { - $params = $this->getState('params', new Registry); - - $options = array(); - $options['access'] = $this->getState('filter.access'); - $options['published'] = $this->getState('filter.published'); - $options['countItems'] = $params->get('show_cat_num_links', 1) || !$params->get('show_empty_categories_cat', 0); - $categories = Categories::getInstance('Weblinks', $options); - $this->_parent = $categories->get($this->getState('filter.parentId', 'root')); - - if (is_object($this->_parent)) - { - $this->_items = $this->_parent->getChildren(); - } - else - { - $this->_items = false; - } - } - - return $this->_items; - } - - /** - * Get the parent - * - * @return mixed An array of data items on success, false on failure. - */ - public function getParent() - { - if (!is_object($this->_parent)) - { - $this->getItems(); - } - - return $this->_parent; - } + return $this->_parent; + } } diff --git a/src/components/com_weblinks/src/Model/CategoryModel.php b/src/components/com_weblinks/src/Model/CategoryModel.php index 47a2a7d..c17a6e4 100644 --- a/src/components/com_weblinks/src/Model/CategoryModel.php +++ b/src/components/com_weblinks/src/Model/CategoryModel.php @@ -1,4 +1,5 @@ _params)) - { - $item->params = new Registry($item->params); - } - - // Some contexts may not use tags data at all, so we allow callers to disable loading tag data - if ($this->getState('load_tags', true)) - { - $item->tags = new TagsHelper; - $taggedItems[$item->id] = $item; - } - } - - // Load tags of all items. - if ($taggedItems) - { - $tagsHelper = new TagsHelper(); - $itemIds = \array_keys($taggedItems); - - foreach ($tagsHelper->getMultipleItemTags('com_weblinks.weblink', $itemIds) as $id => $tags) - { - $taggedItems[$id]->tags->itemTags = $tags; - } - } - - return $items; - } - - /** - * Method to get a JDatabaseQuery object for retrieving the data set from a database. - * - * @return \JDatabaseQuery A JDatabaseQuery object to retrieve the data set. - * - * @since 1.6 - */ - protected function getListQuery() - { - $viewLevels = $this->getCurrentUser()->getAuthorisedViewLevels(); - - // Create a new query object. - $db = $this->getDatabase(); - $query = $db->getQuery(true); - - // Select required fields from the categories. - $query->select($this->getState('list.select', 'a.*')) - ->from($db->quoteName('#__weblinks') . ' AS a') - ->whereIn($db->quoteName('a.access'), $viewLevels); - - // Filter by category. - if ($categoryId = $this->getState('category.id')) - { - // Group by subcategory - if ($this->getState('category.group', 0)) - { - $query->select('c.title AS category_title') - ->where('c.parent_id = :parent_id') - ->bind(':parent_id', $categoryId, ParameterType::INTEGER) - ->join('LEFT', '#__categories AS c ON c.id = a.catid') - ->whereIn($db->quoteName('c.access'), $viewLevels); - } - else - { - $query->where('a.catid = :catid') - ->bind(':catid', $categoryId, ParameterType::INTEGER) - ->join('LEFT', '#__categories AS c ON c.id = a.catid') - ->whereIn($db->quoteName('c.access'), $viewLevels); - } - - // Filter by published category - $cpublished = $this->getState('filter.c.published'); - - if (is_numeric($cpublished)) - { - $query->where('c.published = :published') - ->bind(':published', $cpublished, ParameterType::INTEGER); - } - } - - // Join over the users for the author and modified_by names. - $query->select("CASE WHEN a.created_by_alias > ' ' THEN a.created_by_alias ELSE ua.name END AS author") - ->select("ua.email AS author_email") - ->join('LEFT', '#__users AS ua ON ua.id = a.created_by') - ->join('LEFT', '#__users AS uam ON uam.id = a.modified_by'); - - // Filter by state - $state = $this->getState('filter.state'); - - if (is_numeric($state)) - { - $query->where('a.state = :state') - ->bind(':state', $state, ParameterType::INTEGER); - } - - // Do not show trashed links on the front-end - $query->where('a.state != -2'); - - // Filter by start and end dates. - if ($this->getState('filter.publish_date')) - { - $nowDate = Factory::getDate()->toSql(); - $query->where('(' . $db->quoteName('a.publish_up') - . ' IS NULL OR ' . $db->quoteName('a.publish_up') . ' <= :publish_up)' - ) - ->where('(' . $db->quoteName('a.publish_down') - . ' IS NULL OR ' . $db->quoteName('a.publish_down') . ' >= :publish_down)' - ) - ->bind(':publish_up', $nowDate) - ->bind(':publish_down', $nowDate); - } - - // Filter by language - if ($this->getState('filter.language')) - { - $query->whereIn($db->quoteName('a.language'), [Factory::getLanguage()->getTag(), '*'], ParameterType::STRING); - } - - // Filter by search in title - $search = $this->getState('list.filter'); - - if (!empty($search)) - { - $search = '%' . trim($search) . '%'; - $query->where('(a.title LIKE :search)') - ->bind(':search', $search); - } - - // If grouping by subcategory, add the subcategory list ordering clause. - if ($this->getState('category.group', 0)) - { - $query->order( - $db->escape($this->getState('category.ordering', 'c.lft')) . ' ' . - $db->escape($this->getState('category.direction', 'ASC')) - ); - } - - // Add the list ordering clause. - $query->order( - $db->escape($this->getState('list.ordering', 'a.ordering')) . ' ' . - $db->escape($this->getState('list.direction', 'ASC')) - ); - - return $query; - } - - /** - * Method to auto-populate the model state. - * - * Note. Calling getState in this method will result in recursion. - * - * @param string $ordering An optional ordering field. - * @param string $direction An optional direction (asc|desc). - * - * @return void - * - * @since 1.6 - */ - protected function populateState($ordering = null, $direction = null) - { - $app = Factory::getApplication(); - - $params = $app->getParams(); - $this->setState('params', $params); - - // List state information - $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->get('list_limit'), 'uint'); - $this->setState('list.limit', $limit); - - $limitstart = $app->input->get('limitstart', 0, 'uint'); - $this->setState('list.start', $limitstart); - - // Optional filter text - $this->setState('list.filter', $app->input->getString('filter-search')); - - $orderCol = $app->input->get('filter_order', 'ordering'); - - if (!in_array($orderCol, $this->filter_fields)) - { - $orderCol = 'ordering'; - } - - $this->setState('list.ordering', $orderCol); - - $listOrder = $app->input->get('filter_order_Dir', 'ASC'); - - if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) - { - $listOrder = 'ASC'; - } - - $this->setState('list.direction', $listOrder); - - $id = $app->input->get('id', 0, 'int'); - $this->setState('category.id', $id); - - $user = $this->getCurrentUser(); - - if (!$user->authorise('core.edit.state', 'com_weblinks') && !$user->authorise('core.edit', 'com_weblinks')) - { - // Limit to published for people who can't edit or edit.state. - $this->setState('filter.state', 1); - - // Filter by start and end dates. - $this->setState('filter.publish_date', true); - } - - $this->setState('filter.language', Multilanguage::isEnabled()); - } - - /** - * Method to get category data for the current category - * - * @return object - * - * @since 1.5 - */ - public function getCategory() - { - if (!is_object($this->_item)) - { - $params = $this->getState('params', new Registry); - - $options = array(); - $options['countItems'] = $params->get('show_cat_num_links_cat', 1) - || $params->get('show_empty_categories', 0); - - $categories = Categories::getInstance('Weblinks', $options); - $this->_item = $categories->get($this->getState('category.id', 'root')); - - if (is_object($this->_item)) - { - $this->_children = $this->_item->getChildren(); - $this->_parent = false; - - if ($this->_item->getParent()) - { - $this->_parent = $this->_item->getParent(); - } - - $this->_rightsibling = $this->_item->getSibling(); - $this->_leftsibling = $this->_item->getSibling(false); - } - else - { - $this->_children = false; - $this->_parent = false; - } - } - - return $this->_item; - } - - /** - * Get the parent category - * - * @return mixed An array of categories or false if an error occurs. - */ - public function getParent() - { - if (!is_object($this->_item)) - { - $this->getCategory(); - } - - return $this->_parent; - } - - /** - * Get the leftsibling (adjacent) categories. - * - * @return mixed An array of categories or false if an error occurs. - */ - public function &getLeftSibling() - { - if (!is_object($this->_item)) - { - $this->getCategory(); - } - - return $this->_leftsibling; - } - - /** - * Get the rightsibling (adjacent) categories. - * - * @return mixed An array of categories or false if an error occurs. - */ - public function &getRightSibling() - { - if (!is_object($this->_item)) - { - $this->getCategory(); - } - - return $this->_rightsibling; - } - - /** - * Get the child categories. - * - * @return mixed An array of categories or false if an error occurs. - */ - public function &getChildren() - { - if (!is_object($this->_item)) - { - $this->getCategory(); - } - - return $this->_children; - } - - /** - * Increment the hit counter for the category. - * - * @param integer $pk Optional primary key of the category to increment. - * - * @return boolean True if successful; false otherwise and internal error set. - * - * @since 3.2 - */ - public function hit($pk = 0) - { - $hitcount = Factory::getApplication()->input->getInt('hitcount', 1); - - if ($hitcount) - { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('category.id'); - $table = Table::getInstance('Category', 'Joomla\\CMS\\Table\\'); - $table->load($pk); - $table->hit($pk); - } - - return true; - } + /** + * Category item data + * + * @var CategoryNode|null + */ + protected $_item = null; + + /** + * Category left of this one + * + * @var CategoryNode|null + */ + protected $_leftsibling = null; + + /** + * Category right right of this one + * + * @var CategoryNode|null + */ + protected $_rightsibling = null; + + /** + * Array of child-categories + * + * @var CategoryNode[]|null + */ + protected $_children = null; + + /** + * Parent category of the current one + * + * @var CategoryNode|null + */ + protected $_parent = null; + + /** + * Constructor. + * + * @param array $config An optional associative array of configuration settings. + * + * @see JControllerLegacy + * @since 1.6 + */ + public function __construct($config = []) + { + if (empty($config['filter_fields'])) { + $config['filter_fields'] = [ + 'id', 'a.id', + 'title', 'a.title', + 'hits', 'a.hits', + 'ordering', 'a.ordering', + ]; + } + + parent::__construct($config); + } + + + /** + * Method to get a list of items. + * + * @return mixed An array of objects on success, false on failure. + */ + public function getItems() + { + // Invoke the parent getItems method to get the main list + $items = parent::getItems(); + + $taggedItems = []; + + // Convert the params field into an object, saving original in _params + foreach ($items as $item) { + if (!isset($this->_params)) { + $item->params = new Registry($item->params); + } + + // Some contexts may not use tags data at all, so we allow callers to disable loading tag data + if ($this->getState('load_tags', true)) { + $item->tags = new TagsHelper(); + $taggedItems[$item->id] = $item; + } + } + + // Load tags of all items. + if ($taggedItems) { + $tagsHelper = new TagsHelper(); + $itemIds = \array_keys($taggedItems); + + foreach ($tagsHelper->getMultipleItemTags('com_weblinks.weblink', $itemIds) as $id => $tags) { + $taggedItems[$id]->tags->itemTags = $tags; + } + } + + return $items; + } + + /** + * Method to get a JDatabaseQuery object for retrieving the data set from a database. + * + * @return \JDatabaseQuery A JDatabaseQuery object to retrieve the data set. + * + * @since 1.6 + */ + protected function getListQuery() + { + $viewLevels = $this->getCurrentUser()->getAuthorisedViewLevels(); + + // Create a new query object. + $db = $this->getDatabase(); + $query = $db->getQuery(true); + + // Select required fields from the categories. + $query->select($this->getState('list.select', 'a.*')) + ->from($db->quoteName('#__weblinks') . ' AS a') + ->whereIn($db->quoteName('a.access'), $viewLevels); + + // Filter by category. + if ($categoryId = $this->getState('category.id')) { + // Group by subcategory + if ($this->getState('category.group', 0)) { + $query->select('c.title AS category_title') + ->where('c.parent_id = :parent_id') + ->bind(':parent_id', $categoryId, ParameterType::INTEGER) + ->join('LEFT', '#__categories AS c ON c.id = a.catid') + ->whereIn($db->quoteName('c.access'), $viewLevels); + } else { + $query->where('a.catid = :catid') + ->bind(':catid', $categoryId, ParameterType::INTEGER) + ->join('LEFT', '#__categories AS c ON c.id = a.catid') + ->whereIn($db->quoteName('c.access'), $viewLevels); + } + + // Filter by published category + $cpublished = $this->getState('filter.c.published'); + + if (is_numeric($cpublished)) { + $query->where('c.published = :published') + ->bind(':published', $cpublished, ParameterType::INTEGER); + } + } + + // Join over the users for the author and modified_by names. + $query->select("CASE WHEN a.created_by_alias > ' ' THEN a.created_by_alias ELSE ua.name END AS author") + ->select("ua.email AS author_email") + ->join('LEFT', '#__users AS ua ON ua.id = a.created_by') + ->join('LEFT', '#__users AS uam ON uam.id = a.modified_by'); + + // Filter by state + $state = $this->getState('filter.state'); + + if (is_numeric($state)) { + $query->where('a.state = :state') + ->bind(':state', $state, ParameterType::INTEGER); + } + + // Do not show trashed links on the front-end + $query->where('a.state != -2'); + + // Filter by start and end dates. + if ($this->getState('filter.publish_date')) { + $nowDate = Factory::getDate()->toSql(); + $query->where('(' . $db->quoteName('a.publish_up') + . ' IS NULL OR ' . $db->quoteName('a.publish_up') . ' <= :publish_up)') + ->where('(' . $db->quoteName('a.publish_down') + . ' IS NULL OR ' . $db->quoteName('a.publish_down') . ' >= :publish_down)') + ->bind(':publish_up', $nowDate) + ->bind(':publish_down', $nowDate); + } + + // Filter by language + if ($this->getState('filter.language')) { + $query->whereIn($db->quoteName('a.language'), [Factory::getLanguage()->getTag(), '*'], ParameterType::STRING); + } + + // Filter by search in title + $search = $this->getState('list.filter'); + + if (!empty($search)) { + $search = '%' . trim($search) . '%'; + $query->where('(a.title LIKE :search)') + ->bind(':search', $search); + } + + // If grouping by subcategory, add the subcategory list ordering clause. + if ($this->getState('category.group', 0)) { + $query->order( + $db->escape($this->getState('category.ordering', 'c.lft')) . ' ' . + $db->escape($this->getState('category.direction', 'ASC')) + ); + } + + // Add the list ordering clause. + $query->order( + $db->escape($this->getState('list.ordering', 'a.ordering')) . ' ' . + $db->escape($this->getState('list.direction', 'ASC')) + ); + + return $query; + } + + /** + * Method to auto-populate the model state. + * + * Note. Calling getState in this method will result in recursion. + * + * @param string $ordering An optional ordering field. + * @param string $direction An optional direction (asc|desc). + * + * @return void + * + * @since 1.6 + */ + protected function populateState($ordering = null, $direction = null) + { + $app = Factory::getApplication(); + + $params = $app->getParams(); + $this->setState('params', $params); + + // List state information + $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->get('list_limit'), 'uint'); + $this->setState('list.limit', $limit); + + $limitstart = $app->input->get('limitstart', 0, 'uint'); + $this->setState('list.start', $limitstart); + + // Optional filter text + $this->setState('list.filter', $app->input->getString('filter-search')); + + $orderCol = $app->input->get('filter_order', 'ordering'); + + if (!in_array($orderCol, $this->filter_fields)) { + $orderCol = 'ordering'; + } + + $this->setState('list.ordering', $orderCol); + + $listOrder = $app->input->get('filter_order_Dir', 'ASC'); + + if (!in_array(strtoupper($listOrder), ['ASC', 'DESC', ''])) { + $listOrder = 'ASC'; + } + + $this->setState('list.direction', $listOrder); + + $id = $app->input->get('id', 0, 'int'); + $this->setState('category.id', $id); + + $user = $this->getCurrentUser(); + + if (!$user->authorise('core.edit.state', 'com_weblinks') && !$user->authorise('core.edit', 'com_weblinks')) { + // Limit to published for people who can't edit or edit.state. + $this->setState('filter.state', 1); + + // Filter by start and end dates. + $this->setState('filter.publish_date', true); + } + + $this->setState('filter.language', Multilanguage::isEnabled()); + } + + /** + * Method to get category data for the current category + * + * @return object + * + * @since 1.5 + */ + public function getCategory() + { + if (!is_object($this->_item)) { + $params = $this->getState('params', new Registry()); + + $options = []; + $options['countItems'] = $params->get('show_cat_num_links_cat', 1) + || $params->get('show_empty_categories', 0); + + $categories = Categories::getInstance('Weblinks', $options); + $this->_item = $categories->get($this->getState('category.id', 'root')); + + if (is_object($this->_item)) { + $this->_children = $this->_item->getChildren(); + $this->_parent = false; + + if ($this->_item->getParent()) { + $this->_parent = $this->_item->getParent(); + } + + $this->_rightsibling = $this->_item->getSibling(); + $this->_leftsibling = $this->_item->getSibling(false); + } else { + $this->_children = false; + $this->_parent = false; + } + } + + return $this->_item; + } + + /** + * Get the parent category + * + * @return mixed An array of categories or false if an error occurs. + */ + public function getParent() + { + if (!is_object($this->_item)) { + $this->getCategory(); + } + + return $this->_parent; + } + + /** + * Get the leftsibling (adjacent) categories. + * + * @return mixed An array of categories or false if an error occurs. + */ + public function &getLeftSibling() + { + if (!is_object($this->_item)) { + $this->getCategory(); + } + + return $this->_leftsibling; + } + + /** + * Get the rightsibling (adjacent) categories. + * + * @return mixed An array of categories or false if an error occurs. + */ + public function &getRightSibling() + { + if (!is_object($this->_item)) { + $this->getCategory(); + } + + return $this->_rightsibling; + } + + /** + * Get the child categories. + * + * @return mixed An array of categories or false if an error occurs. + */ + public function &getChildren() + { + if (!is_object($this->_item)) { + $this->getCategory(); + } + + return $this->_children; + } + + /** + * Increment the hit counter for the category. + * + * @param integer $pk Optional primary key of the category to increment. + * + * @return boolean True if successful; false otherwise and internal error set. + * + * @since 3.2 + */ + public function hit($pk = 0) + { + $hitcount = Factory::getApplication()->input->getInt('hitcount', 1); + + if ($hitcount) { + $pk = (!empty($pk)) ? $pk : (int) $this->getState('category.id'); + $table = Table::getInstance('Category', 'Joomla\\CMS\\Table\\'); + $table->load($pk); + $table->hit($pk); + } + + return true; + } } diff --git a/src/components/com_weblinks/src/Model/FormModel.php b/src/components/com_weblinks/src/Model/FormModel.php index 6de943e..c8e1778 100644 --- a/src/components/com_weblinks/src/Model/FormModel.php +++ b/src/components/com_weblinks/src/Model/FormModel.php @@ -1,4 +1,5 @@ getState('return_page', '')); - } + /** + * Get the return URL. + * + * @return string The return URL. + * + * @since 1.6 + */ + public function getReturnPage() + { + return base64_encode($this->getState('return_page', '')); + } - /** - * Method to auto-populate the model state. - * - * Note. Calling getState in this method will result in recursion. - * - * @return void - * - * @since 1.6 - */ - protected function populateState() - { - $app = Factory::getApplication(); + /** + * Method to auto-populate the model state. + * + * Note. Calling getState in this method will result in recursion. + * + * @return void + * + * @since 1.6 + */ + protected function populateState() + { + $app = Factory::getApplication(); - // Load state from the request. - $pk = $app->input->getInt('w_id'); - $this->setState('weblink.id', $pk); + // Load state from the request. + $pk = $app->input->getInt('w_id'); + $this->setState('weblink.id', $pk); - // Add compatibility variable for default naming conventions. - $this->setState('form.id', $pk); + // Add compatibility variable for default naming conventions. + $this->setState('form.id', $pk); - $categoryId = $app->input->getInt('catid'); - $this->setState('weblink.catid', $categoryId); + $categoryId = $app->input->getInt('catid'); + $this->setState('weblink.catid', $categoryId); - $return = $app->input->get('return', '', 'base64'); + $return = $app->input->get('return', '', 'base64'); - if ($return && !Uri::isInternal(base64_decode($return))) - { - $return = ''; - } + if ($return && !Uri::isInternal(base64_decode($return))) { + $return = ''; + } - $this->setState('return_page', base64_decode($return)); + $this->setState('return_page', base64_decode($return)); - // Load the parameters. - $params = $app->getParams(); - $this->setState('params', $params); + // Load the parameters. + $params = $app->getParams(); + $this->setState('params', $params); - $this->setState('layout', $app->input->getString('layout')); - } + $this->setState('layout', $app->input->getString('layout')); + } - /** - * Abstract method for getting the form from the model. - * - * @param array $data Data for the form. - * @param boolean $loadData True if the form is to load its own data (default case), false if not. - * - * @return mixed A JForm object on success, false on failure - * - * @since __DEPLOY_VERSION__ - */ - public function getForm($data = array(), $loadData = true) - { - $form = $this->loadForm('com_weblinks.form', 'weblink', array('control' => 'jform', 'load_data' => $loadData)); + /** + * Abstract method for getting the form from the model. + * + * @param array $data Data for the form. + * @param boolean $loadData True if the form is to load its own data (default case), false if not. + * + * @return mixed A JForm object on success, false on failure + * + * @since __DEPLOY_VERSION__ + */ + public function getForm($data = [], $loadData = true) + { + $form = $this->loadForm('com_weblinks.form', 'weblink', ['control' => 'jform', 'load_data' => $loadData]); - // Disable the buttons and just allow editor none for not authenticated users - if ($this->getCurrentUser()->guest) - { - $form->setFieldAttribute('description', 'editor', 'none'); - $form->setFieldAttribute('description', 'buttons', 'no'); - } + // Disable the buttons and just allow editor none for not authenticated users + if ($this->getCurrentUser()->guest) { + $form->setFieldAttribute('description', 'editor', 'none'); + $form->setFieldAttribute('description', 'buttons', 'no'); + } - return $form; - } + return $form; + } - /** - * Method to get a table object, load it if necessary. - * - * @param string $name The table name. Optional. - * @param string $prefix The class prefix. Optional. - * @param array $options Configuration array for model. Optional. - * - * @return Table A Table object - * - * @since 4.0.0 - * @throws \Exception - */ - public function getTable($name = 'Weblink', $prefix = 'Administrator', $options = array()) - { - return parent::getTable($name, $prefix, $options); - } + /** + * Method to get a table object, load it if necessary. + * + * @param string $name The table name. Optional. + * @param string $prefix The class prefix. Optional. + * @param array $options Configuration array for model. Optional. + * + * @return Table A Table object + * + * @since 4.0.0 + * @throws \Exception + */ + public function getTable($name = 'Weblink', $prefix = 'Administrator', $options = []) + { + return parent::getTable($name, $prefix, $options); + } } diff --git a/src/components/com_weblinks/src/Model/WeblinkModel.php b/src/components/com_weblinks/src/Model/WeblinkModel.php index 959cb5d..82a0733 100644 --- a/src/components/com_weblinks/src/Model/WeblinkModel.php +++ b/src/components/com_weblinks/src/Model/WeblinkModel.php @@ -1,4 +1,5 @@ input->getInt('id'); - $this->setState('weblink.id', $pk); + // Load the object state. + $pk = $app->input->getInt('id'); + $this->setState('weblink.id', $pk); - // Load the parameters. - $params = $app->getParams(); - $this->setState('params', $params); + // Load the parameters. + $params = $app->getParams(); + $this->setState('params', $params); - $user = $this->getCurrentUser(); + $user = $this->getCurrentUser(); - if (!$user->authorise('core.edit.state', 'com_weblinks') && !$user->authorise('core.edit', 'com_weblinks')) - { - $this->setState('filter.published', 1); - $this->setState('filter.archived', 2); - } + if (!$user->authorise('core.edit.state', 'com_weblinks') && !$user->authorise('core.edit', 'com_weblinks')) { + $this->setState('filter.published', 1); + $this->setState('filter.archived', 2); + } - $this->setState('filter.language', Multilanguage::isEnabled()); - } + $this->setState('filter.language', Multilanguage::isEnabled()); + } - /** - * Method to get an object. - * - * @param integer $pk The id of the object to get. - * - * @return mixed Object on success, false on failure. - */ - public function getItem($pk = null) - { - $user = $this->getCurrentUser(); + /** + * Method to get an object. + * + * @param integer $pk The id of the object to get. + * + * @return mixed Object on success, false on failure. + */ + public function getItem($pk = null) + { + $user = $this->getCurrentUser(); - $pk = (!empty($pk)) ? $pk : (int) $this->getState('weblink.id'); + $pk = (!empty($pk)) ? $pk : (int) $this->getState('weblink.id'); - if ($this->_item === null) - { - $this->_item = array(); - } + if ($this->_item === null) { + $this->_item = []; + } - if (!isset($this->_item[$pk])) - { - try - { - $db = $this->getDatabase(); - $query = $db->getQuery(true) - ->select($this->getState('item.select', 'a.*')) - ->from('#__weblinks AS a') - ->where($db->quoteName('a.id') . ' = :id') - ->bind(':id', $pk, ParameterType::INTEGER); + if (!isset($this->_item[$pk])) { + try { + $db = $this->getDatabase(); + $query = $db->getQuery(true) + ->select($this->getState('item.select', 'a.*')) + ->from('#__weblinks AS a') + ->where($db->quoteName('a.id') . ' = :id') + ->bind(':id', $pk, ParameterType::INTEGER); - // Join on category table. - $query->select('c.title AS category_title, c.alias AS category_alias, c.access AS category_access') - ->innerJoin('#__categories AS c on c.id = a.catid') - ->where('c.published > 0'); + // Join on category table. + $query->select('c.title AS category_title, c.alias AS category_alias, c.access AS category_access') + ->innerJoin('#__categories AS c on c.id = a.catid') + ->where('c.published > 0'); - // Join on user table. - $query->select('u.name AS author') - ->join('LEFT', '#__users AS u on u.id = a.created_by'); + // Join on user table. + $query->select('u.name AS author') + ->join('LEFT', '#__users AS u on u.id = a.created_by'); - // Filter by language - if ($this->getState('filter.language')) - { - $query->whereIn($db->quoteName('a.language'), [Factory::getLanguage()->getTag(), '*'], ParameterType::STRING); - } + // Filter by language + if ($this->getState('filter.language')) { + $query->whereIn($db->quoteName('a.language'), [Factory::getLanguage()->getTag(), '*'], ParameterType::STRING); + } - // Join over the categories to get parent category titles - $query->select('parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias') - ->join('LEFT', '#__categories as parent ON parent.id = c.parent_id'); + // Join over the categories to get parent category titles + $query->select('parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias') + ->join('LEFT', '#__categories as parent ON parent.id = c.parent_id'); - if (!$user->authorise('core.edit.state', 'com_weblinks') && !$user->authorise('core.edit', 'com_weblinks')) - { - // Filter by start and end dates. - $nowDate = Factory::getDate()->toSql(); - $query->where('(' . $db->quoteName('a.publish_up') - . ' IS NULL OR ' . $db->quoteName('a.publish_up') . ' <= :publish_up)' - ) - ->where('(' . $db->quoteName('a.publish_down') - . ' IS NULL OR ' . $db->quoteName('a.publish_down') . ' >= :publish_down)' - ) - ->bind(':publish_up', $nowDate) - ->bind(':publish_down', $nowDate); - } + if (!$user->authorise('core.edit.state', 'com_weblinks') && !$user->authorise('core.edit', 'com_weblinks')) { + // Filter by start and end dates. + $nowDate = Factory::getDate()->toSql(); + $query->where('(' . $db->quoteName('a.publish_up') + . ' IS NULL OR ' . $db->quoteName('a.publish_up') . ' <= :publish_up)') + ->where('(' . $db->quoteName('a.publish_down') + . ' IS NULL OR ' . $db->quoteName('a.publish_down') . ' >= :publish_down)') + ->bind(':publish_up', $nowDate) + ->bind(':publish_down', $nowDate); + } - // Filter by published state. - $published = $this->getState('filter.published'); - $archived = $this->getState('filter.archived'); + // Filter by published state. + $published = $this->getState('filter.published'); + $archived = $this->getState('filter.archived'); - if (is_numeric($published)) - { - $query->whereIn($db->quoteName('a.state'), [$published, $archived]); - } + if (is_numeric($published)) { + $query->whereIn($db->quoteName('a.state'), [$published, $archived]); + } - $db->setQuery($query); + $db->setQuery($query); - $data = $db->loadObject(); + $data = $db->loadObject(); - if (empty($data)) - { - throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_NOT_FOUND'), 404); - } + if (empty($data)) { + throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_NOT_FOUND'), 404); + } - // Check for published state if filter set. - if ((is_numeric($published) || is_numeric($archived)) && (($data->state != $published) && ($data->state != $archived))) - { - throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_NOT_FOUND'), 404); - } + // Check for published state if filter set. + if ((is_numeric($published) || is_numeric($archived)) && (($data->state != $published) && ($data->state != $archived))) { + throw new \Exception(Text::_('COM_WEBLINKS_ERROR_WEBLINK_NOT_FOUND'), 404); + } - // Convert parameter fields to objects. - $data->params = new Registry($data->params); - $data->metadata = new Registry($data->metadata); + // Convert parameter fields to objects. + $data->params = new Registry($data->params); + $data->metadata = new Registry($data->metadata); - // Some contexts may not use tags data at all, so we allow callers to disable loading tag data - if ($this->getState('load_tags', true)) - { - $data->tags = new TagsHelper; - $data->tags->getItemTags('com_weblinks.weblink', $data->id); - } + // Some contexts may not use tags data at all, so we allow callers to disable loading tag data + if ($this->getState('load_tags', true)) { + $data->tags = new TagsHelper(); + $data->tags->getItemTags('com_weblinks.weblink', $data->id); + } - // Compute access permissions. - if ($access = $this->getState('filter.access')) - { - // If the access filter has been set, we already know this user can view. - $data->params->set('access-view', true); - } - else - { - // If no access filter is set, the layout takes some responsibility for display of limited information. - $groups = $user->getAuthorisedViewLevels(); - $data->params->set('access-view', in_array($data->access, $groups) && in_array($data->category_access, $groups)); - } + // Compute access permissions. + if ($access = $this->getState('filter.access')) { + // If the access filter has been set, we already know this user can view. + $data->params->set('access-view', true); + } else { + // If no access filter is set, the layout takes some responsibility for display of limited information. + $groups = $user->getAuthorisedViewLevels(); + $data->params->set('access-view', in_array($data->access, $groups) && in_array($data->category_access, $groups)); + } - $this->_item[$pk] = $data; - } - catch (\Exception $e) - { - $this->setError($e); - $this->_item[$pk] = false; - } - } + $this->_item[$pk] = $data; + } catch (\Exception $e) { + $this->setError($e); + $this->_item[$pk] = false; + } + } - return $this->_item[$pk]; - } + return $this->_item[$pk]; + } - /** - * Returns a reference to the a Table object, always creating it. - * - * @param string $type The table type to instantiate - * @param string $prefix A prefix for the table class name. Optional. - * @param array $config Configuration array for model. Optional. - * - * @return Table A database object - * - * @since 1.6 - */ - public function getTable($type = 'Weblink', $prefix = 'Administrator', $config = array()) - { - return parent::getTable($type, $prefix, $config); - } + /** + * Returns a reference to the a Table object, always creating it. + * + * @param string $type The table type to instantiate + * @param string $prefix A prefix for the table class name. Optional. + * @param array $config Configuration array for model. Optional. + * + * @return Table A database object + * + * @since 1.6 + */ + public function getTable($type = 'Weblink', $prefix = 'Administrator', $config = []) + { + return parent::getTable($type, $prefix, $config); + } - /** - * Method to increment the hit counter for the weblink - * - * @param integer $pk Optional ID of the weblink. - * - * @return boolean True on success - */ - public function hit($pk = null) - { - if (empty($pk)) - { - $pk = $this->getState('weblink.id'); - } + /** + * Method to increment the hit counter for the weblink + * + * @param integer $pk Optional ID of the weblink. + * + * @return boolean True on success + */ + public function hit($pk = null) + { + if (empty($pk)) { + $pk = $this->getState('weblink.id'); + } - return $this->getTable('Weblink')->hit($pk); - } + return $this->getTable('Weblink')->hit($pk); + } } diff --git a/src/components/com_weblinks/src/Service/Category.php b/src/components/com_weblinks/src/Service/Category.php index 1c8f1c3..ba82752 100644 --- a/src/components/com_weblinks/src/Service/Category.php +++ b/src/components/com_weblinks/src/Service/Category.php @@ -1,4 +1,5 @@ categoryFactory = $categoryFactory; + $this->db = $db; + $params = ComponentHelper::getParams('com_weblinks'); + $this->noIDs = (bool) $params->get('sef_ids'); + $categories = new RouterViewConfiguration('categories'); + $categories->setKey('id'); + $this->registerView($categories); + $category = new RouterViewConfiguration('category'); + $category->setKey('id')->setParent($categories, 'catid')->setNestable(); + $this->registerView($category); + $webLink = new RouterViewConfiguration('weblink'); + $webLink->setKey('id')->setParent($category, 'catid'); + $this->registerView($webLink); + $form = new RouterViewConfiguration('form'); + $form->setKey('w_id'); + $this->registerView($form); + parent::__construct($app, $menu); + $this->attachRule(new MenuRules($this)); + $this->attachRule(new StandardRules($this)); + $this->attachRule(new NomenuRules($this)); + } - /** - * The category factory - * - * @var CategoryFactoryInterface - * - * @since 4.0.0 - */ - private $categoryFactory; + /** + * Method to get the segment(s) for a category + * + * @param string $id ID of the category to retrieve the segments for + * @param array $query The request that is built right now + * + * @return array|string The segments of this item + */ + public function getCategorySegment($id, $query) + { + $category = $this->getCategories()->get($id); + if ($category) { + $path = array_reverse($category->getPath(), true); + $path[0] = '1:root'; + if ($this->noIDs) { + foreach ($path as &$segment) { + list($id, $segment) = explode(':', $segment, 2); + } + } - /** - * The category cache - * - * @var array - * - * @since 4.0.0 - */ - private $categoryCache = []; + return $path; + } - /** - * The db - * - * @var DatabaseInterface - * - * @since 4.0.0 - */ - private $db; + return []; + } - /** - * Weblinks Component router constructor - * - * @param SiteApplication $app The application object - * @param AbstractMenu $menu The menu object to work with - * @param CategoryFactoryInterface $categoryFactory The category object - * @param DatabaseInterface $db The database object - */ - public function __construct(SiteApplication $app, AbstractMenu $menu, CategoryFactoryInterface $categoryFactory, DatabaseInterface $db) - { - $this->categoryFactory = $categoryFactory; - $this->db = $db; + /** + * Method to get the segment(s) for a category + * + * @param string $id ID of the category to retrieve the segments for + * @param array $query The request that is built right now + * + * @return array|string The segments of this item + */ + public function getCategoriesSegment($id, $query) + { + return $this->getCategorySegment($id, $query); + } - $params = ComponentHelper::getParams('com_weblinks'); - $this->noIDs = (bool) $params->get('sef_ids'); - $categories = new RouterViewConfiguration('categories'); - $categories->setKey('id'); - $this->registerView($categories); - $category = new RouterViewConfiguration('category'); - $category->setKey('id')->setParent($categories, 'catid')->setNestable(); - $this->registerView($category); - $webLink = new RouterViewConfiguration('weblink'); - $webLink->setKey('id')->setParent($category, 'catid'); - $this->registerView($webLink); - $form = new RouterViewConfiguration('form'); - $form->setKey('w_id'); - $this->registerView($form); + /** + * Method to get the segment(s) for a weblink + * + * @param string $id ID of the weblink to retrieve the segments for + * @param array $query The request that is built right now + * + * @return array|string The segments of this item + */ + public function getWeblinkSegment($id, $query) + { + if (!strpos($id, ':')) { + $id = (int) $id; + $dbquery = $this->db->getQuery(true); + $dbquery->select($this->db->quoteName('alias')) + ->from($this->db->quoteName('#__weblinks')) + ->where($this->db->quoteName('id') . ' = :id') + ->bind(':id', $id, ParameterType::INTEGER); + $this->db->setQuery($dbquery); + $id .= ':' . $this->db->loadResult(); + } - parent::__construct($app, $menu); + if ($this->noIDs) { + list($void, $segment) = explode(':', $id, 2); + return [$void => $segment]; + } - $this->attachRule(new MenuRules($this)); - $this->attachRule(new StandardRules($this)); - $this->attachRule(new NomenuRules($this)); - } + return [(int) $id => $id]; + } - /** - * Method to get the segment(s) for a category - * - * @param string $id ID of the category to retrieve the segments for - * @param array $query The request that is built right now - * - * @return array|string The segments of this item - */ - public function getCategorySegment($id, $query) - { - $category = $this->getCategories()->get($id); + /** + * Method to get the segment(s) for a form + * + * @param string $id ID of the weblink form to retrieve the segments for + * @param array $query The request that is built right now + * + * @return array|string The segments of this item + * + * @since 4.0.0 + */ + public function getFormSegment($id, $query) + { + return $this->getWeblinkSegment($id, $query); + } - if ($category) - { - $path = array_reverse($category->getPath(), true); - $path[0] = '1:root'; + /** + * Method to get the id for a category + * + * @param string $segment Segment to retrieve the ID for + * @param array $query The request that is parsed right now + * + * @return mixed The id of this item or false + */ + public function getCategoryId($segment, $query) + { + if (isset($query['id'])) { + $category = $this->getCategories(['access' => false])->get($query['id']); + if ($category) { + foreach ($category->getChildren() as $child) { + if ($this->noIDs) { + if ($child->alias == $segment) { + return $child->id; + } + } else { + if ($child->id == (int) $segment) { + return $child->id; + } + } + } + } + } - if ($this->noIDs) - { - foreach ($path as &$segment) - { - list($id, $segment) = explode(':', $segment, 2); - } - } + return false; + } - return $path; - } + /** + * Method to get the segment(s) for a category + * + * @param string $segment Segment to retrieve the ID for + * @param array $query The request that is parsed right now + * + * @return mixed The id of this item or false + */ + public function getCategoriesId($segment, $query) + { + return $this->getCategoryId($segment, $query); + } - return array(); - } + /** + * Method to get the segment(s) for a weblink + * + * @param string $segment Segment of the weblink to retrieve the ID for + * @param array $query The request that is parsed right now + * + * @return mixed The id of this item or false + */ + public function getWeblinkId($segment, $query) + { + if ($this->noIDs) { + $dbquery = $this->db->getQuery(true); + $dbquery->select($this->db->quoteName('id')) + ->from($this->db->quoteName('#__weblinks')) + ->where([ + $this->db->quoteName('alias') . ' = :alias', + $this->db->quoteName('catid') . ' = :catid', + ]) + ->bind(':alias', $segment) + ->bind(':catid', $query['id'], ParameterType::INTEGER); + $this->db->setQuery($dbquery); + return (int) $this->db->loadResult(); + } - /** - * Method to get the segment(s) for a category - * - * @param string $id ID of the category to retrieve the segments for - * @param array $query The request that is built right now - * - * @return array|string The segments of this item - */ - public function getCategoriesSegment($id, $query) - { - return $this->getCategorySegment($id, $query); - } + return (int) $segment; + } - /** - * Method to get the segment(s) for a weblink - * - * @param string $id ID of the weblink to retrieve the segments for - * @param array $query The request that is built right now - * - * @return array|string The segments of this item - */ - public function getWeblinkSegment($id, $query) - { - if (!strpos($id, ':')) - { - $id = (int) $id; - $dbquery = $this->db->getQuery(true); - $dbquery->select($this->db->quoteName('alias')) - ->from($this->db->quoteName('#__weblinks')) - ->where($this->db->quoteName('id') . ' = :id') - ->bind(':id', $id, ParameterType::INTEGER); - $this->db->setQuery($dbquery); + /** + * Method to get categories from cache + * + * @param array $options The options for retrieving categories + * + * @return CategoryInterface The object containing categories + * + * @since 4.0.0 + */ + private function getCategories(array $options = []): CategoryInterface + { + $key = serialize($options); + if (!isset($this->categoryCache[$key])) { + $this->categoryCache[$key] = $this->categoryFactory->createCategory($options); + } - $id .= ':' . $this->db->loadResult(); - } - - if ($this->noIDs) - { - list($void, $segment) = explode(':', $id, 2); - - return array($void => $segment); - } - - return array((int) $id => $id); - } - - /** - * Method to get the segment(s) for a form - * - * @param string $id ID of the weblink form to retrieve the segments for - * @param array $query The request that is built right now - * - * @return array|string The segments of this item - * - * @since 4.0.0 - */ - public function getFormSegment($id, $query) - { - return $this->getWeblinkSegment($id, $query); - } - - /** - * Method to get the id for a category - * - * @param string $segment Segment to retrieve the ID for - * @param array $query The request that is parsed right now - * - * @return mixed The id of this item or false - */ - public function getCategoryId($segment, $query) - { - if (isset($query['id'])) - { - $category = $this->getCategories(['access' => false])->get($query['id']); - - if ($category) - { - foreach ($category->getChildren() as $child) - { - if ($this->noIDs) - { - if ($child->alias == $segment) - { - return $child->id; - } - } - else - { - if ($child->id == (int) $segment) - { - return $child->id; - } - } - } - } - } - - return false; - } - - /** - * Method to get the segment(s) for a category - * - * @param string $segment Segment to retrieve the ID for - * @param array $query The request that is parsed right now - * - * @return mixed The id of this item or false - */ - public function getCategoriesId($segment, $query) - { - return $this->getCategoryId($segment, $query); - } - - /** - * Method to get the segment(s) for a weblink - * - * @param string $segment Segment of the weblink to retrieve the ID for - * @param array $query The request that is parsed right now - * - * @return mixed The id of this item or false - */ - public function getWeblinkId($segment, $query) - { - if ($this->noIDs) - { - $dbquery = $this->db->getQuery(true); - $dbquery->select($this->db->quoteName('id')) - ->from($this->db->quoteName('#__weblinks')) - ->where( - [ - $this->db->quoteName('alias') . ' = :alias', - $this->db->quoteName('catid') . ' = :catid', - ] - ) - ->bind(':alias', $segment) - ->bind(':catid', $query['id'], ParameterType::INTEGER); - $this->db->setQuery($dbquery); - - return (int) $this->db->loadResult(); - } - - return (int) $segment; - } - - /** - * Method to get categories from cache - * - * @param array $options The options for retrieving categories - * - * @return CategoryInterface The object containing categories - * - * @since 4.0.0 - */ - private function getCategories(array $options = []): CategoryInterface - { - $key = serialize($options); - - if (!isset($this->categoryCache[$key])) - { - $this->categoryCache[$key] = $this->categoryFactory->createCategory($options); - } - - return $this->categoryCache[$key]; - } + return $this->categoryCache[$key]; + } } diff --git a/src/components/com_weblinks/src/View/Categories/HtmlView.php b/src/components/com_weblinks/src/View/Categories/HtmlView.php index 8e30794..0e1e0dc 100644 --- a/src/components/com_weblinks/src/View/Categories/HtmlView.php +++ b/src/components/com_weblinks/src/View/Categories/HtmlView.php @@ -1,4 +1,5 @@ items as $item) { + $item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id; + $temp = $item->params; + $item->params = clone $this->params; + $item->params->merge($temp); + if ($item->params->get('count_clicks', 1) == 1) { + $item->link = Route::_('index.php?option=com_weblinks&task=weblink.go&id=' . $item->id); + } else { + $item->link = $item->url; + } + } - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise a Error object. - */ - public function display($tpl = null) - { - parent::commonCategoryDisplay(); + return parent::display($tpl); + } - // Prepare the data. - // Compute the weblink slug & link url. - foreach ($this->items as $item) - { - $item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id; - $temp = $item->params; - $item->params = clone $this->params; - $item->params->merge($temp); + /** + * Prepares the document + * + * @return void + */ + protected function prepareDocument() + { + parent::prepareDocument(); + parent::addFeed(); + if ($this->menuItemMatchCategory) { + // If the active menu item is linked directly to the category being displayed, no further process is needed + return; + } - if ($item->params->get('count_clicks', 1) == 1) - { - $item->link = Route::_('index.php?option=com_weblinks&task=weblink.go&id=' . $item->id); - } - else - { - $item->link = $item->url; - } - } + // Get ID of the category from active menu item + $menu = $this->menu; - return parent::display($tpl); - } + if ( + $menu && $menu->component == 'com_weblinks' && isset($menu->query['view']) + && in_array($menu->query['view'], ['categories', 'category']) + ) { + $id = $menu->query['id']; + } else { + $id = 0; + } - /** - * Prepares the document - * - * @return void - */ - protected function prepareDocument() - { - parent::prepareDocument(); + $path = [['title' => $this->category->title, 'link' => '']]; + $category = $this->category->getParent(); + while ($category !== null && $category->id != $id && $category->id !== 'root') { + $path[] = ['title' => $category->title, 'link' => RouteHelper::getCategoryRoute($category->id, $category->language)]; + $category = $category->getParent(); + } - parent::addFeed(); - - if ($this->menuItemMatchCategory) - { - // If the active menu item is linked directly to the category being displayed, no further process is needed - return; - } - - // Get ID of the category from active menu item - $menu = $this->menu; - - if ($menu && $menu->component == 'com_weblinks' && isset($menu->query['view']) - && in_array($menu->query['view'], ['categories', 'category'])) - { - $id = $menu->query['id']; - } - else - { - $id = 0; - } - - $path = [['title' => $this->category->title, 'link' => '']]; - $category = $this->category->getParent(); - - while ($category !== null && $category->id != $id && $category->id !== 'root') - { - $path[] = ['title' => $category->title, 'link' => RouteHelper::getCategoryRoute($category->id, $category->language)]; - $category = $category->getParent(); - } - - $path = array_reverse($path); - - foreach ($path as $item) - { - $this->pathway->addItem($item['title'], $item['link']); - } - } + $path = array_reverse($path); + foreach ($path as $item) { + $this->pathway->addItem($item['title'], $item['link']); + } + } } diff --git a/src/components/com_weblinks/src/View/Form/HtmlView.php b/src/components/com_weblinks/src/View/Form/HtmlView.php index 00348d1..dfa26f7 100644 --- a/src/components/com_weblinks/src/View/Form/HtmlView.php +++ b/src/components/com_weblinks/src/View/Form/HtmlView.php @@ -1,4 +1,5 @@ getCurrentUser(); + /** + * Display the view. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise an Error object. + */ + public function display($tpl = null) + { + $user = $this->getCurrentUser(); - // Get model data. - $this->state = $this->get('State'); - $this->item = $this->get('Item'); - $this->form = $this->get('Form'); - $this->return_page = $this->get('ReturnPage'); + // Get model data. + $this->state = $this->get('State'); + $this->item = $this->get('Item'); + $this->form = $this->get('Form'); + $this->return_page = $this->get('ReturnPage'); - if (empty($this->item->id)) - { - $authorised = $user->authorise('core.create', 'com_weblinks') || count($user->getAuthorisedCategories('com_weblinks', 'core.create')); - } - else - { - $authorised = $user->authorise('core.edit', 'com_weblinks.category.' . $this->item->catid); - } + if (empty($this->item->id)) { + $authorised = $user->authorise('core.create', 'com_weblinks') || count($user->getAuthorisedCategories('com_weblinks', 'core.create')); + } else { + $authorised = $user->authorise('core.edit', 'com_weblinks.category.' . $this->item->catid); + } - if ($authorised !== true) - { - throw new \Exception(Text::_('JERROR_ALERTNOAUTHOR'), 403); - } + if ($authorised !== true) { + throw new \Exception(Text::_('JERROR_ALERTNOAUTHOR'), 403); + } - if (!empty($this->item)) - { - // Override the base weblink data with any data in the session. - $temp = (array) Factory::getApplication()->getUserState('com_weblinks.edit.weblink.data', array()); + if (!empty($this->item)) { + // Override the base weblink data with any data in the session. + $temp = (array) Factory::getApplication()->getUserState('com_weblinks.edit.weblink.data', []); - foreach ($temp as $k => $v) - { - $this->item->$k = $v; - } + foreach ($temp as $k => $v) { + $this->item->$k = $v; + } - $this->form->bind($this->item); - } + $this->form->bind($this->item); + } - // Check for errors. - if (count($errors = $this->get('Errors'))) - { - throw new GenericDataException(implode("\n", $errors), 500); - } + // Check for errors. + if (count($errors = $this->get('Errors'))) { + throw new GenericDataException(implode("\n", $errors), 500); + } - // Create a shortcut to the parameters. - $params = &$this->state->params; + // Create a shortcut to the parameters. + $params = &$this->state->params; - // Escape strings for HTML output - $this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx', '')); + // Escape strings for HTML output + $this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx', '')); - $this->params = $params; - $this->user = $user; + $this->params = $params; + $this->user = $user; - $this->_prepareDocument(); + $this->prepareDocument(); - parent::display($tpl); - } + parent::display($tpl); + } - /** - * Prepares the document - * - * @return void - */ - protected function _prepareDocument() - { - $app = Factory::getApplication(); + /** + * Prepares the document + * + * @return void + */ + protected function prepareDocument() + { + $app = Factory::getApplication(); - // Because the application sets a default page title, - // we need to get it from the menu item itself - $menu = $app->getMenu()->getActive(); + // Because the application sets a default page title, + // we need to get it from the menu item itself + $menu = $app->getMenu()->getActive(); - if (empty($this->item->id)) - { - $head = Text::_('COM_WEBLINKS_FORM_SUBMIT_WEBLINK'); - } - else - { - $head = Text::_('COM_WEBLINKS_FORM_EDIT_WEBLINK'); - } + if (empty($this->item->id)) { + $head = Text::_('COM_WEBLINKS_FORM_SUBMIT_WEBLINK'); + } else { + $head = Text::_('COM_WEBLINKS_FORM_EDIT_WEBLINK'); + } - if ($menu) - { - $this->params->def('page_heading', $this->params->get('page_title', $menu->title)); - } - else - { - $this->params->def('page_heading', $head); - } + if ($menu) { + $this->params->def('page_heading', $this->params->get('page_title', $menu->title)); + } else { + $this->params->def('page_heading', $head); + } - $title = $this->params->def('page_title', $head); + $title = $this->params->def('page_title', $head); - $this->setDocumentTitle($title); + $this->setDocumentTitle($title); - if ($this->params->get('menu-meta_description')) - { - $this->document->setDescription($this->params->get('menu-meta_description')); - } + if ($this->params->get('menu-meta_description')) { + $this->document->setDescription($this->params->get('menu-meta_description')); + } - if ($this->params->get('menu-meta_keywords')) - { - $this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords')); - } + if ($this->params->get('menu-meta_keywords')) { + $this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords')); + } - if ($this->params->get('robots')) - { - $this->document->setMetadata('robots', $this->params->get('robots')); - } - } + if ($this->params->get('robots')) { + $this->document->setMetadata('robots', $this->params->get('robots')); + } + } } diff --git a/src/components/com_weblinks/src/View/Weblink/HtmlView.php b/src/components/com_weblinks/src/View/Weblink/HtmlView.php index 3a05ff3..c69e295 100644 --- a/src/components/com_weblinks/src/View/Weblink/HtmlView.php +++ b/src/components/com_weblinks/src/View/Weblink/HtmlView.php @@ -1,4 +1,5 @@ item = $this->get('Item'); - $this->state = $this->get('State'); - $this->params = $this->state->get('params'); - - // Create a shortcut for $item. - $item = $this->item; - - $item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id; - - $temp = $item->params; - $item->params = clone $app->getParams(); - $item->params->merge($temp); - - $offset = $this->state->get('list.offset'); - - $app->triggerEvent('onContentPrepare', array('com_weblinks.weblink', &$item, &$item->params, $offset)); - - $item->event = new \stdClass; - - $results = $app->triggerEvent('onContentAfterTitle', array('com_weblinks.weblink', &$item, &$item->params, $offset)); - $item->event->afterDisplayTitle = trim(implode("\n", $results)); - - $results = $app->triggerEvent('onContentBeforeDisplay', array('com_weblinks.weblink', &$item, &$item->params, $offset)); - $item->event->beforeDisplayContent = trim(implode("\n", $results)); - - $results = $app->triggerEvent('onContentAfterDisplay', array('com_weblinks.weblink', &$item, &$item->params, $offset)); - $item->event->afterDisplayContent = trim(implode("\n", $results)); - - parent::display($tpl); - } + /** + * The weblink object + * + * @var \JObject + */ + protected $item; + /** + * The page parameters + * + * @var \Joomla\Registry\Registry|null + */ + protected $params; + /** + * The item model state + * + * @var \Joomla\Registry\Registry + * @since 1.6 + */ + protected $state; + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise an Error object. + * + * @since __DEPLOY_VERSION__ + */ + public function display($tpl = null) + { + $app = Factory::getApplication(); + $this->item = $this->get('Item'); + $this->state = $this->get('State'); + $this->params = $this->state->get('params'); + // Create a shortcut for $item. + $item = $this->item; + $item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id; + $temp = $item->params; + $item->params = clone $app->getParams(); + $item->params->merge($temp); + $offset = $this->state->get('list.offset'); + $app->triggerEvent('onContentPrepare', ['com_weblinks.weblink', &$item, &$item->params, $offset]); + $item->event = new \stdClass(); + $results = $app->triggerEvent('onContentAfterTitle', ['com_weblinks.weblink', &$item, &$item->params, $offset]); + $item->event->afterDisplayTitle = trim(implode("\n", $results)); + $results = $app->triggerEvent('onContentBeforeDisplay', ['com_weblinks.weblink', &$item, &$item->params, $offset]); + $item->event->beforeDisplayContent = trim(implode("\n", $results)); + $results = $app->triggerEvent('onContentAfterDisplay', ['com_weblinks.weblink', &$item, &$item->params, $offset]); + $item->event->afterDisplayContent = trim(implode("\n", $results)); + parent::display($tpl); + } } diff --git a/src/components/com_weblinks/tmpl/categories/default.php b/src/components/com_weblinks/tmpl/categories/default.php index c7b77a1..2dc2f62 100644 --- a/src/components/com_weblinks/tmpl/categories/default.php +++ b/src/components/com_weblinks/tmpl/categories/default.php @@ -1,4 +1,5 @@ document->getWebAssetManager(); $wa->getRegistry()->addExtensionRegistryFile('com_categories'); @@ -23,8 +23,8 @@ $wa->usePreset('com_categories.shared-categories-accordion'); ?> diff --git a/src/components/com_weblinks/tmpl/categories/default_items.php b/src/components/com_weblinks/tmpl/categories/default_items.php index 200094d..22d52e9 100644 --- a/src/components/com_weblinks/tmpl/categories/default_items.php +++ b/src/components/com_weblinks/tmpl/categories/default_items.php @@ -1,4 +1,5 @@ maxLevelcat != 0 && count($this->items[$this->parent->id]) > 0) : -?> -
- items[$this->parent->id] as $id => $item) : ?> - params->get('show_empty_categories_cat') || $item->numitems || count($item->getChildren())) : ?> -
-
- - escape($item->title); ?> - params->get('show_cat_num_links_cat') == 1) :?> - -   - numitems; ?> - - - maxLevelcat > 1 && count($item->getChildren()) > 0) : ?> - - -
+ ?> +
+ items[$this->parent->id] as $id => $item) : + ?> + params->get('show_empty_categories_cat') || $item->numitems || count($item->getChildren())) : + ?> +
+
+ + escape($item->title); ?> + params->get('show_cat_num_links_cat') == 1) : + ?> + +   + numitems; ?> + + + maxLevelcat > 1 && count($item->getChildren()) > 0) : + ?> + + +
- params->get('show_subcat_desc_cat') == 1 && !empty($item->description)) : ?> -
- description, '', 'com_weblinks.categories'); ?> -
- + params->get('show_subcat_desc_cat') == 1 && !empty($item->description)) : + ?> +
+ description, '', 'com_weblinks.categories'); ?> +
+ - params->get('show_description_image') && !empty($item->getParams()->get('image'))) : ?> - getParams(); - $img = HTMLHelper::cleanImageURL($params->get('image')); - $alt = ''; - if (!empty($params->get('image_alt'))) : - $alt = 'alt="' . htmlspecialchars($params->get('image_alt'), ENT_COMPAT, 'UTF-8') . '"'; - elseif (!empty($params->get('image_alt_empty'))) : - $alt = 'alt=""'; - endif; - ?> - > - + params->get('show_description_image') && !empty($item->getParams()->get('image'))) : + ?> + getParams(); + $img = HTMLHelper::cleanImageURL($params->get('image')); + $alt = ''; + if (!empty($params->get('image_alt'))) : + $alt = 'alt="' . htmlspecialchars($params->get('image_alt'), ENT_COMPAT, 'UTF-8') . '"'; + elseif (!empty($params->get('image_alt_empty'))) : + $alt = 'alt=""'; + endif; + ?> + > + - maxLevelcat > 1 && count($item->getChildren()) > 0) : ?> - - -
- - -
- + maxLevelcat > 1 && count($item->getChildren()) > 0) : + ?> + + +
+ + +
+ diff --git a/src/components/com_weblinks/tmpl/category/default.php b/src/components/com_weblinks/tmpl/category/default.php index a5990da..3cc3746 100644 --- a/src/components/com_weblinks/tmpl/category/default.php +++ b/src/components/com_weblinks/tmpl/category/default.php @@ -1,4 +1,5 @@ \ No newline at end of file + subtemplatename = 'items'; + echo LayoutHelper::render('joomla.content.category_default', $this); + ?> + diff --git a/src/components/com_weblinks/tmpl/category/default_children.php b/src/components/com_weblinks/tmpl/category/default_children.php index b128610..cfde6a1 100644 --- a/src/components/com_weblinks/tmpl/category/default_children.php +++ b/src/components/com_weblinks/tmpl/category/default_children.php @@ -1,4 +1,5 @@ maxLevel != 0 && count($this->children[$this->category->id]) > 0) : -?> - - + getChildren()) > 0) : + $this->children[$child->id] = $child->getChildren(); + $this->category = $child; + $this->maxLevel--; + echo $this->loadTemplate('children'); + $this->category = $child->getParent(); + $this->maxLevel++; + endif; ?> + + + + + diff --git a/src/components/com_weblinks/tmpl/category/default_items.php b/src/components/com_weblinks/tmpl/category/default_items.php index 685dbba..38458d8 100644 --- a/src/components/com_weblinks/tmpl/category/default_items.php +++ b/src/components/com_weblinks/tmpl/category/default_items.php @@ -1,4 +1,5 @@ getIdentity(); - // Check if user is allowed to add/edit based on weblinks permission. $canEdit = $user->authorise('core.edit', 'com_weblinks.category.' . $this->category->id); $canEditOwn = $user->authorise('core.edit.own', 'com_weblinks.category.' . $this->category->id); $canCreate = $user->authorise('core.create', 'com_weblinks.category.' . $this->category->id); - $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); ?> + - params->get('show_pagination')) : ?> - - pagination->getPagesLinks(); ?> - - + + + - + params->get('show_pagination')) : + ?> + + + + + + + category, $this->category->params); ?> + + diff --git a/src/components/com_weblinks/tmpl/form/edit.php b/src/components/com_weblinks/tmpl/form/edit.php index 5170723..02fbb63 100644 --- a/src/components/com_weblinks/tmpl/form/edit.php +++ b/src/components/com_weblinks/tmpl/form/edit.php @@ -1,4 +1,5 @@ params->get('captcha', Factory::getApplication()->get('captcha', '0')); - -foreach (PluginHelper::getPlugin('captcha') as $plugin) -{ - if ($captchaSet === $plugin->name) - { - $captchaEnabled = true; - break; - } +foreach (PluginHelper::getPlugin('captcha') as $plugin) { + if ($captchaSet === $plugin->name) { + $captchaEnabled = true; + break; + } } // Create shortcut to parameters. $params = $this->state->get('params'); ?>
- params->get('show_page_heading')) : ?> - - -
+ params->get('show_page_heading')) : + ?> + + + - form->renderField('title'); ?> - form->renderField('alias'); ?> - form->renderField('catid'); ?> - form->renderField('url'); ?> - form->renderField('tags'); ?> + form->renderField('title'); ?> + form->renderField('alias'); ?> + form->renderField('catid'); ?> + form->renderField('url'); ?> + form->renderField('tags'); ?> - get('save_history', 0)) : ?> - form->renderField('version_note'); ?> - + get('save_history', 0)) : + ?> + form->renderField('version_note'); ?> + - user->authorise('core.edit.state', 'com_weblinks.weblink')) : ?> - form->renderField('state'); ?> - - form->renderField('language'); ?> - form->renderField('description'); ?> + user->authorise('core.edit.state', 'com_weblinks.weblink')) : + ?> + form->renderField('state'); ?> + + form->renderField('language'); ?> + form->renderField('description'); ?> - form->renderField('image_first', 'images'); ?> - form->renderField('image_first_alt', 'images'); ?> - form->renderField('image_first_alt_empty', 'images'); ?> - form->renderField('float_first', 'images'); ?> - form->renderField('image_first_caption', 'images'); ?> + form->renderField('image_first', 'images'); ?> + form->renderField('image_first_alt', 'images'); ?> + form->renderField('image_first_alt_empty', 'images'); ?> + form->renderField('float_first', 'images'); ?> + form->renderField('image_first_caption', 'images'); ?> - form->renderField('image_second', 'images'); ?> - form->renderField('image_second_alt', 'images'); ?> - form->renderField('image_second_alt_empty', 'images'); ?> - form->renderField('float_second', 'images'); ?> - form->renderField('image_second_caption', 'images'); ?> + form->renderField('image_second', 'images'); ?> + form->renderField('image_second_alt', 'images'); ?> + form->renderField('image_second_alt_empty', 'images'); ?> + form->renderField('float_second', 'images'); ?> + form->renderField('image_second_caption', 'images'); ?> - -
- form->renderField('captcha'); ?> -
- + +
+ form->renderField('captcha'); ?> +
+ -
- - - params->get('save_history', 0) && $this->item->id) : ?> - form->getInput('contenthistory'); ?> - -
+
+ + + params->get('save_history', 0) && $this->item->id) : + ?> + form->getInput('contenthistory'); ?> + +
- - - -
+ + + +
diff --git a/src/components/com_weblinks/tmpl/weblink/default.php b/src/components/com_weblinks/tmpl/weblink/default.php index ca40dc6..46eb7b9 100644 --- a/src/components/com_weblinks/tmpl/weblink/default.php +++ b/src/components/com_weblinks/tmpl/weblink/default.php @@ -1,4 +1,5 @@ item->url); $user = Factory::getApplication()->getIdentity(); - $canEdit = $user->authorise('core.edit', 'com_weblinks.category.' . $this->item->catid); - -if (!$canEdit) -{ - $canEditOwn = $user->authorise('core.edit.own', 'com_weblinks.category.' . $this->item->catid); - $canEdit = $canEditOwn && $this->item->created_by == $user->id; +if (!$canEdit) { + $canEditOwn = $user->authorise('core.edit.own', 'com_weblinks.category.' . $this->item->catid); + $canEdit = $canEditOwn && $this->item->created_by == $user->id; } ?>
- - - -
-
-
- item, $this->item->params); ?> -
-
-
- + + + +
+
+
+ item, $this->item->params); ?> +
+
+
+ - - item->event->afterDisplayTitle; ?> + + item->event->afterDisplayTitle; ?> - - item->event->beforeDisplayContent; ?> + + item->event->beforeDisplayContent; ?> -
-
- -
+
+
+ +
- params->get('show_tags', 1) && !empty($this->item->tags->itemTags)) : ?> -
- item->tags->itemTags); ?> -
- + params->get('show_tags', 1) && !empty($this->item->tags->itemTags)) : + ?> +
+ item->tags->itemTags); ?> +
+ -
- item->images); ?> - image_first)) : ?> - - float_first)) : ?> - float_first == 'right' ? 'float-end' : 'float-start'; ?> - - image_first); ?> - image_first_alt) && empty($images->image_first_alt_empty) - ? '' - : 'alt="' . htmlspecialchars($images->image_first_alt, ENT_COMPAT, 'UTF-8') . '"'; ?> -
- itemprop="thumbnail" /> - image_first_caption)) : ?> -
image_first_caption, ENT_COMPAT, 'UTF-8'); ?>
- -
- +
+ item->images); ?> + image_first)) : + ?> + + float_first)) : + ?> + float_first == 'right' ? 'float-end' : 'float-start'; ?> + + image_first); ?> + image_first_alt) && empty($images->image_first_alt_empty) + ? '' + : 'alt="' . htmlspecialchars($images->image_first_alt, ENT_COMPAT, 'UTF-8') . '"'; ?> +
+ itemprop="thumbnail" /> + image_first_caption)) : + ?> +
image_first_caption, ENT_COMPAT, 'UTF-8'); ?>
+ +
+ - image_second)) : ?> - - float_second)) : ?> - float_second == 'right' ? 'float-end' : 'float-start'; ?> - - image_second); ?> - image_second_alt) && empty($images->image_second_alt_empty) - ? '' - : 'alt="' . htmlspecialchars($images->image_second_alt, ENT_COMPAT, 'UTF-8') . '"'; ?> -
- itemprop="thumbnail" /> - image_second_caption)) : ?> -
image_second_caption, ENT_COMPAT, 'UTF-8'); ?>
- -
- + image_second)) : + ?> + + float_second)) : + ?> + float_second == 'right' ? 'float-end' : 'float-start'; ?> + + image_second); ?> + image_second_alt) && empty($images->image_second_alt_empty) + ? '' + : 'alt="' . htmlspecialchars($images->image_second_alt, ENT_COMPAT, 'UTF-8') . '"'; ?> +
+ itemprop="thumbnail" /> + image_second_caption)) : + ?> +
image_second_caption, ENT_COMPAT, 'UTF-8'); ?>
+ +
+ - item->description)) : ?> - item->description; ?> - + item->description)) : + ?> + item->description; ?> + -
+
-
- - item->event->afterDisplayContent; ?> +
+ + item->event->afterDisplayContent; ?>
diff --git a/src/modules/mod_weblinks/services/provider.php b/src/modules/mod_weblinks/services/provider.php index 75815ef..e663c2f 100644 --- a/src/modules/mod_weblinks/services/provider.php +++ b/src/modules/mod_weblinks/services/provider.php @@ -8,7 +8,9 @@ * @license GNU General Public License version 2 or later; see LICENSE.txt */ -defined('_JEXEC') or die; +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects use Joomla\CMS\Extension\Service\Provider\HelperFactory; use Joomla\CMS\Extension\Service\Provider\Module; @@ -22,20 +24,20 @@ use Joomla\DI\ServiceProviderInterface; * @since __DEPLOY_VERSION__ */ return new class () implements ServiceProviderInterface { - /** - * Registers the service provider with a DI container. - * - * @param Container $container The DI container. - * - * @return void - * - * @since __DEPLOY_VERSION__ - */ - public function register(Container $container) - { - $container->registerServiceProvider(new ModuleDispatcherFactory('\\Joomla\\Module\\Weblinks')); - $container->registerServiceProvider(new HelperFactory('\\Joomla\\Module\\Weblinks\\Site\\Helper')); + /** + * Registers the service provider with a DI container. + * + * @param Container $container The DI container. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function register(Container $container) + { + $container->registerServiceProvider(new ModuleDispatcherFactory('\\Joomla\\Module\\Weblinks')); + $container->registerServiceProvider(new HelperFactory('\\Joomla\\Module\\Weblinks\\Site\\Helper')); - $container->registerServiceProvider(new Module()); - } + $container->registerServiceProvider(new Module()); + } }; diff --git a/src/modules/mod_weblinks/src/Dispatcher/Dispatcher.php b/src/modules/mod_weblinks/src/Dispatcher/Dispatcher.php index 9df4bd2..55a1ec6 100644 --- a/src/modules/mod_weblinks/src/Dispatcher/Dispatcher.php +++ b/src/modules/mod_weblinks/src/Dispatcher/Dispatcher.php @@ -14,9 +14,11 @@ use Joomla\CMS\Dispatcher\AbstractModuleDispatcher; use Joomla\CMS\Helper\HelperFactoryAwareInterface; use Joomla\CMS\Helper\HelperFactoryAwareTrait; +// phpcs:disable PSR1.Files.SideEffects // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects +// phpcs:enable PSR1.Files.SideEffects /** * Dispatcher class for mod_weblinks @@ -25,26 +27,26 @@ use Joomla\CMS\Helper\HelperFactoryAwareTrait; */ class Dispatcher extends AbstractModuleDispatcher implements HelperFactoryAwareInterface { - use HelperFactoryAwareTrait; + use HelperFactoryAwareTrait; - /** - * Returns the layout data. - * - * @return array - * - * @since __DEPLOY_VERSION__ - */ - protected function getLayoutData() - { - $data = parent::getLayoutData(); + /** + * Returns the layout data. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + protected function getLayoutData() + { + $data = parent::getLayoutData(); - $data['list'] = $this->getHelperFactory()->getHelper('WeblinksHelper')->getWeblinks( - $data['params'], - $this->getApplication() - ); + $data['list'] = $this->getHelperFactory()->getHelper('WeblinksHelper')->getWeblinks( + $data['params'], + $this->getApplication() + ); - $data['moduleclass_sfx'] = htmlspecialchars($data['params']->get('moduleclass_sfx', '')); + $data['moduleclass_sfx'] = htmlspecialchars($data['params']->get('moduleclass_sfx', '')); - return $data; - } + return $data; + } } diff --git a/src/modules/mod_weblinks/src/Helper/WeblinksHelper.php b/src/modules/mod_weblinks/src/Helper/WeblinksHelper.php index c476ea9..9a1c773 100644 --- a/src/modules/mod_weblinks/src/Helper/WeblinksHelper.php +++ b/src/modules/mod_weblinks/src/Helper/WeblinksHelper.php @@ -1,4 +1,5 @@ bootComponent('com_weblinks')->getMVCFactory() - ->createModel('Category', 'Site', ['ignore_request' => true]); + /** + * Retrieve list of weblinks + * + * @param Registry $params The module parameters + * @param CMSApplicationInterface $app The application + * + * @return array Array containing all the weblinks. + * + * @since __DEPLOY_VERSION__ + **/ + public function getWeblinks($params, $app) + { + // @var \Joomla\Component\Weblinks\Site\Model\CategoryModel $model + $model = $app->bootComponent('com_weblinks')->getMVCFactory() + ->createModel('Category', 'Site', ['ignore_request' => true]); - // Set application parameters in model - $cParams = ComponentHelper::getParams('com_weblinks'); - $model->setState('params', $cParams); + // Set application parameters in model + $cParams = ComponentHelper::getParams('com_weblinks'); + $model->setState('params', $cParams); - // Set the filters based on the module params - $model->setState('list.start', 0); - $model->setState('list.limit', (int) $params->get('count', 5)); + // Set the filters based on the module params + $model->setState('list.start', 0); + $model->setState('list.limit', (int) $params->get('count', 5)); - $model->setState('filter.state', 1); - $model->setState('filter.publish_date', true); + $model->setState('filter.state', 1); + $model->setState('filter.publish_date', true); - // Access filter - $access = !ComponentHelper::getParams('com_weblinks')->get('show_noauth'); - $model->setState('filter.access', $access); + // Access filter + $access = !ComponentHelper::getParams('com_weblinks')->get('show_noauth'); + $model->setState('filter.access', $access); - $ordering = $params->get('ordering', 'ordering'); - $model->setState('list.ordering', $ordering == 'order' ? 'ordering' : $ordering); - $model->setState('list.direction', $params->get('direction', 'asc')); + $ordering = $params->get('ordering', 'ordering'); + $model->setState('list.ordering', $ordering == 'order' ? 'ordering' : $ordering); + $model->setState('list.direction', $params->get('direction', 'asc')); - $catid = (int) $params->get('catid', 0); - $model->setState('category.id', $catid); - $model->setState('category.group', $params->get('groupby', 0)); - $model->setState('category.ordering', $params->get('groupby_ordering', 'c.lft')); - $model->setState('category.direction', $params->get('groupby_direction', 'ASC')); + $catid = (int) $params->get('catid', 0); + $model->setState('category.id', $catid); + $model->setState('category.group', $params->get('groupby', 0)); + $model->setState('category.ordering', $params->get('groupby_ordering', 'c.lft')); + $model->setState('category.direction', $params->get('groupby_direction', 'ASC')); - // Create query object - $db = $model->getDbo(); - $query = $db->getQuery(true); + // Create query object + $db = $model->getDbo(); + $query = $db->getQuery(true); - $case_when1 = ' CASE WHEN '; - $case_when1 .= $query->charLength('a.alias', '!=', '0'); - $case_when1 .= ' THEN '; - $a_id = $query->castAs('CHAR', 'a.id'); - $case_when1 .= $query->concatenate([$a_id, 'a.alias'], ':'); - $case_when1 .= ' ELSE '; - $case_when1 .= $a_id . ' END as slug'; + $case_when1 = ' CASE WHEN '; + $case_when1 .= $query->charLength('a.alias', '!=', '0'); + $case_when1 .= ' THEN '; + $a_id = $query->castAs('CHAR', 'a.id'); + $case_when1 .= $query->concatenate([$a_id, 'a.alias'], ':'); + $case_when1 .= ' ELSE '; + $case_when1 .= $a_id . ' END as slug'; - $case_when2 = ' CASE WHEN '; - $case_when2 .= $query->charLength('c.alias', '!=', '0'); - $case_when2 .= ' THEN '; - $c_id = $query->castAs('CHAR', 'c.id'); - $case_when2 .= $query->concatenate([$c_id, 'c.alias'], ':'); - $case_when2 .= ' ELSE '; - $case_when2 .= $c_id . ' END as catslug'; + $case_when2 = ' CASE WHEN '; + $case_when2 .= $query->charLength('c.alias', '!=', '0'); + $case_when2 .= ' THEN '; + $c_id = $query->castAs('CHAR', 'c.id'); + $case_when2 .= $query->concatenate([$c_id, 'c.alias'], ':'); + $case_when2 .= ' ELSE '; + $case_when2 .= $c_id . ' END as catslug'; - $model->setState( - 'list.select', - 'a.*, c.description AS c_description, c.published AS c_published,' . $case_when1 . ',' . $case_when2 - ); + $model->setState( + 'list.select', + 'a.*, c.description AS c_description, c.published AS c_published,' . $case_when1 . ',' . $case_when2 + ); - $model->setState('filter.c.published', 1); + $model->setState('filter.c.published', 1); - // Filter by language - $model->setState('filter.language', $app->getLanguageFilter()); + // Filter by language + $model->setState('filter.language', $app->getLanguageFilter()); - $items = $model->getItems(); + $items = $model->getItems(); - if ($items) - { - foreach ($items as $item) - { - $temp = $item->params; - $item->params = clone $cParams; - $item->params->merge($temp); + if ($items) { + foreach ($items as $item) { + $temp = $item->params; + $item->params = clone $cParams; + $item->params->merge($temp); - if ($item->params->get('count_clicks', 1) == 1) - { - $item->link = Route::_('index.php?option=com_weblinks&task=weblink.go&catid=' . $item->catslug . '&id=' . $item->slug); - } - else - { - $item->link = $item->url; - } - } + if ($item->params->get('count_clicks', 1) == 1) { + $item->link = Route::_('index.php?option=com_weblinks&task=weblink.go&catid=' . $item->catslug . '&id=' . $item->slug); + } else { + $item->link = $item->url; + } + } - return $items; - } + return $items; + } - return []; - } + return []; + } - /** - * Retrieve list of weblinks - * - * @param Registry $params The module parameters - * @param CMSApplicationInterface $app The application - * - * @return mixed Null if no weblinks based on input parameters else an array containing all the weblinks. - * - * @since 1.5 - * - * @deprecated 5.0 Use the none static function getWeblinks - **/ - public static function getList($params, $app) - { - return (new self())->getWeblinks($params, $app); - } + /** + * Retrieve list of weblinks + * + * @param Registry $params The module parameters + * @param CMSApplicationInterface $app The application + * + * @return mixed Null if no weblinks based on input parameters else an array containing all the weblinks. + * + * @since 1.5 + * + * @deprecated 5.0 Use the none static function getWeblinks + **/ + public static function getList($params, $app) + { + return (new self())->getWeblinks($params, $app); + } } diff --git a/src/modules/mod_weblinks/tmpl/default.php b/src/modules/mod_weblinks/tmpl/default.php index 0cac7fb..e24b891 100644 --- a/src/modules/mod_weblinks/tmpl/default.php +++ b/src/modules/mod_weblinks/tmpl/default.php @@ -1,4 +1,5 @@ -get('groupby', 0)) : ?> - - get('groupby_columns', 3); ?> - - $l->catid, 'title' => $l->category_title); ?> - - - $cat) : ?> - - - catid == $cat['catid']) : ?> - - - - 1) :?> - -
- -
- - get('groupby_showtitle', 1)) :?> - - ; -
    - -
  • -
    - link; - $width = (int) $item->params->get('width', 600); - $height = (int) $item->params->get('height', 500); +get('groupby', 0)) : + ?> + + get('groupby_columns', 3); ?> + + $l->catid, 'title' => $l->category_title); ?> + + + $cat) : + ?> + + + catid == $cat['catid']) : + ?> + + + + 1) : + ?> + +
    + +
    + + get('groupby_showtitle', 1)) : + ?> + + ; +
      + +
    • +
      + link; + $width = (int) $item->params->get('width', 600); + $height = (int) $item->params->get('height', 500); + switch ($item->params->get('target')) { + case 1: + // Open in a new window + echo '' . + htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; + break; + case 2: + // Open in a popup window + $attribs = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' . $width . ',height=' . $height; + echo "" . + htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; - switch ($item->params->get('target')) - { - case 1: - // Open in a new window - echo '' . - htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; - break; - case 2: - // Open in a popup window - $attribs = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' . $width . ',height=' . $height; - echo "" . - htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; - break; - case 3: - // Open in a modal window - $modalId = 'weblink-item-modal-' . $item->id; - $modalParams['title'] = htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8'); - $modalParams['url'] = $link; - $modalParams['height'] = '100%'; - $modalParams['width'] = '100%'; - $modalParams['bodyHeight'] = 70; - $modalParams['modalWidth'] = 80; - echo HTMLHelper::_('bootstrap.renderModal', $modalId, $modalParams); - echo ''; - break; - default: - // Open in parent window - echo '' . - htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; - break; - } - ?> -
      - get('description', 0) ? '
      ' . $item->description . '
      ' : ''; ?> - get('hits', 0)) : ?> -
      - hits . ' ' . Text::_('MOD_WEBLINKS_HITS'); ?> -
      - -
    • - -
    - 1) :?> -
    - -
    - - - - -
      - -
    • -
      - link; - $width = (int) $item->params->get('width', 600); - $height = (int) $item->params->get('height', 500); + break; + case 3: + // Open in a modal window + $modalId = 'weblink-item-modal-' . $item->id; + $modalParams['title'] = htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8'); + $modalParams['url'] = $link; + $modalParams['height'] = '100%'; + $modalParams['width'] = '100%'; + $modalParams['bodyHeight'] = 70; + $modalParams['modalWidth'] = 80; + echo HTMLHelper::_('bootstrap.renderModal', $modalId, $modalParams); + echo ''; - switch ($item->params->get('target')) - { - case 1: - // Open in a new window - echo '' . - htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; - break; - case 2: - // Open in a popup window - $attribs = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' . $width . ',height=' . $height; - echo "" . - htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; - break; - case 3: - // Open in a modal window - $modalId = 'weblink-item-modal-' . $item->id; - $modalParams['title'] = htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8'); - $modalParams['url'] = $link; - $modalParams['height'] = '100%'; - $modalParams['width'] = '100%'; - $modalParams['bodyHeight'] = 70; - $modalParams['modalWidth'] = 80; - echo HTMLHelper::_('bootstrap.renderModal', $modalId, $modalParams); - echo '
      + get('description', 0) ? '
      ' . $item->description . '
      ' : ''; ?> + get('hits', 0)) : + ?> +
      + hits . ' ' . Text::_('MOD_WEBLINKS_HITS'); ?> +
      + +
    • + +
    + 1) : + ?> +
    + +
    + + + + +
      + +
    • +
      + link; + $width = (int) $item->params->get('width', 600); + $height = (int) $item->params->get('height', 500); + switch ($item->params->get('target')) { + case 1: + // Open in a new window + echo '' . + htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; + + break; + case 2: + // Open in a popup window + $attribs = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' . $width . ',height=' . $height; + echo "" . + htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; + + break; + case 3: + // Open in a modal window + $modalId = 'weblink-item-modal-' . $item->id; + $modalParams['title'] = htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8'); + $modalParams['url'] = $link; + $modalParams['height'] = '100%'; + $modalParams['width'] = '100%'; + $modalParams['bodyHeight'] = 70; + $modalParams['modalWidth'] = 80; + echo HTMLHelper::_('bootstrap.renderModal', $modalId, $modalParams); + echo ''; - break; - default: - // Open in parent window - echo '' . - htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; - break; - } - ?> -
      - get('description', 0) ? '
      ' . $item->description . '
      ' : ''; ?> - get('hits', 0)) : ?> -
      - hits . ' ' . Text::_('MOD_WEBLINKS_HITS'); ?> -
      - -
    • - -
    - + + break; + default: + // Open in parent window + echo '' . + htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8') . ''; + + break; + } + ?> +
+ get('description', 0) ? '
' . $item->description . '
' : ''; ?> + get('hits', 0)) : + ?> +
+ hits . ' ' . Text::_('MOD_WEBLINKS_HITS'); ?> +
+ + + + + diff --git a/src/plugins/editors-xtd/weblink/services/provider.php b/src/plugins/editors-xtd/weblink/services/provider.php index 418d626..6789c09 100644 --- a/src/plugins/editors-xtd/weblink/services/provider.php +++ b/src/plugins/editors-xtd/weblink/services/provider.php @@ -8,7 +8,9 @@ * @license GNU General Public License version 2 or later; see LICENSE.txt */ -defined('_JEXEC') or die; +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects use Joomla\CMS\Extension\PluginInterface; use Joomla\CMS\Factory; @@ -19,29 +21,29 @@ use Joomla\Event\DispatcherInterface; use Joomla\Plugin\EditorsXtd\Weblink\Extension\Weblink; return new class () implements ServiceProviderInterface { - /** - * Registers the service provider with a DI container. - * - * @param Container $container The DI container. - * - * @return void - * - * @since __DEPLOY_VERSION__ - */ - public function register(Container $container) - { - $container->set( - PluginInterface::class, - function (Container $container) { - $app = Factory::getApplication(); - $dispatcher = $container->get(DispatcherInterface::class); + /** + * Registers the service provider with a DI container. + * + * @param Container $container The DI container. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function register(Container $container) + { + $container->set( + PluginInterface::class, + function (Container $container) { + $app = Factory::getApplication(); + $dispatcher = $container->get(DispatcherInterface::class); - return new Weblink( - $dispatcher, - (array) PluginHelper::getPlugin('editors-xtd', 'weblink'), - $app - ); - } - ); - } + return new Weblink( + $dispatcher, + (array) PluginHelper::getPlugin('editors-xtd', 'weblink'), + $app + ); + } + ); + } }; diff --git a/src/plugins/editors-xtd/weblink/src/Extension/Weblink.php b/src/plugins/editors-xtd/weblink/src/Extension/Weblink.php index de0ce28..3b19457 100644 --- a/src/plugins/editors-xtd/weblink/src/Extension/Weblink.php +++ b/src/plugins/editors-xtd/weblink/src/Extension/Weblink.php @@ -1,4 +1,5 @@ setApplication($application); - } + $this->setApplication($application); + } - /** - * Display the button - * - * @param string $name The name of the button to add - * - * @return CMSObject The button options as JObject - * - * @since __DEPLOY_VERSION__ - */ - public function onDisplay($name) - { - $user = $this->getApplication()->getIdentity(); + /** + * Display the button + * + * @param string $name The name of the button to add + * + * @return CMSObject The button options as JObject + * + * @since __DEPLOY_VERSION__ + */ + public function onDisplay($name) + { + $user = $this->getApplication()->getIdentity(); - if ($user->authorise('core.create', 'com_weblinks') - || $user->authorise('core.edit', 'com_weblinks') - || $user->authorise('core.edit.own', 'com_weblinks')) - { - // The URL for the weblinks list - $link = 'index.php?option=com_weblinks&view=weblinks&layout=modal&tmpl=component&' - . Session::getFormToken() . '=1&editor=' . $name; + if ( + $user->authorise('core.create', 'com_weblinks') + || $user->authorise('core.edit', 'com_weblinks') + || $user->authorise('core.edit.own', 'com_weblinks') + ) { + // The URL for the weblinks list + $link = 'index.php?option=com_weblinks&view=weblinks&layout=modal&tmpl=component&' + . Session::getFormToken() . '=1&editor=' . $name; - $button = new CMSObject; - $button->modal = true; - $button->link = $link; - $button->text = Text::_('PLG_EDITORS-XTD_WEBLINK_BUTTON_WEBLINK'); - $button->name = $this->_type . '_' . $this->_name; - $button->icon = 'globe'; - $button->iconSVG = ' + $button = new CMSObject(); + $button->modal = true; + $button->link = $link; + $button->text = Text::_('PLG_EDITORS-XTD_WEBLINK_BUTTON_WEBLINK'); + $button->name = $this->_type . '_' . $this->_name; + $button->icon = 'globe'; + // phpcs:disable Generic.Files.LineLength + $button->iconSVG = ' '; + // phpcs:enable Generic.Files.LineLength + $button->options = [ + 'height' => '300px', + 'width' => '800px', + 'bodyHeight' => '70', + 'modalWidth' => '80', + ]; - $button->options = [ - 'height' => '300px', - 'width' => '800px', - 'bodyHeight' => '70', - 'modalWidth' => '80', - ]; - - return $button; - } - } + return $button; + } + } } diff --git a/src/plugins/finder/weblinks/services/provider.php b/src/plugins/finder/weblinks/services/provider.php index 5147ef3..1e724df 100644 --- a/src/plugins/finder/weblinks/services/provider.php +++ b/src/plugins/finder/weblinks/services/provider.php @@ -8,7 +8,9 @@ * @license GNU General Public License version 2 or later; see LICENSE.txt */ -defined('_JEXEC') or die; +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects use Joomla\CMS\Extension\PluginInterface; use Joomla\CMS\Plugin\PluginHelper; @@ -19,29 +21,29 @@ use Joomla\Event\DispatcherInterface; use Joomla\Plugin\Finder\Weblinks\Extension\Weblinks; return new class () implements ServiceProviderInterface { - /** - * Registers the service provider with a DI container. - * - * @param Container $container The DI container. - * - * @return void - * - * @since __DEPLOY_VERSION__ - */ - public function register(Container $container) - { - $container->set( - PluginInterface::class, - function (Container $container) { - $dispatcher = $container->get(DispatcherInterface::class); - $database = $container->get(DatabaseInterface::class); + /** + * Registers the service provider with a DI container. + * + * @param Container $container The DI container. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function register(Container $container) + { + $container->set( + PluginInterface::class, + function (Container $container) { + $dispatcher = $container->get(DispatcherInterface::class); + $database = $container->get(DatabaseInterface::class); - return new Weblinks( - $dispatcher, - (array) PluginHelper::getPlugin('finder', 'weblinks'), - $database - ); - } - ); - } + return new Weblinks( + $dispatcher, + (array) PluginHelper::getPlugin('finder', 'weblinks'), + $database + ); + } + ); + } }; diff --git a/src/plugins/finder/weblinks/src/Extension/Weblinks.php b/src/plugins/finder/weblinks/src/Extension/Weblinks.php index 1144c53..0341ce8 100644 --- a/src/plugins/finder/weblinks/src/Extension/Weblinks.php +++ b/src/plugins/finder/weblinks/src/Extension/Weblinks.php @@ -1,4 +1,5 @@ setDatabase($database); - } + $this->setDatabase($database); + } - /** - * Method to update the item link information when the item category is - * changed. This is fired when the item category is published or unpublished - * from the list view. - * - * @param string $extension The extension whose category has been updated. - * @param array $pks An array of primary key ids of the content that has changed state. - * @param integer $value The value of the state that the content has been changed to. - * - * @return void - * - * @since 2.5 - */ - public function onFinderCategoryChangeState($extension, $pks, $value) - { - // Make sure we're handling com_weblinks categories. - if ($extension == 'com_weblinks') - { - $this->categoryStateChange($pks, $value); - } - } + /** + * Method to update the item link information when the item category is + * changed. This is fired when the item category is published or unpublished + * from the list view. + * + * @param string $extension The extension whose category has been updated. + * @param array $pks An array of primary key ids of the content that has changed state. + * @param integer $value The value of the state that the content has been changed to. + * + * @return void + * + * @since 2.5 + */ + public function onFinderCategoryChangeState($extension, $pks, $value) + { + // Make sure we're handling com_weblinks categories. + if ($extension == 'com_weblinks') { + $this->categoryStateChange($pks, $value); + } + } - /** - * Method to remove the link information for items that have been deleted. - * - * @param string $context The context of the action being performed. - * @param Table $table A JTable object containing the record to be deleted. - * - * @return boolean True on success. - * - * @throws \Exception on database error. - * @since 2.5 - */ - public function onFinderAfterDelete($context, $table) - { - if ($context == 'com_weblinks.weblink') - { - $id = $table->id; - } - elseif ($context == 'com_finder.index') - { - $id = $table->link_id; - } - else - { - return true; - } + /** + * Method to remove the link information for items that have been deleted. + * + * @param string $context The context of the action being performed. + * @param Table $table A JTable object containing the record to be deleted. + * + * @return boolean True on success. + * + * @throws \Exception on database error. + * @since 2.5 + */ + public function onFinderAfterDelete($context, $table) + { + if ($context == 'com_weblinks.weblink') { + $id = $table->id; + } elseif ($context == 'com_finder.index') { + $id = $table->link_id; + } else { + return true; + } - // Remove the item from the index. - return $this->remove($id); - } + // Remove the item from the index. + return $this->remove($id); + } - /** - * Smart Search after content save method. - * Reindexes the link information for a weblink that has been saved. - * It also makes adjustments if the access level of a weblink item or - * the category to which it belongs has been changed. - * - * @param string $context The context of the content passed to the plugin. - * @param Table $row A JTable object. - * @param boolean $isNew True if the content has just been created. - * - * @return boolean True on success. - * - * @throws \Exception on database error. - * @since 2.5 - */ - public function onFinderAfterSave($context, $row, $isNew) - { - // We only want to handle web links here. We need to handle front end and back end editing. - if ($context == 'com_weblinks.weblink' || $context == 'com_weblinks.form') - { - // Check if the access levels are different. - if (!$isNew && $this->old_access != $row->access) - { - // Process the change. - $this->itemAccessChange($row); - } + /** + * Smart Search after content save method. + * Reindexes the link information for a weblink that has been saved. + * It also makes adjustments if the access level of a weblink item or + * the category to which it belongs has been changed. + * + * @param string $context The context of the content passed to the plugin. + * @param Table $row A JTable object. + * @param boolean $isNew True if the content has just been created. + * + * @return boolean True on success. + * + * @throws \Exception on database error. + * @since 2.5 + */ + public function onFinderAfterSave($context, $row, $isNew) + { + // We only want to handle web links here. We need to handle front end and back end editing. + if ($context == 'com_weblinks.weblink' || $context == 'com_weblinks.form') { + // Check if the access levels are different. + if (!$isNew && $this->old_access != $row->access) { + // Process the change. + $this->itemAccessChange($row); + } - // Reindex the item. - $this->reindex($row->id); - } + // Reindex the item. + $this->reindex($row->id); + } - // Check for access changes in the category. - if ($context == 'com_categories.category') - { - // Check if the access levels are different. - if (!$isNew && $this->old_cataccess != $row->access) - { - $this->categoryAccessChange($row); - } - } + // Check for access changes in the category. + if ($context == 'com_categories.category') { + // Check if the access levels are different. + if (!$isNew && $this->old_cataccess != $row->access) { + $this->categoryAccessChange($row); + } + } - return true; - } + return true; + } - /** - * Smart Search before content save method. - * This event is fired before the data is actually saved. - * - * @param string $context The context of the content passed to the plugin. - * @param Table $row A JTable object. - * @param boolean $isNew True if the content is just about to be created. - * - * @return boolean True on success. - * - * @throws \Exception on database error. - * @since 2.5 - */ - public function onFinderBeforeSave($context, $row, $isNew) - { - // We only want to handle web links here. - if ($context == 'com_weblinks.weblink' || $context == 'com_weblinks.form') - { - // Query the database for the old access level if the item isn't new. - if (!$isNew) - { - $this->checkItemAccess($row); - } - } + /** + * Smart Search before content save method. + * This event is fired before the data is actually saved. + * + * @param string $context The context of the content passed to the plugin. + * @param Table $row A JTable object. + * @param boolean $isNew True if the content is just about to be created. + * + * @return boolean True on success. + * + * @throws \Exception on database error. + * @since 2.5 + */ + public function onFinderBeforeSave($context, $row, $isNew) + { + // We only want to handle web links here. + if ($context == 'com_weblinks.weblink' || $context == 'com_weblinks.form') { + // Query the database for the old access level if the item isn't new. + if (!$isNew) { + $this->checkItemAccess($row); + } + } - // Check for access levels from the category. - if ($context == 'com_categories.category') - { - // Query the database for the old access level if the item isn't new. - if (!$isNew) - { - $this->checkCategoryAccess($row); - } - } + // Check for access levels from the category. + if ($context == 'com_categories.category') { + // Query the database for the old access level if the item isn't new. + if (!$isNew) { + $this->checkCategoryAccess($row); + } + } - return true; - } + return true; + } - /** - * Method to update the link information for items that have been changed - * from outside the edit screen. This is fired when the item is published, - * unpublished, archived, or unarchived from the list view. - * - * @param string $context The context for the content passed to the plugin. - * @param array $pks An array of primary key ids of the content that has changed state. - * @param integer $value The value of the state that the content has been changed to. - * - * @return void - * - * @since 2.5 - */ - public function onFinderChangeState($context, $pks, $value) - { - // We only want to handle web links here. - if ($context == 'com_weblinks.weblink' || $context == 'com_weblinks.form') - { - $this->itemStateChange($pks, $value); - } + /** + * Method to update the link information for items that have been changed + * from outside the edit screen. This is fired when the item is published, + * unpublished, archived, or unarchived from the list view. + * + * @param string $context The context for the content passed to the plugin. + * @param array $pks An array of primary key ids of the content that has changed state. + * @param integer $value The value of the state that the content has been changed to. + * + * @return void + * + * @since 2.5 + */ + public function onFinderChangeState($context, $pks, $value) + { + // We only want to handle web links here. + if ($context == 'com_weblinks.weblink' || $context == 'com_weblinks.form') { + $this->itemStateChange($pks, $value); + } - // Handle when the plugin is disabled. - if ($context == 'com_plugins.plugin' && $value === 0) - { - $this->pluginDisable($pks); - } - } + // Handle when the plugin is disabled. + if ($context == 'com_plugins.plugin' && $value === 0) { + $this->pluginDisable($pks); + } + } - /** - * Method to index an item. The item must be a FinderIndexerResult object. - * - * @param Result $item The item to index as an FinderIndexerResult object. - * - * @return void - * - * @throws \Exception on database error. - * @since 2.5 - */ - protected function index(Result $item) - { - // Check if the extension is enabled - if (ComponentHelper::isEnabled($this->extension) == false) - { - return; - } + /** + * Method to index an item. The item must be a FinderIndexerResult object. + * + * @param Result $item The item to index as an FinderIndexerResult object. + * + * @return void + * + * @throws \Exception on database error. + * @since 2.5 + */ + protected function index(Result $item) + { + // Check if the extension is enabled + if (ComponentHelper::isEnabled($this->extension) == false) { + return; + } - $item->setLanguage(); + $item->setLanguage(); - // Initialise the item parameters. - $item->params = new Registry($item->params); - $item->metadata = new Registry($item->metadata); + // Initialise the item parameters. + $item->params = new Registry($item->params); + $item->metadata = new Registry($item->metadata); - // Build the necessary route and path information. - $item->url = $this->getURL($item->id, $this->extension, $this->layout); - $item->route = RouteHelper::getWeblinkRoute($item->slug, $item->catslug, $item->language); + // Build the necessary route and path information. + $item->url = $this->getURL($item->id, $this->extension, $this->layout); + $item->route = RouteHelper::getWeblinkRoute($item->slug, $item->catslug, $item->language); - /* - * Add the meta-data processing instructions based on the newsfeeds - * configuration parameters. - */ - // Add the meta-author. - $item->metaauthor = $item->metadata->get('author'); + /* + * Add the meta-data processing instructions based on the newsfeeds + * configuration parameters. + */ + // Add the meta-author. + $item->metaauthor = $item->metadata->get('author'); - // Handle the link to the meta-data. - $item->addInstruction(Indexer::META_CONTEXT, 'link'); - $item->addInstruction(Indexer::META_CONTEXT, 'metakey'); - $item->addInstruction(Indexer::META_CONTEXT, 'metadesc'); - $item->addInstruction(Indexer::META_CONTEXT, 'metaauthor'); - $item->addInstruction(Indexer::META_CONTEXT, 'author'); - $item->addInstruction(Indexer::META_CONTEXT, 'created_by_alias'); + // Handle the link to the meta-data. + $item->addInstruction(Indexer::META_CONTEXT, 'link'); + $item->addInstruction(Indexer::META_CONTEXT, 'metakey'); + $item->addInstruction(Indexer::META_CONTEXT, 'metadesc'); + $item->addInstruction(Indexer::META_CONTEXT, 'metaauthor'); + $item->addInstruction(Indexer::META_CONTEXT, 'author'); + $item->addInstruction(Indexer::META_CONTEXT, 'created_by_alias'); - // Translate the state. Weblinks should only be published if the category is published and also ensure that 'state' for trashed items is set to zero - $item->state = $this->translateState($item->state, $item->cat_state); + // Translate the state. Weblinks should only be published if the category is published and also ensure that 'state' for trashed items is set to zero + $item->state = $this->translateState($item->state, $item->cat_state); - // Add the type taxonomy data. - $item->addTaxonomy('Type', 'Web Link'); + // Add the type taxonomy data. + $item->addTaxonomy('Type', 'Web Link'); - // Add the category taxonomy data. - $categories = Categories::getInstance('com_weblinks', ['published' => false, 'access' => false]); - $category = $categories->get($item->catid); + // Add the category taxonomy data. + $categories = Categories::getInstance('com_weblinks', ['published' => false, 'access' => false]); + $category = $categories->get($item->catid); - // Category does not exist, stop here - if (!$category) - { - return; - } + // Category does not exist, stop here + if (!$category) { + return; + } - $item->addNestedTaxonomy('Category', $category, $this->translateState($category->published), $category->access, $category->language); + $item->addNestedTaxonomy('Category', $category, $this->translateState($category->published), $category->access, $category->language); - // Add the language taxonomy data. - $item->addTaxonomy('Language', $item->language); + // Add the language taxonomy data. + $item->addTaxonomy('Language', $item->language); - // Get content extras. - Helper::getContentExtras($item); + // Get content extras. + Helper::getContentExtras($item); - // Index the item. - $this->indexer->index($item); - } + // Index the item. + $this->indexer->index($item); + } - /** - * Method to setup the indexer to be run. - * - * @return boolean True on success. - * - * @since 2.5 - */ - protected function setup() - { - return true; - } + /** + * Method to setup the indexer to be run. + * + * @return boolean True on success. + * + * @since 2.5 + */ + protected function setup() + { + return true; + } - /** - * Method to get the SQL query used to retrieve the list of content items. - * - * @param mixed $query A JDatabaseQuery object or null. - * - * @return DatabaseQuery A database object. - * - * @since 2.5 - */ - protected function getListQuery($query = null) - { - $db = $this->getDatabase(); + /** + * Method to get the SQL query used to retrieve the list of content items. + * + * @param mixed $query A JDatabaseQuery object or null. + * + * @return DatabaseQuery A database object. + * + * @since 2.5 + */ + protected function getListQuery($query = null) + { + $db = $this->getDatabase(); - // Check if we can use the supplied SQL query. - $query = $query instanceof DatabaseQuery ? $query : $db->getQuery(true) - ->select('a.id, a.catid, a.title, a.alias, a.url AS link, a.description AS summary') - ->select('a.metakey, a.metadesc, a.metadata, a.language, a.access, a.ordering') - ->select('a.created_by_alias, a.modified, a.modified_by') - ->select('a.publish_up AS publish_start_date, a.publish_down AS publish_end_date') - ->select('a.state AS state, a.created AS start_date, a.params') - ->select('c.title AS category, c.published AS cat_state, c.access AS cat_access'); + // Check if we can use the supplied SQL query. + $query = $query instanceof DatabaseQuery ? $query : $db->getQuery(true) + ->select('a.id, a.catid, a.title, a.alias, a.url AS link, a.description AS summary') + ->select('a.metakey, a.metadesc, a.metadata, a.language, a.access, a.ordering') + ->select('a.created_by_alias, a.modified, a.modified_by') + ->select('a.publish_up AS publish_start_date, a.publish_down AS publish_end_date') + ->select('a.state AS state, a.created AS start_date, a.params') + ->select('c.title AS category, c.published AS cat_state, c.access AS cat_access'); - // Handle the alias CASE WHEN portion of the query. - $case_when_item_alias = ' CASE WHEN '; - $case_when_item_alias .= $query->charLength('a.alias', '!=', '0'); - $case_when_item_alias .= ' THEN '; - $a_id = $query->castAs('CHAR', 'a.id'); - $case_when_item_alias .= $query->concatenate([$a_id, 'a.alias'], ':'); - $case_when_item_alias .= ' ELSE '; - $case_when_item_alias .= $a_id . ' END as slug'; - $query->select($case_when_item_alias); + // Handle the alias CASE WHEN portion of the query. + $case_when_item_alias = ' CASE WHEN '; + $case_when_item_alias .= $query->charLength('a.alias', '!=', '0'); + $case_when_item_alias .= ' THEN '; + $a_id = $query->castAs('CHAR', 'a.id'); + $case_when_item_alias .= $query->concatenate([$a_id, 'a.alias'], ':'); + $case_when_item_alias .= ' ELSE '; + $case_when_item_alias .= $a_id . ' END as slug'; + $query->select($case_when_item_alias); - $case_when_category_alias = ' CASE WHEN '; - $case_when_category_alias .= $query->charLength('c.alias', '!=', '0'); - $case_when_category_alias .= ' THEN '; - $c_id = $query->castAs('CHAR', 'c.id'); - $case_when_category_alias .= $query->concatenate([$c_id, 'c.alias'], ':'); - $case_when_category_alias .= ' ELSE '; - $case_when_category_alias .= $c_id . ' END as catslug'; - $query->select($case_when_category_alias) - ->from('#__weblinks AS a') - ->join('LEFT', '#__categories AS c ON c.id = a.catid'); + $case_when_category_alias = ' CASE WHEN '; + $case_when_category_alias .= $query->charLength('c.alias', '!=', '0'); + $case_when_category_alias .= ' THEN '; + $c_id = $query->castAs('CHAR', 'c.id'); + $case_when_category_alias .= $query->concatenate([$c_id, 'c.alias'], ':'); + $case_when_category_alias .= ' ELSE '; + $case_when_category_alias .= $c_id . ' END as catslug'; + $query->select($case_when_category_alias) + ->from('#__weblinks AS a') + ->join('LEFT', '#__categories AS c ON c.id = a.catid'); - return $query; - } + return $query; + } - /** - * Method to get the query clause for getting items to update by time. - * - * @param string $time The modified timestamp. - * - * @return DatabaseQuery A database object. - * - * @since 2.5 - */ - protected function getUpdateQueryByTime($time) - { - // Build an SQL query based on the modified time. - $db = $this->getDatabase(); - $query = $db->getQuery(true) - ->where('a.date >= ' . $db->quote($time)); + /** + * Method to get the query clause for getting items to update by time. + * + * @param string $time The modified timestamp. + * + * @return DatabaseQuery A database object. + * + * @since 2.5 + */ + protected function getUpdateQueryByTime($time) + { + // Build an SQL query based on the modified time. + $db = $this->getDatabase(); + $query = $db->getQuery(true) + ->where('a.date >= ' . $db->quote($time)); - return $query; - } + return $query; + } } diff --git a/src/plugins/search/weblinks/services/provider.php b/src/plugins/search/weblinks/services/provider.php index 47f24db..1a7c075 100644 --- a/src/plugins/search/weblinks/services/provider.php +++ b/src/plugins/search/weblinks/services/provider.php @@ -8,7 +8,9 @@ * @license GNU General Public License version 2 or later; see LICENSE.txt */ -defined('_JEXEC') or die; +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects use Joomla\CMS\Extension\PluginInterface; use Joomla\CMS\Factory; @@ -20,31 +22,31 @@ use Joomla\Event\DispatcherInterface; use Joomla\Plugin\Search\Weblinks\Extension\Weblinks; return new class () implements ServiceProviderInterface { - /** - * Registers the service provider with a DI container. - * - * @param Container $container The DI container. - * - * @return void - * - * @since __DEPLOY_VERSION__ - */ - public function register(Container $container) - { - $container->set( - PluginInterface::class, - function (Container $container) { - $app = Factory::getApplication(); - $dispatcher = $container->get(DispatcherInterface::class); - $database = $container->get(DatabaseInterface::class); + /** + * Registers the service provider with a DI container. + * + * @param Container $container The DI container. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function register(Container $container) + { + $container->set( + PluginInterface::class, + function (Container $container) { + $app = Factory::getApplication(); + $dispatcher = $container->get(DispatcherInterface::class); + $database = $container->get(DatabaseInterface::class); - return new Weblinks( - $dispatcher, - (array) PluginHelper::getPlugin('finder', 'weblinks'), - $app, - $database - ); - } - ); - } + return new Weblinks( + $dispatcher, + (array) PluginHelper::getPlugin('finder', 'weblinks'), + $app, + $database + ); + } + ); + } }; diff --git a/src/plugins/search/weblinks/src/Extension/Weblinks.php b/src/plugins/search/weblinks/src/Extension/Weblinks.php index 5864c4d..a7a2812 100644 --- a/src/plugins/search/weblinks/src/Extension/Weblinks.php +++ b/src/plugins/search/weblinks/src/Extension/Weblinks.php @@ -1,4 +1,5 @@ setApplication($application); - $this->setDatabase($database); - } + $this->setApplication($application); + $this->setDatabase($database); + } - /** - * Determine areas searchable by this plugin. - * - * @return array An array of search areas. - * - * @since 1.6 - */ - public function onContentSearchAreas() - { - static $areas = [ - 'weblinks' => 'PLG_SEARCH_WEBLINKS_WEBLINKS', - ]; + /** + * Determine areas searchable by this plugin. + * + * @return array An array of search areas. + * + * @since 1.6 + */ + public function onContentSearchAreas() + { + static $areas = [ + 'weblinks' => 'PLG_SEARCH_WEBLINKS_WEBLINKS', + ]; - return $areas; - } + return $areas; + } - /** - * Search content (weblinks). - * - * The SQL must return the following fields that are used in a common display - * routine: href, title, section, created, text, browsernav - * - * @param string $text Target search string. - * @param string $phrase Matching option (possible values: exact|any|all). Default is "any". - * @param string $ordering Ordering option (possible values: newest|oldest|popular|alpha|category). Default is "newest". - * @param mixed $areas An array if the search it to be restricted to areas or null to search all areas. - * - * @return array Search results. - * - * @since 1.6 - */ - public function onContentSearch($text, $phrase = '', $ordering = '', $areas = null) - { - $app = $this->getApplication(); - $db = $this->getDatabase(); - $groups = $app->getIdentity()->getAuthorisedViewLevels(); + /** + * Search content (weblinks). + * + * The SQL must return the following fields that are used in a common display + * routine: href, title, section, created, text, browsernav + * + * @param string $text Target search string. + * @param string $phrase Matching option (possible values: exact|any|all). Default is "any". + * @param string $ordering Ordering option (possible values: newest|oldest|popular|alpha|category). Default is "newest". + * @param mixed $areas An array if the search it to be restricted to areas or null to search all areas. + * + * @return array Search results. + * + * @since 1.6 + */ + public function onContentSearch($text, $phrase = '', $ordering = '', $areas = null) + { + $app = $this->getApplication(); + $db = $this->getDatabase(); + $groups = $app->getIdentity()->getAuthorisedViewLevels(); - $searchText = $text; + $searchText = $text; - if (is_array($areas) - && !array_intersect($areas, array_keys($this->onContentSearchAreas()))) - { - return []; - } + if ( + is_array($areas) + && !array_intersect($areas, array_keys($this->onContentSearchAreas())) + ) { + return []; + } - $sContent = $this->params->get('search_content', 1); - $sArchived = $this->params->get('search_archived', 1); - $limit = $this->params->def('search_limit', 50); - $state = []; + $sContent = $this->params->get('search_content', 1); + $sArchived = $this->params->get('search_archived', 1); + $limit = $this->params->def('search_limit', 50); + $state = []; - if ($sContent) - { - $state[] = 1; - } + if ($sContent) { + $state[] = 1; + } - if ($sArchived) - { - $state[] = 2; - } + if ($sArchived) { + $state[] = 2; + } - if (empty($state)) - { - return []; - } + if (empty($state)) { + return []; + } - $text = trim($text); + $text = trim($text); - if ($text == '') - { - return []; - } + if ($text == '') { + return []; + } - $searchWeblinks = Text::_('PLG_SEARCH_WEBLINKS'); + $searchWeblinks = Text::_('PLG_SEARCH_WEBLINKS'); - switch ($phrase) - { - case 'exact': - $text = $db->quote('%' . $db->escape($text, true) . '%', false); - $wheres2 = []; - $wheres2[] = 'a.url LIKE ' . $text; - $wheres2[] = 'a.description LIKE ' . $text; - $wheres2[] = 'a.title LIKE ' . $text; - $where = '(' . implode(') OR (', $wheres2) . ')'; - break; + switch ($phrase) { + case 'exact': + $text = $db->quote('%' . $db->escape($text, true) . '%', false); + $wheres2 = []; + $wheres2[] = 'a.url LIKE ' . $text; + $wheres2[] = 'a.description LIKE ' . $text; + $wheres2[] = 'a.title LIKE ' . $text; + $where = '(' . implode(') OR (', $wheres2) . ')'; + break; - case 'all': - case 'any': - default: - $words = explode(' ', $text); - $wheres = []; + case 'all': + case 'any': + default: + $words = explode(' ', $text); + $wheres = []; - foreach ($words as $word) - { - $word = $db->quote('%' . $db->escape($word, true) . '%', false); - $wheres2 = []; - $wheres2[] = 'a.url LIKE ' . $word; - $wheres2[] = 'a.description LIKE ' . $word; - $wheres2[] = 'a.title LIKE ' . $word; - $wheres[] = implode(' OR ', $wheres2); - } + foreach ($words as $word) { + $word = $db->quote('%' . $db->escape($word, true) . '%', false); + $wheres2 = []; + $wheres2[] = 'a.url LIKE ' . $word; + $wheres2[] = 'a.description LIKE ' . $word; + $wheres2[] = 'a.title LIKE ' . $word; + $wheres[] = implode(' OR ', $wheres2); + } - $where = '(' . implode(($phrase == 'all' ? ') AND (' : ') OR ('), $wheres) . ')'; - break; - } + $where = '(' . implode(($phrase == 'all' ? ') AND (' : ') OR ('), $wheres) . ')'; + break; + } - switch ($ordering) - { - case 'oldest': - $order = 'a.created ASC'; - break; + switch ($ordering) { + case 'oldest': + $order = 'a.created ASC'; + break; - case 'popular': - $order = 'a.hits DESC'; - break; + case 'popular': + $order = 'a.hits DESC'; + break; - case 'alpha': - $order = 'a.title ASC'; - break; + case 'alpha': + $order = 'a.title ASC'; + break; - case 'category': - $order = 'c.title ASC, a.title ASC'; - break; + case 'category': + $order = 'c.title ASC, a.title ASC'; + break; - case 'newest': - default: - $order = 'a.created DESC'; - } + case 'newest': + default: + $order = 'a.created DESC'; + } - $query = $db->getQuery(true); + $query = $db->getQuery(true); - // SQLSRV changes. - $caseWhen = ' CASE WHEN '; - $caseWhen .= $query->charLength('a.alias', '!=', '0'); - $caseWhen .= ' THEN '; - $a_id = $query->castAs('CHAR', 'a.id'); - $caseWhen .= $query->concatenate([$a_id, 'a.alias'], ':'); - $caseWhen .= ' ELSE '; - $caseWhen .= $a_id . ' END as slug'; + // SQLSRV changes. + $caseWhen = ' CASE WHEN '; + $caseWhen .= $query->charLength('a.alias', '!=', '0'); + $caseWhen .= ' THEN '; + $a_id = $query->castAs('CHAR', 'a.id'); + $caseWhen .= $query->concatenate([$a_id, 'a.alias'], ':'); + $caseWhen .= ' ELSE '; + $caseWhen .= $a_id . ' END as slug'; - $caseWhen1 = ' CASE WHEN '; - $caseWhen1 .= $query->charLength('c.alias', '!=', '0'); - $caseWhen1 .= ' THEN '; - $c_id = $query->castAs('CHAR', 'c.id'); - $caseWhen1 .= $query->concatenate([$c_id, 'c.alias'], ':'); - $caseWhen1 .= ' ELSE '; - $caseWhen1 .= $c_id . ' END as catslug'; + $caseWhen1 = ' CASE WHEN '; + $caseWhen1 .= $query->charLength('c.alias', '!=', '0'); + $caseWhen1 .= ' THEN '; + $c_id = $query->castAs('CHAR', 'c.id'); + $caseWhen1 .= $query->concatenate([$c_id, 'c.alias'], ':'); + $caseWhen1 .= ' ELSE '; + $caseWhen1 .= $c_id . ' END as catslug'; - $query->select('a.title AS title, a.created AS created, a.url, a.description AS text, ' . $caseWhen . "," . $caseWhen1) - ->select($query->concatenate([$db->quote($searchWeblinks), 'c.title'], " / ") . ' AS section') - ->select('\'1\' AS browsernav') - ->from('#__weblinks AS a') - ->join('INNER', '#__categories as c ON c.id = a.catid') - ->where('(' . $where . ')') - ->whereIn($db->quoteName('a.state'), $state) - ->where($db->quoteName('c.published') . ' = 1') - ->whereIn($db->quoteName('c.access'), $groups) - ->order($order); + $query->select('a.title AS title, a.created AS created, a.url, a.description AS text, ' . $caseWhen . "," . $caseWhen1) + ->select($query->concatenate([$db->quote($searchWeblinks), 'c.title'], " / ") . ' AS section') + ->select('\'1\' AS browsernav') + ->from('#__weblinks AS a') + ->join('INNER', '#__categories as c ON c.id = a.catid') + ->where('(' . $where . ')') + ->whereIn($db->quoteName('a.state'), $state) + ->where($db->quoteName('c.published') . ' = 1') + ->whereIn($db->quoteName('c.access'), $groups) + ->order($order); - // Filter by language. + // Filter by language. - if ($app->isClient('site') && Multilanguage::isEnabled()) - { - $languages = [$app->getLanguage()->getTag(), '*']; - $query->whereIn($db->quoteName('a.language'), $languages, ParameterType::STRING) - ->whereIn($db->quoteName('c.language'), $languages, ParameterType::STRING); - } + if ($app->isClient('site') && Multilanguage::isEnabled()) { + $languages = [$app->getLanguage()->getTag(), '*']; + $query->whereIn($db->quoteName('a.language'), $languages, ParameterType::STRING) + ->whereIn($db->quoteName('c.language'), $languages, ParameterType::STRING); + } - $db->setQuery($query, 0, $limit); - $rows = $db->loadObjectList(); + $db->setQuery($query, 0, $limit); + $rows = $db->loadObjectList(); - $return = []; + $return = []; - if ($rows) - { - foreach ($rows as $key => $row) - { - $rows[$key]->href = RouteHelper::getWeblinkRoute($row->slug, $row->catslug); - } + if ($rows) { + foreach ($rows as $key => $row) { + $rows[$key]->href = RouteHelper::getWeblinkRoute($row->slug, $row->catslug); + } - foreach ($rows as $weblink) - { - if (\searchHelper::checkNoHTML($weblink, $searchText, ['url', 'text', 'title'])) - { - $return[] = $weblink; - } - } - } + foreach ($rows as $weblink) { + if (\searchHelper::checkNoHTML($weblink, $searchText, ['url', 'text', 'title'])) { + $return[] = $weblink; + } + } + } - return $return; - } + return $return; + } } diff --git a/src/plugins/system/weblinks/services/provider.php b/src/plugins/system/weblinks/services/provider.php index 572b21f..6e2a7d3 100644 --- a/src/plugins/system/weblinks/services/provider.php +++ b/src/plugins/system/weblinks/services/provider.php @@ -8,7 +8,9 @@ * @license GNU General Public License version 2 or later; see LICENSE.txt */ -defined('_JEXEC') or die; +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects use Joomla\CMS\Extension\PluginInterface; use Joomla\CMS\Plugin\PluginHelper; @@ -19,29 +21,29 @@ use Joomla\Event\DispatcherInterface; use Joomla\Plugin\System\Weblinks\Extension\Weblinks; return new class () implements ServiceProviderInterface { - /** - * Registers the service provider with a DI container. - * - * @param Container $container The DI container. - * - * @return void - * - * @since __DEPLOY_VERSION__ - */ - public function register(Container $container) - { - $container->set( - PluginInterface::class, - function (Container $container) { - $dispatcher = $container->get(DispatcherInterface::class); - $database = $container->get(DatabaseInterface::class); + /** + * Registers the service provider with a DI container. + * + * @param Container $container The DI container. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function register(Container $container) + { + $container->set( + PluginInterface::class, + function (Container $container) { + $dispatcher = $container->get(DispatcherInterface::class); + $database = $container->get(DatabaseInterface::class); - return new Weblinks( - $dispatcher, - (array) PluginHelper::getPlugin('system', 'weblinks'), - $database - ); - } - ); - } + return new Weblinks( + $dispatcher, + (array) PluginHelper::getPlugin('system', 'weblinks'), + $database + ); + } + ); + } }; diff --git a/src/plugins/system/weblinks/src/Extension/Weblinks.php b/src/plugins/system/weblinks/src/Extension/Weblinks.php index e378804..ee7d19e 100644 --- a/src/plugins/system/weblinks/src/Extension/Weblinks.php +++ b/src/plugins/system/weblinks/src/Extension/Weblinks.php @@ -1,4 +1,5 @@ setDatabase($database); - } + $this->setDatabase($database); + } - /** - * Returns an array of CMS events this plugin will listen to and the respective handlers. - * - * @return array - * - * @since __DEPLOY_VERSION__ - */ - public static function getSubscribedEvents(): array - { - return [ - 'onGetStats' => 'onGetStats', - ]; - } + /** + * Returns an array of CMS events this plugin will listen to and the respective handlers. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function getSubscribedEvents(): array + { + return [ + 'onGetStats' => 'onGetStats', + ]; + } - /** - * Method to add statistics information to Administrator control panel. - * - * @param string $extension The extension requesting information. - * - * @return void - * - * @since __DEPLOY_VERSION__ - */ - public function onGetStats(Event $event) - { - if (!ComponentHelper::isEnabled('com_weblinks')) - { - return; - } + /** + * Method to add statistics information to Administrator control panel. + * + * @param string $extension The extension requesting information. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function onGetStats(Event $event) + { + if (!ComponentHelper::isEnabled('com_weblinks')) { + return; + } - [$extension] = $event->getArguments(); + [$extension] = $event->getArguments(); - if (!in_array($extension, $this->supportedExtensions)) - { - return; - } + if (!in_array($extension, $this->supportedExtensions)) { + return; + } - $db = $this->getDatabase(); - $query = $db->getQuery(true) - ->select('COUNT(id) AS count_links') - ->from('#__weblinks') - ->where('state = 1'); - $webLinks = $db->setQuery($query)->loadResult(); + $db = $this->getDatabase(); + $query = $db->getQuery(true) + ->select('COUNT(id) AS count_links') + ->from('#__weblinks') + ->where('state = 1'); + $webLinks = $db->setQuery($query)->loadResult(); - if (!$webLinks) - { - return; - } + if (!$webLinks) { + return; + } - $result = $event->getArgument('result', []); - $result[] = [ - [ - 'title' => Text::_('PLG_SYSTEM_WEBLINKS_STATISTICS'), - 'icon' => 'out-2', - 'data' => $webLinks, - ], - ]; + $result = $event->getArgument('result', []); + $result[] = [ + [ + 'title' => Text::_('PLG_SYSTEM_WEBLINKS_STATISTICS'), + 'icon' => 'out-2', + 'data' => $webLinks, + ], + ]; - $event->setArgument('result', $result); - } + $event->setArgument('result', $result); + } }