diff --git a/CHANGELOG.md b/CHANGELOG.md index 93439eb3..6258b86b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ -# v2.1.1 +# v5.0.0-beta1 -- Moved over to a Joomla Package \ No newline at end of file +- First release of [[[Component]]] towards Joomla 5 + +# v3.0.3 + +- Removed the not_required field from the sermon model. #36 + +# v3.0.2 + +- Add the HTML class to the site default layout. \ No newline at end of file diff --git a/README.md b/README.md index d5b2c31e..37fc3d72 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# Sermon Distributor (2.1.x) +# Sermon Distributor (5.0.x) ![Sermon Distributor image](https://git.vdm.dev/christian/Joomla-Sermon-Distributor/raw/branch/master/admin/assets/images/vdm-component.jpg "The Sermon Distributor") -Distributor is a highly advanced sermon distributor that runs on the [Joomla 3.x](http://www.joomla.org) framework. You can link a shared folder from Dropbox to the component and use Dropbox as your file host, not to mention the advanced auto builder that gives you the ability to simply load sermons to your website by only adding them to Dropbox. +Distributor is a highly advanced sermon distributor that runs on the [Joomla 4.x & 5.x](http://www.joomla.org) framework. You can link a shared folder from Dropbox to the component and use Dropbox as your file host, not to mention the advanced auto builder that gives you the ability to simply load sermons to your website by only adding them to Dropbox. The best way to see all your options is to install this component on you Joomla website and test all features yourself. Here is a [direct download link](https://git.vdm.dev/christian/Joomla-Sermon-Distributor/archive/master.zip) @@ -24,38 +24,38 @@ The best way to see all your options is to install this component on you Joomla + *Author*: [Llewellyn van der Merwe](mailto:joomla@vdm.io) + *Name*: [Sermon Distributor](https://www.vdm.io/) + *First Build*: 22nd October, 2015 -+ *Last Build*: 29th May, 2023 -+ *Version*: 2.1.x ++ *Last Build*: 2nd March, 2024 ++ *Version*: 5.0.x + *Copyright*: Copyright (C) 2015. All Rights Reserved + *License*: GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html ## Build Time :hourglass: -**210 Hours** or **26 Eight Hour Days** (actual time the author saved - +**245 Hours** or **31 Eight Hour Days** (actual time the author saved - due to [Automated Component Builder](https://www.joomlacomponentbuilder.com)) > (if creating a folder and file took **5 seconds** and writing one line of code took **10 seconds**, > never making one mistake or taking any coffee break.) -+ *Line count*: **75271** -+ *File count*: **486** -+ *Folder count*: **105** ++ *Line count*: **87679** ++ *File count*: **575** ++ *Folder count*: **120** -**138 Hours** or **18 Eight Hour Days** (the actual time the author spent) +**161 Hours** or **20 Eight Hour Days** (the actual time the author spent) > (with the following break down: -> **debugging @52hours** = codingtime / 4; -> **planning @30hours** = codingtime / 7; -> **mapping @21hours** = codingtime / 10; -> **office @35hours** = codingtime / 6;) +> **debugging @61hours** = codingtime / 4; +> **planning @35hours** = codingtime / 7; +> **mapping @24hours** = codingtime / 10; +> **office @41hours** = codingtime / 6;) -**348 Hours** or **44 Eight Hour Days** +**406 Hours** or **51 Eight Hour Days** (a total of the realistic time frame for this project) > (if creating a folder and file took **5 seconds** and writing one line of code took **10 seconds**, > with the normal everyday realities at the office, that includes the component planning, mapping & debugging.) -Project duration: **8.8 weeks** or **1.8 months** +Project duration: **10.2 weeks** or **2.1 months** > This **component** was build with a Joomla [Automated Component Builder](https://www.joomlacomponentbuilder.com). -> Developed by [Llewellyn van der Merwe](mailto:llewellyn@joomlacomponentbuilder.com) \ No newline at end of file +> Developed by [Llewellyn van der Merwe](mailto:joomla@vdm.io) \ No newline at end of file diff --git a/SermondistributorInstallerScript.php b/SermondistributorInstallerScript.php new file mode 100644 index 00000000..ffee91d0 --- /dev/null +++ b/SermondistributorInstallerScript.php @@ -0,0 +1,1731 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Filesystem\File; +use Joomla\CMS\Installer\InstallerAdapter; +use Joomla\CMS\Installer\InstallerScriptInterface; +use Joomla\CMS\Application\CMSApplication; +use Joomla\CMS\Log\Log; +use Joomla\CMS\Version; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\Filesystem\Folder; +use Joomla\Database\DatabaseInterface; + +// No direct access to this file +defined('_JEXEC') or die; + +/** + * Script File of Sermondistributor Component + * + * @since 3.6 + */ +class Com_SermondistributorInstallerScript implements InstallerScriptInterface +{ + /** + * The CMS Application. + * + * @var CMSApplication + * @since 4.4.2 + */ + protected CMSApplication $app; + + /** + * The database class. + * + * @since 4.4.2 + */ + protected $db; + + /** + * The version number of the extension. + * + * @var string + * @since 3.6 + */ + protected $release; + + /** + * The table the parameters are stored in. + * + * @var string + * @since 3.6 + */ + protected $paramTable; + + /** + * The extension name. This should be set in the installer script. + * + * @var string + * @since 3.6 + */ + protected $extension; + + /** + * A list of files to be deleted + * + * @var array + * @since 3.6 + */ + protected $deleteFiles = []; + + /** + * A list of folders to be deleted + * + * @var array + * @since 3.6 + */ + protected $deleteFolders = []; + + /** + * A list of CLI script files to be copied to the cli directory + * + * @var array + * @since 3.6 + */ + protected $cliScriptFiles = []; + + /** + * Minimum PHP version required to install the extension + * + * @var string + * @since 3.6 + */ + protected $minimumPhp; + + /** + * Minimum Joomla! version required to install the extension + * + * @var string + * @since 3.6 + */ + protected $minimumJoomla; + + /** + * Extension script constructor. + * + * @since 3.0.0 + */ + public function __construct() + { + $this->minimumJoomla = '4.3'; + $this->minimumPhp = JOOMLA_MINIMUM_PHP; + $this->app ??= Factory::getApplication(); + $this->db = Factory::getContainer()->get(DatabaseInterface::class); + + // check if the files exist + if (is_file(JPATH_ROOT . '/administrator/components/com_sermondistributor/sermondistributor.php')) + { + // remove Joomla 3 files + $this->deleteFiles = [ + '/administrator/components/com_sermondistributor/sermondistributor.php', + '/administrator/components/com_sermondistributor/controller.php', + '/components/com_sermondistributor/sermondistributor.php', + '/components/com_sermondistributor/controller.php', + '/components/com_sermondistributor/router.php', + ]; + } + + // check if the Folders exist + if (is_dir(JPATH_ROOT . '/administrator/components/com_sermondistributor/modules')) + { + // remove Joomla 3 folder + $this->deleteFolders = [ + '/administrator/components/com_sermondistributor/controllers', + '/administrator/components/com_sermondistributor/helpers', + '/administrator/components/com_sermondistributor/modules', + '/administrator/components/com_sermondistributor/tables', + '/administrator/components/com_sermondistributor/views', + '/components/com_sermondistributor/controllers', + '/components/com_sermondistributor/helpers', + '/components/com_sermondistributor/modules', + '/components/com_sermondistributor/views', + ]; + } + } + + /** + * Function called after the extension is installed. + * + * @param InstallerAdapter $adapter The adapter calling this method + * + * @return boolean True on success + * + * @since 4.2.0 + */ + public function install(InstallerAdapter $adapter): bool {return true;} + + /** + * Function called after the extension is updated. + * + * @param InstallerAdapter $adapter The adapter calling this method + * + * @return boolean True on success + * + * @since 4.2.0 + */ + public function update(InstallerAdapter $adapter): bool {return true;} + + /** + * Function called after the extension is uninstalled. + * + * @param InstallerAdapter $adapter The adapter calling this method + * + * @return boolean True on success + * + * @since 4.2.0 + */ + public function uninstall(InstallerAdapter $adapter): bool + { + // Remove Related Component Data. + + // Remove Preacher Data + $this->removeViewData("com_sermondistributor.preacher"); + + // Remove Sermon Data + $this->removeViewData("com_sermondistributor.sermon"); + + // Remove Sermon catid Data + $this->removeViewData("com_sermondistributor.sermon.category"); + + // Remove Series Data + $this->removeViewData("com_sermondistributor.series"); + + // Remove Statistic Data + $this->removeViewData("com_sermondistributor.statistic"); + + // Remove External source Data + $this->removeViewData("com_sermondistributor.external_source"); + + // Remove Local listing Data + $this->removeViewData("com_sermondistributor.local_listing"); + + // Remove Help document Data + $this->removeViewData("com_sermondistributor.help_document"); + + // Remove Asset Data. + $this->removeAssetData(); + + // Revert the assets table rules column back to the default. + $this->removeDatabaseAssetsRulesFix(); + + // Remove component from action logs extensions table. + $this->removeActionLogsExtensions(); + + // Remove Preacher from action logs config table. + $this->removeActionLogConfig('com_sermondistributor.preacher'); + + // Remove Sermon from action logs config table. + $this->removeActionLogConfig('com_sermondistributor.sermon'); + + // Remove Series from action logs config table. + $this->removeActionLogConfig('com_sermondistributor.series'); + + // Remove Statistic from action logs config table. + $this->removeActionLogConfig('com_sermondistributor.statistic'); + + // Remove External_source from action logs config table. + $this->removeActionLogConfig('com_sermondistributor.external_source'); + + // Remove Local_listing from action logs config table. + $this->removeActionLogConfig('com_sermondistributor.local_listing'); + + // Remove Help_document from action logs config table. + $this->removeActionLogConfig('com_sermondistributor.help_document'); + // little notice as after service, in case of bad experience with component. + echo '
+

Did something go wrong? Are you disappointed?

+

Please let me know at joomla@vdm.io. +
We at Vast Development Method are committed to building extensions that performs proficiently! You can help us, really! +
Send me your thoughts on improvements that is needed, trust me, I will be very grateful! +
Visit us at https://www.vdm.io/ today!

'; + + return true; + } + + /** + * Function called before extension installation/update/removal procedure commences. + * + * @param string $type The type of change (install or discover_install, update, uninstall) + * @param InstallerAdapter $adapter The adapter calling this method + * + * @return boolean True on success + * + * @since 4.2.0 + */ + public function preflight(string $type, InstallerAdapter $adapter): bool + { + // Check for the minimum PHP version before continuing + if (!empty($this->minimumPhp) && version_compare(PHP_VERSION, $this->minimumPhp, '<')) + { + Log::add(Text::sprintf('JLIB_INSTALLER_MINIMUM_PHP', $this->minimumPhp), Log::WARNING, 'jerror'); + + return false; + } + + // Check for the minimum Joomla version before continuing + if (!empty($this->minimumJoomla) && version_compare(JVERSION, $this->minimumJoomla, '<')) + { + Log::add(Text::sprintf('JLIB_INSTALLER_MINIMUM_JOOMLA', $this->minimumJoomla), Log::WARNING, 'jerror'); + + return false; + } + + // Extension manifest file version + $this->extension = $adapter->getName(); + $this->release = $adapter->getManifest()->version; + + // do any updates needed + if ($type === 'update') + { + } + + // do any install needed + if ($type === 'install') + { + } + + return true; + } + + /** + * Function called after extension installation/update/removal procedure commences. + * + * @param string $type The type of change (install or discover_install, update, uninstall) + * @param InstallerAdapter $adapter The adapter calling this method + * + * @return boolean True on success + * + * @since 4.2.0 + */ + public function postflight(string $type, InstallerAdapter $adapter): bool + { + // We check if we have dynamic folders to copy + $this->moveFolders($adapter); + + // set the default component settings + if ($type === 'install') + { + + // Install Preacher Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Preacher', + // typeAlias + 'com_sermondistributor.preacher', + // table + '{"special": {"dbtable": "#__sermondistributor_preacher","key": "id","type": "PreacherTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "name","core_state": "published","core_alias": "alias","core_created_time": "created","core_modified_time": "modified","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"name":"name","description":"description","website":"website","email":"email","icon":"icon","alias":"alias"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/preacher.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits"],"displayLookup": [{"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"}]}' + ); + // Install Sermon Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Sermon', + // typeAlias + 'com_sermondistributor.sermon', + // table + '{"special": {"dbtable": "#__sermondistributor_sermon","key": "id","type": "SermonTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "name","core_state": "published","core_alias": "alias","core_created_time": "created","core_modified_time": "modified","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "catid","core_xreference": "null","asset_id": "asset_id"},"special": {"name":"name","preacher":"preacher","series":"series","short_description":"short_description","link_type":"link_type","source":"source","local_files":"local_files","alias":"alias","description":"description","tags":"tags","icon":"icon","build":"build","manual_files":"manual_files","auto_sermons":"auto_sermons","url":"url","scripture":"scripture"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/sermon.xml","hideFields": ["asset_id","checked_out","checked_out_time","auto_sermons"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","preacher","series","catid","link_type","source","build"],"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"},{"sourceColumn": "preacher","targetTable": "#__sermondistributor_preacher","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "series","targetTable": "#__sermondistributor_series","targetColumn": "id","displayColumn": "name"}]}' + ); + // Install Sermon category Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Sermon Catid', + // typeAlias + 'com_sermondistributor.sermon.category', + // table + '{"special":{"dbtable":"#__categories","key":"id","type":"Category","prefix":"JTable","config":"array()"},"common":{"dbtable":"#__ucm_content","key":"ucm_id","type":"Corecontent","prefix":"JTable","config":"array()"}}', + // rules + '', + // fieldMappings + '{"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"}}', + // router + '', + // contentHistoryOptions + '{"formFile":"administrator\/components\/com_categories\/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", "hits", "path"],"convertToInt":["publish_up", "publish_down"], "displayLookup":[{"sourceColumn":"created_user_id","targetTable":"#__users","targetColumn":"id","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"}]}' + ); + // Install Series Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Series', + // typeAlias + 'com_sermondistributor.series', + // table + '{"special": {"dbtable": "#__sermondistributor_series","key": "id","type": "SeriesTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "name","core_state": "published","core_alias": "alias","core_created_time": "created","core_modified_time": "modified","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"name":"name","description":"description","scripture":"scripture","icon":"icon","alias":"alias"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/series.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits"],"displayLookup": [{"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"}]}' + ); + // Install Statistic Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Statistic', + // typeAlias + 'com_sermondistributor.statistic', + // table + '{"special": {"dbtable": "#__sermondistributor_statistic","key": "id","type": "StatisticTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "filename","core_state": "published","core_alias": "null","core_created_time": "created","core_modified_time": "modified","core_body": "null","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"filename":"filename","sermon":"sermon","preacher":"preacher","series":"series","counter":"counter"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/statistic.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","sermon","preacher","series","counter"],"displayLookup": [{"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"},{"sourceColumn": "sermon","targetTable": "#__sermondistributor_sermon","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "preacher","targetTable": "#__sermondistributor_preacher","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "series","targetTable": "#__sermondistributor_series","targetColumn": "id","displayColumn": "name"}]}' + ); + // Install External source Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor External_source', + // typeAlias + 'com_sermondistributor.external_source', + // table + '{"special": {"dbtable": "#__sermondistributor_external_source","key": "id","type": "External_sourceTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "description","core_state": "published","core_alias": "null","core_created_time": "created","core_modified_time": "modified","core_body": "null","core_hits": "hits","core_publish_up": "null","core_publish_down": "null","core_access": "null","core_params": "params","core_featured": "null","core_metadata": "null","core_language": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "null","core_metadesc": "null","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"description":"description","externalsources":"externalsources","update_method":"update_method","filetypes":"filetypes","build":"build","not_required":"not_required","update_timer":"update_timer","dropboxoptions":"dropboxoptions","permissiontype":"permissiontype","oauthtoken":"oauthtoken"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/external_source.xml","hideFields": ["asset_id","checked_out","checked_out_time","not_required"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","externalsources","update_method","build","not_required","update_timer","dropboxoptions"],"displayLookup": [{"sourceColumn": "created_by","targetTable": "#__users","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "modified_by","targetTable": "#__users","targetColumn": "id","displayColumn": "name"}]}' + ); + // Install Local listing Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Local_listing', + // typeAlias + 'com_sermondistributor.local_listing', + // table + '{"special": {"dbtable": "#__sermondistributor_local_listing","key": "id","type": "Local_listingTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "name","core_state": "published","core_alias": "null","core_created_time": "created","core_modified_time": "modified","core_body": "null","core_hits": "hits","core_publish_up": "null","core_publish_down": "null","core_access": "null","core_params": "params","core_featured": "null","core_metadata": "null","core_language": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "null","core_metadesc": "null","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"name":"name","build":"build","size":"size","external_source":"external_source","key":"key","url":"url"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/local_listing.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","build","size","external_source"],"displayLookup": [{"sourceColumn": "created_by","targetTable": "#__users","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "modified_by","targetTable": "#__users","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "external_source","targetTable": "#__sermondistributor_external_source","targetColumn": "id","displayColumn": "description"}]}' + ); + // Install Help document Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Help_document', + // typeAlias + 'com_sermondistributor.help_document', + // table + '{"special": {"dbtable": "#__sermondistributor_help_document","key": "id","type": "Help_documentTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "title","core_state": "published","core_alias": "alias","core_created_time": "created","core_modified_time": "modified","core_body": "content","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"title":"title","type":"type","groups":"groups","location":"location","admin_view":"admin_view","site_view":"site_view","alias":"alias","content":"content","article":"article","url":"url","target":"target"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/help_document.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","type","location","article","target"],"displayLookup": [{"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"},{"sourceColumn": "article","targetTable": "#__content","targetColumn": "id","displayColumn": "title"}]}' + ); + + + // Fix the assets table rules column size. + $this->setDatabaseAssetsRulesFix(22240, "TEXT"); + // Install the global extension assets permission. + $this->setAssetsRules( + '{"site.preachers.access":{"1":1},"site.preacher.access":{"1":1},"site.categories.access":{"1":1},"site.category.access":{"1":1},"site.serieslist.access":{"1":1},"site.series.access":{"1":1},"site.sermon.access":{"1":1}}' + ); + + // Install the global extension params. + $this->setExtensionsParams( + '{"autorName":"Llewellyn van der Merwe","autorEmail":"joomla@vdm.io","player":"1","add_to_button":"0","preachers_display":"2","preachers_list_style":"2","preachers_table_color":"0","preachers_icon":"1","preachers_desc":"1","preachers_sermon_count":"1","preachers_hits":"1","preachers_website":"1","preachers_email":"1","preacher_request_id":"0","preacher_display":"3","preacher_box_contrast":"1","preacher_list_style":"3","preacher_icon":"1","preacher_desc":"1","preacher_sermon_count":"1","preacher_hits":"1","preacher_email":"1","preacher_website":"1","preacher_sermons_display":"2","preacher_sermons_list_style":"2","preacher_sermons_table_color":"0","preacher_sermons_icon":"1","preacher_sermons_desc":"1","preacher_sermons_series":"1","preacher_sermons_category":"1","preacher_sermons_download_counter":"1","preacher_sermons_hits":"1","preacher_sermons_downloads":"1","preacher_sermons_open":"1","categories_display":"2","categories_list_style":"2","categories_table_color":"0","categories_icon":"1","categories_desc":"1","categories_sermon_count":"1","categories_hits":"1","category_display":"3","category_box_contrast":"1","category_list_style":"3","category_icon":"1","category_desc":"1","category_sermon_count":"1","category_hits":"1","category_sermons_display":"2","category_sermons_list_style":"1","category_sermons_table_color":"1","category_sermons_icon":"1","category_sermons_desc":"1","category_sermons_preacher":"1","category_sermons_series":"1","category_sermons_download_counter":"1","category_sermons_hits":"1","category_sermons_downloads":"1","category_sermons_open":"1","list_series_display":"2","list_series_list_style":"2","list_series_table_color":"0","list_series_icon":"1","list_series_desc":"1","list_series_sermon_count":"1","list_series_hits":"1","series_request_id":"0","series_display":"3","series_box_contrast":"1","series_list_style":"3","series_icon":"1","series_desc":"1","series_sermon_count":"1","series_hits":"1","series_sermons_display":"2","series_sermons_list_style":"1","series_sermons_table_color":"1","series_sermons_icon":"1","series_sermons_desc":"1","series_sermons_preacher":"1","series_sermons_category":"1","series_sermons_download_counter":"1","series_sermons_hits":"1","series_sermons_downloads":"1","series_sermons_open":"1","sermon_display":"1","sermon_box_contrast":"1","sermon_list_style":"1","sermon_icon":"1","sermon_desc":"1","sermon_preacher":"1","sermon_series":"1","sermon_category":"1","sermon_download_counter":"1","sermon_hits":"1","sermon_downloads":"1","max_execution_time":"500","check_in":"-1 day","save_history":"1","history_limit":"10","add_jquery_framework":"1","uikit_load":"1","uikit_min":""}' + ); + + + echo '
+ +
'; + + // Add component to the action logs extensions table. + $this->setActionLogsExtensions(); + + // Add Preacher to the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'PREACHER', + // typeAlias + 'com_sermondistributor.preacher', + // idHolder + 'id', + // titleHolder + 'name', + // tableName + '#__sermondistributor_preacher', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add Sermon to the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'SERMON', + // typeAlias + 'com_sermondistributor.sermon', + // idHolder + 'id', + // titleHolder + 'name', + // tableName + '#__sermondistributor_sermon', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add Series to the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'SERIES', + // typeAlias + 'com_sermondistributor.series', + // idHolder + 'id', + // titleHolder + 'name', + // tableName + '#__sermondistributor_series', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add Statistic to the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'STATISTIC', + // typeAlias + 'com_sermondistributor.statistic', + // idHolder + 'id', + // titleHolder + 'filename', + // tableName + '#__sermondistributor_statistic', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add External_source to the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'EXTERNAL_SOURCE', + // typeAlias + 'com_sermondistributor.external_source', + // idHolder + 'id', + // titleHolder + 'description', + // tableName + '#__sermondistributor_external_source', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add Local_listing to the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'LOCAL_LISTING', + // typeAlias + 'com_sermondistributor.local_listing', + // idHolder + 'id', + // titleHolder + 'name', + // tableName + '#__sermondistributor_local_listing', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add Help_document to the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'HELP_DOCUMENT', + // typeAlias + 'com_sermondistributor.help_document', + // idHolder + 'id', + // titleHolder + 'title', + // tableName + '#__sermondistributor_help_document', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + } + + // do any updates needed + if ($type === 'update') + { + + // Update Preacher Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Preacher', + // typeAlias + 'com_sermondistributor.preacher', + // table + '{"special": {"dbtable": "#__sermondistributor_preacher","key": "id","type": "PreacherTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "name","core_state": "published","core_alias": "alias","core_created_time": "created","core_modified_time": "modified","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"name":"name","description":"description","website":"website","email":"email","icon":"icon","alias":"alias"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/preacher.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits"],"displayLookup": [{"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"}]}' + ); + // Update Sermon Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Sermon', + // typeAlias + 'com_sermondistributor.sermon', + // table + '{"special": {"dbtable": "#__sermondistributor_sermon","key": "id","type": "SermonTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "name","core_state": "published","core_alias": "alias","core_created_time": "created","core_modified_time": "modified","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "catid","core_xreference": "null","asset_id": "asset_id"},"special": {"name":"name","preacher":"preacher","series":"series","short_description":"short_description","link_type":"link_type","source":"source","local_files":"local_files","alias":"alias","description":"description","tags":"tags","icon":"icon","build":"build","manual_files":"manual_files","auto_sermons":"auto_sermons","url":"url","scripture":"scripture"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/sermon.xml","hideFields": ["asset_id","checked_out","checked_out_time","auto_sermons"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","preacher","series","catid","link_type","source","build"],"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"},{"sourceColumn": "preacher","targetTable": "#__sermondistributor_preacher","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "series","targetTable": "#__sermondistributor_series","targetColumn": "id","displayColumn": "name"}]}' + ); + // Update Sermon category Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Sermon Catid', + // typeAlias + 'com_sermondistributor.sermon.category', + // table + '{"special":{"dbtable":"#__categories","key":"id","type":"Category","prefix":"JTable","config":"array()"},"common":{"dbtable":"#__ucm_content","key":"ucm_id","type":"Corecontent","prefix":"JTable","config":"array()"}}', + // rules + '', + // fieldMappings + '{"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"}}', + // router + '', + // contentHistoryOptions + '{"formFile":"administrator\/components\/com_categories\/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", "hits", "path"],"convertToInt":["publish_up", "publish_down"], "displayLookup":[{"sourceColumn":"created_user_id","targetTable":"#__users","targetColumn":"id","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"}]}' + ); + // Update Series Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Series', + // typeAlias + 'com_sermondistributor.series', + // table + '{"special": {"dbtable": "#__sermondistributor_series","key": "id","type": "SeriesTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "name","core_state": "published","core_alias": "alias","core_created_time": "created","core_modified_time": "modified","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"name":"name","description":"description","scripture":"scripture","icon":"icon","alias":"alias"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/series.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits"],"displayLookup": [{"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"}]}' + ); + // Update Statistic Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Statistic', + // typeAlias + 'com_sermondistributor.statistic', + // table + '{"special": {"dbtable": "#__sermondistributor_statistic","key": "id","type": "StatisticTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "filename","core_state": "published","core_alias": "null","core_created_time": "created","core_modified_time": "modified","core_body": "null","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"filename":"filename","sermon":"sermon","preacher":"preacher","series":"series","counter":"counter"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/statistic.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","sermon","preacher","series","counter"],"displayLookup": [{"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"},{"sourceColumn": "sermon","targetTable": "#__sermondistributor_sermon","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "preacher","targetTable": "#__sermondistributor_preacher","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "series","targetTable": "#__sermondistributor_series","targetColumn": "id","displayColumn": "name"}]}' + ); + // Update External source Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor External_source', + // typeAlias + 'com_sermondistributor.external_source', + // table + '{"special": {"dbtable": "#__sermondistributor_external_source","key": "id","type": "External_sourceTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "description","core_state": "published","core_alias": "null","core_created_time": "created","core_modified_time": "modified","core_body": "null","core_hits": "hits","core_publish_up": "null","core_publish_down": "null","core_access": "null","core_params": "params","core_featured": "null","core_metadata": "null","core_language": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "null","core_metadesc": "null","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"description":"description","externalsources":"externalsources","update_method":"update_method","filetypes":"filetypes","build":"build","not_required":"not_required","update_timer":"update_timer","dropboxoptions":"dropboxoptions","permissiontype":"permissiontype","oauthtoken":"oauthtoken"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/external_source.xml","hideFields": ["asset_id","checked_out","checked_out_time","not_required"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","externalsources","update_method","build","not_required","update_timer","dropboxoptions"],"displayLookup": [{"sourceColumn": "created_by","targetTable": "#__users","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "modified_by","targetTable": "#__users","targetColumn": "id","displayColumn": "name"}]}' + ); + // Update Local listing Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Local_listing', + // typeAlias + 'com_sermondistributor.local_listing', + // table + '{"special": {"dbtable": "#__sermondistributor_local_listing","key": "id","type": "Local_listingTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "name","core_state": "published","core_alias": "null","core_created_time": "created","core_modified_time": "modified","core_body": "null","core_hits": "hits","core_publish_up": "null","core_publish_down": "null","core_access": "null","core_params": "params","core_featured": "null","core_metadata": "null","core_language": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "null","core_metadesc": "null","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"name":"name","build":"build","size":"size","external_source":"external_source","key":"key","url":"url"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/local_listing.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","build","size","external_source"],"displayLookup": [{"sourceColumn": "created_by","targetTable": "#__users","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "modified_by","targetTable": "#__users","targetColumn": "id","displayColumn": "name"},{"sourceColumn": "external_source","targetTable": "#__sermondistributor_external_source","targetColumn": "id","displayColumn": "description"}]}' + ); + // Update Help document Content Types. + $this->setContentType( + // typeTitle + 'Sermondistributor Help_document', + // typeAlias + 'com_sermondistributor.help_document', + // table + '{"special": {"dbtable": "#__sermondistributor_help_document","key": "id","type": "Help_documentTable","prefix": "TrueChristianChurch\Component\Sermondistributor\Administrator\Table"}}', + // rules + '', + // fieldMappings + '{"common": {"core_content_item_id": "id","core_title": "title","core_state": "published","core_alias": "alias","core_created_time": "created","core_modified_time": "modified","core_body": "content","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": "null","core_images": "null","core_urls": "null","core_version": "version","core_ordering": "ordering","core_metakey": "metakey","core_metadesc": "metadesc","core_catid": "null","core_xreference": "null","asset_id": "asset_id"},"special": {"title":"title","type":"type","groups":"groups","location":"location","admin_view":"admin_view","site_view":"site_view","alias":"alias","content":"content","article":"article","url":"url","target":"target"}}', + // router + '', + // contentHistoryOptions + '{"formFile": "administrator/components/com_sermondistributor/forms/help_document.xml","hideFields": ["asset_id","checked_out","checked_out_time"],"ignoreChanges": ["modified_by","modified","checked_out","checked_out_time","version","hits"],"convertToInt": ["published","ordering","version","hits","type","location","article","target"],"displayLookup": [{"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"},{"sourceColumn": "article","targetTable": "#__content","targetColumn": "id","displayColumn": "title"}]}' + ); + + + + echo '
+ + +

Upgrade to Version 5.0.0-beta1 Was Successful! Let us know if anything is not working as expected.

'; + + // Add/Update component in the action logs extensions table. + $this->setActionLogsExtensions(); + + // Add/Update Preacher in the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'PREACHER', + // typeAlias + 'com_sermondistributor.preacher', + // idHolder + 'id', + // titleHolder + 'name', + // tableName + '#__sermondistributor_preacher', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add/Update Sermon in the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'SERMON', + // typeAlias + 'com_sermondistributor.sermon', + // idHolder + 'id', + // titleHolder + 'name', + // tableName + '#__sermondistributor_sermon', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add/Update Series in the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'SERIES', + // typeAlias + 'com_sermondistributor.series', + // idHolder + 'id', + // titleHolder + 'name', + // tableName + '#__sermondistributor_series', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add/Update Statistic in the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'STATISTIC', + // typeAlias + 'com_sermondistributor.statistic', + // idHolder + 'id', + // titleHolder + 'filename', + // tableName + '#__sermondistributor_statistic', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add/Update External_source in the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'EXTERNAL_SOURCE', + // typeAlias + 'com_sermondistributor.external_source', + // idHolder + 'id', + // titleHolder + 'description', + // tableName + '#__sermondistributor_external_source', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add/Update Local_listing in the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'LOCAL_LISTING', + // typeAlias + 'com_sermondistributor.local_listing', + // idHolder + 'id', + // titleHolder + 'name', + // tableName + '#__sermondistributor_local_listing', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + + // Add/Update Help_document in the action logs config table. + $this->setActionLogConfig( + // typeTitle + 'HELP_DOCUMENT', + // typeAlias + 'com_sermondistributor.help_document', + // idHolder + 'id', + // titleHolder + 'title', + // tableName + '#__sermondistributor_help_document', + // textPrefix + 'COM_SERMONDISTRIBUTOR' + ); + } + + // move CLI files + $this->moveCliFiles(); + + // remove old files and folders + $this->removeFiles(); + + return true; + } + + /** + * Remove the files and folders in the given array from + * + * @return void + * + * @since 3.6 + */ + protected function removeFiles() + { + if (!empty($this->deleteFiles)) + { + foreach ($this->deleteFiles as $file) + { + if (is_file(JPATH_ROOT . $file) && !File::delete(JPATH_ROOT . $file)) + { + echo Text::sprintf('JLIB_INSTALLER_ERROR_FILE_FOLDER', $file) . '
'; + } + } + } + + if (!empty($this->deleteFolders)) + { + foreach ($this->deleteFolders as $folder) + { + if (is_dir(JPATH_ROOT . $folder) && !Folder::delete(JPATH_ROOT . $folder)) + { + echo Text::sprintf('JLIB_INSTALLER_ERROR_FILE_FOLDER', $folder) . '
'; + } + } + } + } + + /** + * Moves the CLI scripts into the CLI folder in the CMS + * + * @return void + * + * @since 3.6 + */ + protected function moveCliFiles() + { + if (!empty($this->cliScriptFiles)) + { + foreach ($this->cliScriptFiles as $file) + { + $name = basename($file); + + if (file_exists(JPATH_ROOT . $file) && !File::move(JPATH_ROOT . $file, JPATH_ROOT . '/cli/' . $name)) + { + echo Text::sprintf('JLIB_INSTALLER_FILE_ERROR_MOVE', $name); + } + } + } + } + + /** + * Set content type integration + * + * @param string $typeTitle + * @param string $typeAlias + * @param string $table + * @param string $rules + * @param string $fieldMappings + * @param string $router + * @param string $contentHistoryOptions + * + * @return void + * @since 4.4.2 + */ + protected function setContentType( + string $typeTitle, + string $typeAlias, + string $table, + string $rules, + string $fieldMappings, + string $router, + string $contentHistoryOptions): void + { + // Create the content type object. + $content = new stdClass(); + $content->type_title = $typeTitle; + $content->type_alias = $typeAlias; + $content->table = $table; + $content->rules = $rules; + $content->field_mappings = $fieldMappings; + $content->router = $router; + $content->content_history_options = $contentHistoryOptions; + + // Check if content type is already in content_type DB. + $query = $this->db->getQuery(true); + $query->select($this->db->quoteName(array('type_id'))); + $query->from($this->db->quoteName('#__content_types')); + $query->where($this->db->quoteName('type_alias') . ' LIKE '. $this->db->quote($content->type_alias)); + + $this->db->setQuery($query); + $this->db->execute(); + + // Check if the type alias is already in the content types table. + if ($this->db->getNumRows()) + { + $content->type_id = $this->db->loadResult(); + if ($this->db->updateObject('#__content_types', $content, 'type_id')) + { + // If its successfully update. + $this->app->enqueueMessage( + Text::sprintf('The (%s) was found in the #__content_types table, and updated.', $content->type_alias) + ); + } + } + elseif ($this->db->insertObject('#__content_types', $content)) + { + // If its successfully added. + $this->app->enqueueMessage( + Text::sprintf('The (%s) was added to the #__content_types table.', $content->type_alias) + ); + } + } + + /** + * Set action log config integration + * + * @param string $typeTitle + * @param string $typeAlias + * @param string $idHolder + * @param string $titleHolder + * @param string $tableName + * @param string $textPrefix + * + * @return void + * @since 4.4.2 + */ + protected function setActionLogConfig( + string $typeTitle, + string $typeAlias, + string $idHolder, + string $titleHolder, + string $tableName, + string $textPrefix): void + { + // Create the content action log config object. + $content = new stdClass(); + $content->type_title = $typeTitle; + $content->type_alias = $typeAlias; + $content->id_holder = $idHolder; + $content->title_holder = $titleHolder; + $content->table_name = $tableName; + $content->text_prefix = $textPrefix; + + // Check if the action log config is already in action_log_config DB. + $query = $this->db->getQuery(true); + $query->select($this->db->quoteName(['id'])); + $query->from($this->db->quoteName('#__action_log_config')); + $query->where($this->db->quoteName('type_alias') . ' LIKE '. $this->db->quote($content->type_alias)); + + $this->db->setQuery($query); + $this->db->execute(); + + // Check if the type alias is already in the action log config table. + if ($this->db->getNumRows()) + { + $content->id = $this->db->loadResult(); + if ($this->db->updateObject('#__action_log_config', $content, 'id')) + { + // If its successfully update. + $this->app->enqueueMessage( + Text::sprintf('The (%s) was found in the #__action_log_config table, and updated.', $content->type_alias) + ); + } + } + elseif ($this->db->insertObject('#__action_log_config', $content)) + { + // If its successfully added. + $this->app->enqueueMessage( + Text::sprintf('The (%s) was added to the #__action_log_config table.', $content->type_alias) + ); + } + } + + /** + * Set action logs extensions integration + * + * @return void + * @since 4.4.2 + */ + protected function setActionLogsExtensions(): void + { + // Create the extension action logs object. + $data = new stdClass(); + $data->extension = 'com_sermondistributor'; + + // Check if sermondistributor action log extension is already in action logs extensions DB. + $query = $this->db->getQuery(true); + $query->select($this->db->quoteName(['id'])); + $query->from($this->db->quoteName('#__action_logs_extensions')); + $query->where($this->db->quoteName('extension') . ' = '. $this->db->quote($data->extension)); + + $this->db->setQuery($query); + $this->db->execute(); + + // Set the object into the action logs extensions table if not found. + if ($this->db->getNumRows()) + { + // If its already set don't set it again. + $this->app->enqueueMessage( + Text::_('The (com_sermondistributor) is already in the #__action_logs_extensions table.') + ); + } + elseif ($this->db->insertObject('#__action_logs_extensions', $data)) + { + // give a success message + $this->app->enqueueMessage( + Text::_('The (com_sermondistributor) was successfully added to the #__action_logs_extensions table.') + ); + } + } + + /** + * Set global extension assets permission of this component + * (on install only) + * + * @param string $rules The component rules + * + * @return void + * @since 4.4.2 + */ + protected function setAssetsRules(string $rules): void + { + // Condition. + $conditions = [ + $this->db->quoteName('name') . ' = ' . $this->db->quote('com_sermondistributor') + ]; + + // Field to update. + $fields = [ + $this->db->quoteName('rules') . ' = ' . $this->db->quote($rules), + ]; + + $query = $this->db->getQuery(true); + $query->update( + $this->db->quoteName('#__assets') + )->set($fields)->where($conditions); + + $this->db->setQuery($query); + + $done = $this->db->execute(); + if ($done) + { + // give a success message + $this->app->enqueueMessage( + Text::_('The (com_sermondistributor) rules was successfully added to the #__assets table.') + ); + } + } + + /** + * Set global extension params of this component + * (on install only) + * + * @param string $params The component rules + * + * @return void + * @since 4.4.2 + */ + protected function setExtensionsParams(string $params): void + { + // Condition. + $conditions = [ + $this->db->quoteName('element') . ' = ' . $this->db->quote('com_sermondistributor') + ]; + + // Field to update. + $fields = [ + $this->db->quoteName('params') . ' = ' . $this->db->quote($params), + ]; + + $query = $this->db->getQuery(true); + $query->update( + $this->db->quoteName('#__extensions') + )->set($fields)->where($conditions); + + $this->db->setQuery($query); + + $done = $this->db->execute(); + if ($done) + { + // give a success message + $this->app->enqueueMessage( + Text::_('The (com_sermondistributor) params was successfully added to the #__extensions table.') + ); + } + } + + /** + * Set database fix (if needed) + * => WHY DO WE NEED AN ASSET TABLE FIX? + * https://git.vdm.dev/joomla/Component-Builder/issues/616#issuecomment-12085 + * https://www.mysqltutorial.org/mysql-varchar/ + * https://stackoverflow.com/a/15227917/1429677 + * https://forums.mysql.com/read.php?24,105964,105964 + * + * @param int $accessWorseCase This is the max rules column size com_sermondistributor would needs. + * @param string $dataType This datatype we will change the rules column to if it to small. + * + * @return void + * @since 4.4.2 + */ + protected function setDatabaseAssetsRulesFix(int $accessWorseCase, string $dataType): void + { + // Get the biggest rule column in the assets table at this point. + $length = "SELECT CHAR_LENGTH(`rules`) as rule_size FROM #__assets ORDER BY rule_size DESC LIMIT 1"; + $this->db->setQuery($length); + if ($this->db->execute()) + { + $rule_length = $this->db->loadResult(); + // Check the size of the rules column + if ($rule_length <= $accessWorseCase) + { + // Fix the assets table rules column size + $fix = "ALTER TABLE `#__assets` CHANGE `rules` `rules` {$dataType} NOT NULL COMMENT 'JSON encoded access control. Enlarged to {$dataType} by Sermondistributor';"; + $this->db->setQuery($fix); + + $done = $this->db->execute(); + if ($done) + { + $this->app->enqueueMessage( + Text::sprintf('The #__assets table rules column was resized to the %s datatype for the components possible large permission rules.', $dataType) + ); + } + } + } + } + + /** + * Remove remnant data related to this view + * + * @param string $context The view context + * @param bool $fields The switch to also remove related field data + * + * @return void + * @since 4.4.2 + */ + protected function removeViewData(string $context, bool $fields = false): void + { + $this->removeContentTypes($context); + $this->removeViewHistory($context); + $this->removeUcmContent($context); // this might be obsolete... + $this->removeContentItemTagMap($context); + $this->removeActionLogConfig($context); + + if ($fields) + { + $this->removeFields($context); + $this->removeFieldsGroups($context); + } + } + + /** + * Remove content types related to this view + * + * @param string $context The view context + * + * @return void + * @since 4.4.2 + */ + protected function removeContentTypes(string $context): void + { + // Create a new query object. + $query = $this->db->getQuery(true); + + // Select id from content type table + $query->select($this->db->quoteName('type_id')); + $query->from($this->db->quoteName('#__content_types')); + + // Where Item alias is found + $query->where($this->db->quoteName('type_alias') . ' = '. $this->db->quote($context)); + $this->db->setQuery($query); + + // Execute query to see if alias is found + $this->db->execute(); + $found = $this->db->getNumRows(); + + // Now check if there were any rows + if ($found) + { + // Since there are load the needed item type ids + $ids = $this->db->loadColumn(); + + // Remove Item from the content type table + $condition = [ + $this->db->quoteName('type_alias') . ' = '. $this->db->quote($context) + ]; + + // Create a new query object. + $query = $this->db->getQuery(true); + $query->delete($this->db->quoteName('#__content_types')); + $query->where($condition); + $this->db->setQuery($query); + + // Execute the query to remove Item items + $done = $this->db->execute(); + if ($done) + { + // If successfully remove Item add queued success message. + $this->app->enqueueMessage( + Text::sprintf('The (%s) type alias was removed from the #__content_type table.', $context) + ); + } + + // Make sure that all the items are cleared from DB + $this->removeUcmBase($ids); + } + } + + /** + * Remove fields related to this view + * + * @param string $context The view context + * + * @return void + * @since 4.4.2 + */ + protected function removeFields(string $context): void + { + // Create a new query object. + $query = $this->db->getQuery(true); + + // Select ids from fields + $query->select($this->db->quoteName('id')); + $query->from($this->db->quoteName('#__fields')); + + // Where context is found + $query->where( + $this->db->quoteName('context') . ' = '. $this->db->quote($context) + ); + $this->db->setQuery($query); + + // Execute query to see if context is found + $this->db->execute(); + $found = $this->db->getNumRows(); + + // Now check if there were any rows + if ($found) + { + // Since there are load the needed release_check field ids + $ids = $this->db->loadColumn(); + + // Create a new query object. + $query = $this->db->getQuery(true); + + // Remove context from the field table + $condition = [ + $this->db->quoteName('context') . ' = '. $this->db->quote($context) + ]; + + $query->delete($this->db->quoteName('#__fields')); + $query->where($condition); + + $this->db->setQuery($query); + + // Execute the query to remove release_check items + $done = $this->db->execute(); + if ($done) + { + // If successfully remove context add queued success message. + $this->app->enqueueMessage( + Text::sprintf('The fields with context (%s) was removed from the #__fields table.', $context) + ); + } + + // Make sure that all the field values are cleared from DB + $this->removeFieldsValues($context, $ids); + } + } + + /** + * Remove fields values related to fields + * + * @param string $context The view context + * @param array $ids The view context + * + * @return void + * @since 4.4.2 + */ + protected function removeFieldsValues(string $context, array $ids): void + { + $condition = [ + $this->db->quoteName('field_id') . ' IN ('. implode(',', $ids) .')' + ]; + + // Create a new query object. + $query = $this->db->getQuery(true); + $query->delete($this->db->quoteName('#__fields_values')); + $query->where($condition); + $this->db->setQuery($query); + + // Execute the query to remove field values + $done = $this->db->execute(); + if ($done) + { + // If successfully remove release_check add queued success message. + $this->app->enqueueMessage( + Text::sprintf('The fields values for (%s) was removed from the #__fields_values table.', $context) + ); + } + } + + /** + * Remove fields groups related to fields + * + * @param string $context The view context + * + * @return void + * @since 4.4.2 + */ + protected function removeFieldsGroups(string $context): void + { + // Create a new query object. + $query = $this->db->getQuery(true); + + // Select ids from fields + $query->select($this->db->quoteName('id')); + $query->from($this->db->quoteName('#__fields_groups')); + + // Where context is found + $query->where( + $this->db->quoteName('context') . ' = '. $this->db->quote($context) + ); + $this->db->setQuery($query); + + // Execute query to see if context is found + $this->db->execute(); + $found = $this->db->getNumRows(); + + // Now check if there were any rows + if ($found) + { + // Create a new query object. + $query = $this->db->getQuery(true); + + // Remove context from the field table + $condition = [ + $this->db->quoteName('context') . ' = '. $this->db->quote($context) + ]; + + $query->delete($this->db->quoteName('#__fields_groups')); + $query->where($condition); + + $this->db->setQuery($query); + + // Execute the query to remove release_check items + $done = $this->db->execute(); + if ($done) + { + // If successfully remove context add queued success message. + $this->app->enqueueMessage( + Text::sprintf('The fields with context (%s) was removed from the #__fields_groups table.', $context) + ); + } + } + } + + /** + * Remove history related to this view + * + * @param string $context The view context + * + * @return void + * @since 4.4.2 + */ + protected function removeViewHistory(string $context): void + { + // Remove Item items from the ucm content table + $condition = [ + $this->db->quoteName('item_id') . ' LIKE ' . $this->db->quote($context . '.%') + ]; + + // Create a new query object. + $query = $this->db->getQuery(true); + $query->delete($this->db->quoteName('#__history')); + $query->where($condition); + $this->db->setQuery($query); + + // Execute the query to remove Item items + $done = $this->db->execute(); + if ($done) + { + // If successfully removed Items add queued success message. + $this->app->enqueueMessage( + Text::sprintf('The (%s) items were removed from the #__history table.', $context) + ); + } + } + + /** + * Remove ucm base values related to these IDs + * + * @param array $ids The type ids + * + * @return void + * @since 4.4.2 + */ + protected function removeUcmBase(array $ids): void + { + // Make sure that all the items are cleared from DB + foreach ($ids as $type_id) + { + // Remove Item items from the ucm base table + $condition = [ + $this->db->quoteName('ucm_type_id') . ' = ' . $type_id + ]; + + // Create a new query object. + $query = $this->db->getQuery(true); + $query->delete($this->db->quoteName('#__ucm_base')); + $query->where($condition); + $this->db->setQuery($query); + + // Execute the query to remove Item items + $this->db->execute(); + } + + $this->app->enqueueMessage( + Text::_('All related items was removed from the #__ucm_base table.') + ); + } + + /** + * Remove ucm content values related to this view + * + * @param string $context The view context + * + * @return void + * @since 4.4.2 + */ + protected function removeUcmContent(string $context): void + { + // Remove Item items from the ucm content table + $condition = [ + $this->db->quoteName('core_type_alias') . ' = ' . $this->db->quote($context) + ]; + + // Create a new query object. + $query = $this->db->getQuery(true); + $query->delete($this->db->quoteName('#__ucm_content')); + $query->where($condition); + $this->db->setQuery($query); + + // Execute the query to remove Item items + $done = $this->db->execute(); + if ($done) + { + // If successfully removed Item add queued success message. + $this->app->enqueueMessage( + Text::sprintf('The (%s) type alias was removed from the #__ucm_content table.', $context) + ); + } + } + + /** + * Remove content item tag map related to this view + * + * @param string $context The view context + * + * @return void + * @since 4.4.2 + */ + protected function removeContentItemTagMap(string $context): void + { + // Create a new query object. + $query = $this->db->getQuery(true); + + // Remove Item items from the contentitem tag map table + $condition = [ + $this->db->quoteName('type_alias') . ' = '. $this->db->quote($context) + ]; + + // Create a new query object. + $query = $this->db->getQuery(true); + $query->delete($this->db->quoteName('#__contentitem_tag_map')); + $query->where($condition); + $this->db->setQuery($query); + + // Execute the query to remove Item items + $done = $this->db->execute(); + if ($done) + { + // If successfully remove Item add queued success message. + $this->app->enqueueMessage( + Text::sprintf('The (%s) type alias was removed from the #__contentitem_tag_map table.', $context) + ); + } + } + + /** + * Remove action log config related to this view + * + * @param string $context The view context + * + * @return void + * @since 4.4.2 + */ + protected function removeActionLogConfig(string $context): void + { + // Remove sermondistributor view from the action_log_config table + $condition = [ + $this->db->quoteName('type_alias') . ' = '. $this->db->quote($context) + ]; + + // Create a new query object. + $query = $this->db->getQuery(true); + $query->delete($this->db->quoteName('#__action_log_config')); + $query->where($condition); + $this->db->setQuery($query); + + // Execute the query to remove com_sermondistributor.view + $done = $this->db->execute(); + if ($done) + { + // If successfully removed sermondistributor view add queued success message. + $this->app->enqueueMessage( + Text::sprintf('The (%s) type alias was removed from the #__action_log_config table.', $context) + ); + } + } + + /** + * Remove Asset Table Integrated + * + * @return void + * @since 4.4.2 + */ + protected function removeAssetData(): void + { + // Remove sermondistributor assets from the assets table + $condition = [ + $this->db->quoteName('name') . ' LIKE ' . $this->db->quote('com_sermondistributor.%') + ]; + + // Create a new query object. + $query = $this->db->getQuery(true); + $query->delete($this->db->quoteName('#__assets')); + $query->where($condition); + $this->db->setQuery($query); + $done = $this->db->execute(); + if ($done) + { + // If successfully removed sermondistributor add queued success message. + $this->app->enqueueMessage( + Text::_('All related (com_sermondistributor) items was removed from the #__assets table.') + ); + } + } + + /** + * Remove action logs extensions integrated + * + * @return void + * @since 4.4.2 + */ + protected function removeActionLogsExtensions(): void + { + // Remove sermondistributor from the action_logs_extensions table + $extension = [ + $this->db->quoteName('extension') . ' = ' . $this->db->quote('com_sermondistributor') + ]; + + // Create a new query object. + $query = $this->db->getQuery(true); + $query->delete($this->db->quoteName('#__action_logs_extensions')); + $query->where($extension); + $this->db->setQuery($query); + + // Execute the query to remove sermondistributor + $done = $this->db->execute(); + if ($done) + { + // If successfully remove sermondistributor add queued success message. + $this->app->enqueueMessage( + Text::_('The (com_sermondistributor) extension was removed from the #__action_logs_extensions table.') + ); + } + } + + /** + * Remove remove database fix (if possible) + * + * @return void + * @since 4.4.2 + */ + protected function removeDatabaseAssetsRulesFix(): void + { + // Get the biggest rule column in the assets table at this point. + $length = "SELECT CHAR_LENGTH(`rules`) as rule_size FROM #__assets ORDER BY rule_size DESC LIMIT 1"; + $this->db->setQuery($length); + if ($this->db->execute()) + { + $rule_length = $this->db->loadResult(); + // Check the size of the rules column + if ($rule_length < 5120) + { + // Revert the assets table rules column back to the default + $revert_rule = "ALTER TABLE `#__assets` CHANGE `rules` `rules` varchar(5120) NOT NULL COMMENT 'JSON encoded access control.';"; + $this->db->setQuery($revert_rule); + $this->db->execute(); + + $this->app->enqueueMessage( + Text::_('Reverted the #__assets table rules column back to its default size of varchar(5120).') + ); + } + else + { + $this->app->enqueueMessage( + Text::_('Could not revert the #__assets table rules column back to its default size of varchar(5120), since there is still one or more components that still requires the column to be larger.') + ); + } + } + } + + /** + * Method to move folders into place. + * + * @param InstallerAdapter $adapter The adapter calling this method + * + * @return void + * @since 4.4.2 + */ + protected function moveFolders(InstallerAdapter $adapter): void + { + // get the installation path + $installer = $adapter->getParent(); + $installPath = $installer->getPath('source'); + // get all the folders + $folders = Folder::folders($installPath); + // check if we have folders we may want to copy + $doNotCopy = ['media','admin','site']; // Joomla already deals with these + if (count((array) $folders) > 1) + { + foreach ($folders as $folder) + { + // Only copy if not a standard folders + if (!in_array($folder, $doNotCopy)) + { + // set the source path + $src = $installPath.'/'.$folder; + // set the destination path + $dest = JPATH_ROOT.'/'.$folder; + // now try to copy the folder + if (!Folder::copy($src, $dest, '', true)) + { + $this->app->enqueueMessage('Could not copy '.$folder.' folder into place, please make sure destination is writable!', 'error'); + } + } + } + } + } +} diff --git a/admin/README.txt b/admin/README.txt index d5b2c31e..37fc3d72 100644 --- a/admin/README.txt +++ b/admin/README.txt @@ -1,8 +1,8 @@ -# Sermon Distributor (2.1.x) +# Sermon Distributor (5.0.x) ![Sermon Distributor image](https://git.vdm.dev/christian/Joomla-Sermon-Distributor/raw/branch/master/admin/assets/images/vdm-component.jpg "The Sermon Distributor") -Distributor is a highly advanced sermon distributor that runs on the [Joomla 3.x](http://www.joomla.org) framework. You can link a shared folder from Dropbox to the component and use Dropbox as your file host, not to mention the advanced auto builder that gives you the ability to simply load sermons to your website by only adding them to Dropbox. +Distributor is a highly advanced sermon distributor that runs on the [Joomla 4.x & 5.x](http://www.joomla.org) framework. You can link a shared folder from Dropbox to the component and use Dropbox as your file host, not to mention the advanced auto builder that gives you the ability to simply load sermons to your website by only adding them to Dropbox. The best way to see all your options is to install this component on you Joomla website and test all features yourself. Here is a [direct download link](https://git.vdm.dev/christian/Joomla-Sermon-Distributor/archive/master.zip) @@ -24,38 +24,38 @@ The best way to see all your options is to install this component on you Joomla + *Author*: [Llewellyn van der Merwe](mailto:joomla@vdm.io) + *Name*: [Sermon Distributor](https://www.vdm.io/) + *First Build*: 22nd October, 2015 -+ *Last Build*: 29th May, 2023 -+ *Version*: 2.1.x ++ *Last Build*: 2nd March, 2024 ++ *Version*: 5.0.x + *Copyright*: Copyright (C) 2015. All Rights Reserved + *License*: GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html ## Build Time :hourglass: -**210 Hours** or **26 Eight Hour Days** (actual time the author saved - +**245 Hours** or **31 Eight Hour Days** (actual time the author saved - due to [Automated Component Builder](https://www.joomlacomponentbuilder.com)) > (if creating a folder and file took **5 seconds** and writing one line of code took **10 seconds**, > never making one mistake or taking any coffee break.) -+ *Line count*: **75271** -+ *File count*: **486** -+ *Folder count*: **105** ++ *Line count*: **87679** ++ *File count*: **575** ++ *Folder count*: **120** -**138 Hours** or **18 Eight Hour Days** (the actual time the author spent) +**161 Hours** or **20 Eight Hour Days** (the actual time the author spent) > (with the following break down: -> **debugging @52hours** = codingtime / 4; -> **planning @30hours** = codingtime / 7; -> **mapping @21hours** = codingtime / 10; -> **office @35hours** = codingtime / 6;) +> **debugging @61hours** = codingtime / 4; +> **planning @35hours** = codingtime / 7; +> **mapping @24hours** = codingtime / 10; +> **office @41hours** = codingtime / 6;) -**348 Hours** or **44 Eight Hour Days** +**406 Hours** or **51 Eight Hour Days** (a total of the realistic time frame for this project) > (if creating a folder and file took **5 seconds** and writing one line of code took **10 seconds**, > with the normal everyday realities at the office, that includes the component planning, mapping & debugging.) -Project duration: **8.8 weeks** or **1.8 months** +Project duration: **10.2 weeks** or **2.1 months** > This **component** was build with a Joomla [Automated Component Builder](https://www.joomlacomponentbuilder.com). -> Developed by [Llewellyn van der Merwe](mailto:llewellyn@joomlacomponentbuilder.com) \ No newline at end of file +> Developed by [Llewellyn van der Merwe](mailto:joomla@vdm.io) \ No newline at end of file diff --git a/admin/assets/css/admin.css b/admin/assets/css/admin.css index b5842c4c..a8118ece 100644 --- a/admin/assets/css/admin.css +++ b/admin/assets/css/admin.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage admin.css diff --git a/admin/assets/css/dashboard.css b/admin/assets/css/dashboard.css index 407f3138..6a4cd635 100644 --- a/admin/assets/css/dashboard.css +++ b/admin/assets/css/dashboard.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage dashboard.css @@ -24,153 +24,153 @@ /* CSS Document */ .dashboard-container { - margin-left: 10px; - margin-top: 10px; - width: 100%; + margin-left: 10px; + margin-top: 10px; + width: 100%; } .dashboard-container [class*="span"] { - display: block; - float: none; - margin-left: 0; - width: auto; + display: block; + float: none; + margin-left: 0; + width: auto; } .dashboard-container:before, .dashboard-container:after { - content: ""; - display: table; + content: ""; + display: table; } .dashboard-container:after { - clear: both; + clear: both; } .dashboard-container [class*="span"] { - box-sizing: border-box; - display: block; - float: left; - min-height: 145px; - min-width: 96px; - width: 100%; + box-sizing: border-box; + display: block; + float: left; + min-height: 145px; + min-width: 96px; + width: 100%; } .dashboard-container [class*="span"]:first-child { - margin-left: 0; + margin-left: 0; } .dashboard-wraper { - background: none repeat scroll 0 0 hsl(0, 0%, 93%); - border-radius: 5px; - float: left; - margin: 1%; - padding: 3px; - width: 17%; - min-height: 194px; - min-width: 96px; + background: none repeat scroll 0 0 hsl(0, 0%, 93%); + border-radius: 5px; + float: left; + margin: 1%; + padding: 3px; + width: 17%; + min-height: 194px; + min-width: 96px; } .dashboard-content a { - background: linear-gradient(to bottom, hsl(0, 0%, 100%) 0%, hsl(0, 0%, 96%) 47%, hsl(0, 0%, 93%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); - border: 1px solid hsl(0, 0%, 85%); - border-radius: 4px; - box-shadow: 0 0 3px hsla(0, 0%, 0%, 0.1) inset; - color: hsl(0, 0%, 20%); - display: block; - min-height: 89px; - padding: 10px; - text-align: center; - text-decoration: none; + background: linear-gradient(to bottom, hsl(0, 0%, 100%) 0%, hsl(0, 0%, 96%) 47%, hsl(0, 0%, 93%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); + border: 1px solid hsl(0, 0%, 85%); + border-radius: 4px; + box-shadow: 0 0 3px hsla(0, 0%, 0%, 0.1) inset; + color: hsl(0, 0%, 20%); + display: block; + min-height: 89px; + padding: 10px; + text-align: center; + text-decoration: none; } .dashboard-content a:hover { - background: linear-gradient(to bottom, hsl(0, 0%, 90%) 0%, hsl(0, 0%, 100%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); - color: hsl(200, 100%, 30%); - text-decoration: none; + background: linear-gradient(to bottom, hsl(0, 0%, 90%) 0%, hsl(0, 0%, 100%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); + color: hsl(200, 100%, 30%); + text-decoration: none; } .dashboard-title { - display: block; - padding-top: 5px; + display: block; + padding-top: 5px; } .dashboard-info { - background: linear-gradient(to bottom, hsl(0, 0%, 100%) 0%, hsl(0, 0%, 96%) 47%, hsl(0, 0%, 93%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); - border: 1px solid hsl(0, 0%, 85%); - border-radius: 4px; - box-shadow: 0 0 3px hsla(0, 0%, 0%, 0.1) inset; - color: hsl(0, 0%, 20%); - display: block; - font-size: 12px; - padding: 10px; - text-align: center; + background: linear-gradient(to bottom, hsl(0, 0%, 100%) 0%, hsl(0, 0%, 96%) 47%, hsl(0, 0%, 93%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); + border: 1px solid hsl(0, 0%, 85%); + border-radius: 4px; + box-shadow: 0 0 3px hsla(0, 0%, 0%, 0.1) inset; + color: hsl(0, 0%, 20%); + display: block; + font-size: 12px; + padding: 10px; + text-align: center; } .dashboard-info span { - display: block; - text-align: center; + display: block; + text-align: center; } .dashboard-info img { - margin: 0 auto; + margin: 0 auto; } .dashboard-table { - border-top: 1px solid hsl(0, 0%, 87%); - margin-top: 5px; - width: 100%; + border-top: 1px solid hsl(0, 0%, 87%); + margin-top: 5px; + width: 100%; } .dashboard-info h5 { - font-size: 11px; - font-weight: bold; + font-size: 11px; + font-weight: bold; } .dashboard-block { - background: linear-gradient(to bottom, hsl(0, 0%, 95%) 0%, hsl(0, 0%, 86%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); - border: 1px solid hsl(0, 0%, 76%); - border-radius: 3px; - box-shadow: 0 1px 0 hsl(0, 0%, 98%) inset; - margin-bottom: 20px; + background: linear-gradient(to bottom, hsl(0, 0%, 95%) 0%, hsl(0, 0%, 86%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); + border: 1px solid hsl(0, 0%, 76%); + border-radius: 3px; + box-shadow: 0 1px 0 hsl(0, 0%, 98%) inset; + margin-bottom: 20px; } .dashboard-block .dashboard-block-head { - background: linear-gradient(to bottom, hsl(0, 0%, 95%) 0%, hsl(0, 0%, 86%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); - border-bottom: 1px solid hsl(0, 0%, 76%); - border-radius: 3px 3px 0 0; - box-shadow: 0 1px 0 hsl(0, 0%, 98%) inset, 0 0 3px hsl(0, 0%, 87%); - height: 40px; - position: relative; + background: linear-gradient(to bottom, hsl(0, 0%, 95%) 0%, hsl(0, 0%, 86%) 100%) repeat scroll 0 0 hsla(0, 0%, 0%, 0); + border-bottom: 1px solid hsl(0, 0%, 76%); + border-radius: 3px 3px 0 0; + box-shadow: 0 1px 0 hsl(0, 0%, 98%) inset, 0 0 3px hsl(0, 0%, 87%); + height: 40px; + position: relative; } .dashboard-block .dashboard-block-head h5 { - font-size: 12px; - margin: 0; - padding-left: 10px; - padding-top: 11px; - text-transform: uppercase; + font-size: 12px; + margin: 0; + padding-left: 10px; + padding-top: 11px; + text-transform: uppercase; } .dashboard-block .dashboard-block-content { - background: none repeat scroll 0 0 hsl(0, 0%, 93%); - border-radius: 0 0 3px 3px; + background: none repeat scroll 0 0 hsl(0, 0%, 93%); + border-radius: 0 0 3px 3px; } .dashboard-block .dashboard-block-box { - background: none repeat scroll 0 0 hsl(0, 0%, 100%); - border-top: 1px solid hsl(0, 0%, 82%); - box-shadow: 0 0 5px hsl(0, 0%, 87%) inset; + background: none repeat scroll 0 0 hsl(0, 0%, 100%); + border-top: 1px solid hsl(0, 0%, 82%); + box-shadow: 0 0 5px hsl(0, 0%, 87%) inset; } .dashboard-block .dashboard-block-content .dashboard-block-box { - margin-top: 0 !important; + margin-top: 0 !important; } .dashboard-block .dashboard-block-content .dashboard-block-box .dashboard-block-table { - margin-bottom: 0 !important; + margin-bottom: 0 !important; } .dashboard-block-table { - background-color: hsla(0, 0%, 0%, 0); - border-collapse: collapse; - border-spacing: 0; - margin-bottom: 20px; - max-width: 100%; - width: 100%; + background-color: hsla(0, 0%, 0%, 0); + border-collapse: collapse; + border-spacing: 0; + margin-bottom: 20px; + max-width: 100%; + width: 100%; } .dashboard-block-table th, .dashboard-block-table td { - border-top: 1px solid hsl(0, 0%, 87%); - line-height: 20px; - padding: 5px; - text-align: left; - vertical-align: middle; + border-top: 1px solid hsl(0, 0%, 87%); + line-height: 20px; + padding: 5px; + text-align: left; + vertical-align: middle; } .dashboard-badge { - background-color: hsl(0, 0%, 60%); - border-radius: 9px; - color: hsl(0, 0%, 100%); - font-size: 11.844px; - font-weight: bold; - line-height: 14px; - padding: 1px 9px 2px; - text-shadow: 0 -1px 0 hsla(0, 0%, 0%, 0.25); - vertical-align: baseline; - white-space: nowrap; + background-color: hsl(0, 0%, 60%); + border-radius: 9px; + color: hsl(0, 0%, 100%); + font-size: 11.844px; + font-weight: bold; + line-height: 14px; + padding: 1px 9px 2px; + text-shadow: 0 -1px 0 hsla(0, 0%, 0%, 0.25); + vertical-align: baseline; + white-space: nowrap; } \ No newline at end of file diff --git a/admin/assets/css/external_source.css b/admin/assets/css/external_source.css index d5dcd5d6..9c0037ee 100644 --- a/admin/assets/css/external_source.css +++ b/admin/assets/css/external_source.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage external_source.css diff --git a/admin/assets/css/external_sources.css b/admin/assets/css/external_sources.css index b0ebcb10..67fef4a2 100644 --- a/admin/assets/css/external_sources.css +++ b/admin/assets/css/external_sources.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage external_sources.css diff --git a/admin/assets/css/help_document.css b/admin/assets/css/help_document.css index d466832c..94d5a0ae 100644 --- a/admin/assets/css/help_document.css +++ b/admin/assets/css/help_document.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage help_document.css diff --git a/admin/assets/css/help_documents.css b/admin/assets/css/help_documents.css index 8f301dc7..6d21c372 100644 --- a/admin/assets/css/help_documents.css +++ b/admin/assets/css/help_documents.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage help_documents.css diff --git a/admin/assets/css/local_listing.css b/admin/assets/css/local_listing.css index 668726f4..1972b2f7 100644 --- a/admin/assets/css/local_listing.css +++ b/admin/assets/css/local_listing.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage local_listing.css diff --git a/admin/assets/css/local_listings.css b/admin/assets/css/local_listings.css index 34354d3d..1f96f390 100644 --- a/admin/assets/css/local_listings.css +++ b/admin/assets/css/local_listings.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage local_listings.css diff --git a/admin/assets/css/manual_updater.css b/admin/assets/css/manual_updater.css index eea232d1..002fc6a6 100644 --- a/admin/assets/css/manual_updater.css +++ b/admin/assets/css/manual_updater.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage manual_updater.css diff --git a/admin/assets/css/preacher.css b/admin/assets/css/preacher.css index 99d15e58..560a0836 100644 --- a/admin/assets/css/preacher.css +++ b/admin/assets/css/preacher.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage preacher.css diff --git a/admin/assets/css/preachers.css b/admin/assets/css/preachers.css index 5f209cd8..1882e456 100644 --- a/admin/assets/css/preachers.css +++ b/admin/assets/css/preachers.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage preachers.css diff --git a/admin/assets/css/series.css b/admin/assets/css/series.css index 7bcfec11..ef610b1a 100644 --- a/admin/assets/css/series.css +++ b/admin/assets/css/series.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage series.css diff --git a/admin/assets/css/series_list.css b/admin/assets/css/series_list.css index 52c14012..53eb0edb 100644 --- a/admin/assets/css/series_list.css +++ b/admin/assets/css/series_list.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage series_list.css diff --git a/admin/assets/css/sermon.css b/admin/assets/css/sermon.css index f4192d9c..157753d7 100644 --- a/admin/assets/css/sermon.css +++ b/admin/assets/css/sermon.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage sermon.css diff --git a/admin/assets/css/sermons.css b/admin/assets/css/sermons.css index b16e2bea..b9855003 100644 --- a/admin/assets/css/sermons.css +++ b/admin/assets/css/sermons.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage sermons.css diff --git a/admin/assets/css/statistic.css b/admin/assets/css/statistic.css index 93f896fa..ebb6be7c 100644 --- a/admin/assets/css/statistic.css +++ b/admin/assets/css/statistic.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage statistic.css diff --git a/admin/assets/css/statistics.css b/admin/assets/css/statistics.css index 637e843b..60aca4a0 100644 --- a/admin/assets/css/statistics.css +++ b/admin/assets/css/statistics.css @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage statistics.css diff --git a/admin/assets/images/import.gif b/admin/assets/images/import.gif index 4371cc61..10bcb856 100644 Binary files a/admin/assets/images/import.gif and b/admin/assets/images/import.gif differ diff --git a/admin/assets/js/admin.js b/admin/assets/js/admin.js index 0ac8b757..ae73268f 100644 --- a/admin/assets/js/admin.js +++ b/admin/assets/js/admin.js @@ -9,7 +9,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage admin.js diff --git a/admin/config.xml b/admin/config.xml index bbd532ef..739f1a52 100644 --- a/admin/config.xml +++ b/admin/config.xml @@ -1,8 +1,8 @@
@@ -301,17 +301,17 @@ name="uikit_config" label="COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_LABEL" description="COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_DESC"> - + default=""> - " - " + " + " " " - " " @@ -341,21 +339,6 @@ " - - - " - " - " -
- @copyright Copyright (C) 2015. All Rights Reserved - @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html - - A sermon distributor that links to Dropbox. - -/----------------------------------------------------------------------------------------------------------------------------------*/ - -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\BaseController; -use Joomla\Utilities\ArrayHelper; - -/** - * General Controller of Sermondistributor component - */ -class SermondistributorController extends BaseController -{ - /** - * Constructor. - * - * @param array $config An optional associative array of configuration settings. - * Recognized key values include 'name', 'default_task', 'model_path', and - * 'view_path' (this list is not meant to be comprehensive). - * - * @since 3.0 - */ - public function __construct($config = array()) - { - // set the default view - $config['default_view'] = 'sermondistributor'; - - parent::__construct($config); - } - - /** - * display task - * - * @return void - */ - function display($cachable = false, $urlparams = false) - { - // set default view if not set - $view = $this->input->getCmd('view', 'sermondistributor'); - $data = $this->getViewRelation($view); - $layout = $this->input->get('layout', null, 'WORD'); - $id = $this->input->getInt('id'); - - // Check for edit form. - if(SermondistributorHelper::checkArray($data)) - { - if ($data['edit'] && $layout == 'edit' && !$this->checkEditId('com_sermondistributor.edit.'.$data['view'], $id)) - { - // Somehow the person just went to the form - we don't allow that. - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $id)); - $this->setMessage($this->getError(), 'error'); - // check if item was opend from other then its own list view - $ref = $this->input->getCmd('ref', 0); - $refid = $this->input->getInt('refid', 0); - // set redirect - if ($refid > 0 && SermondistributorHelper::checkString($ref)) - { - // redirect to item of ref - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view='.(string)$ref.'&layout=edit&id='.(int)$refid, false)); - } - elseif (SermondistributorHelper::checkString($ref)) - { - - // redirect to ref - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view='.(string)$ref, false)); - } - else - { - // normal redirect back to the list view - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view='.$data['views'], false)); - } - - return false; - } - } - - return parent::display($cachable, $urlparams); - } - - protected function getViewRelation($view) - { - // check the we have a value - if (SermondistributorHelper::checkString($view)) - { - // the view relationships - $views = array( - 'preacher' => 'preachers', - 'sermon' => 'sermons', - 'series' => 'series_list', - 'statistic' => 'statistics', - 'external_source' => 'external_sources', - 'local_listing' => 'local_listings', - 'help_document' => 'help_documents' - ); - // check if this is a list view - if (in_array($view, $views)) - { - // this is a list view - return array('edit' => false, 'view' => array_search($view,$views), 'views' => $view); - } - // check if it is an edit view - elseif (array_key_exists($view, $views)) - { - // this is a edit view - return array('edit' => true, 'view' => $view, 'views' => $views[$view]); - } - } - return false; - } -} diff --git a/admin/models/forms/external_source.xml b/admin/forms/external_source.xml similarity index 98% rename from admin/models/forms/external_source.xml rename to admin/forms/external_source.xml index 8b4fd726..c34b1d7a 100644 --- a/admin/models/forms/external_source.xml +++ b/admin/forms/external_source.xml @@ -1,8 +1,11 @@
+ + +
@@ -73,6 +76,7 @@ label="COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_VERSION_LABEL" description="COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_VERSION_DESC" size="6" + default="1" readonly="true" filter="unset" /> @@ -357,7 +361,7 @@ hint="COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_OAUTHTOKEN_HINT" />
- +
diff --git a/admin/models/forms/filter_external_sources.xml b/admin/forms/filter_external_sources.xml similarity index 81% rename from admin/models/forms/filter_external_sources.xml rename to admin/forms/filter_external_sources.xml index 70917b09..437796c9 100644 --- a/admin/models/forms/filter_external_sources.xml +++ b/admin/forms/filter_external_sources.xml @@ -1,7 +1,7 @@ @@ -26,21 +26,21 @@ name="externalsources" label="COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_EXTERNALSOURCES_LABEL" multiple="false" - onchange="this.form.submit();" + class="js-select-submit-on-change" /> @@ -49,9 +49,8 @@ @@ -75,11 +74,9 @@ \ No newline at end of file diff --git a/admin/models/forms/filter_help_documents.xml b/admin/forms/filter_help_documents.xml similarity index 71% rename from admin/models/forms/filter_help_documents.xml rename to admin/forms/filter_help_documents.xml index ac08a878..32e2f928 100644 --- a/admin/models/forms/filter_help_documents.xml +++ b/admin/forms/filter_help_documents.xml @@ -1,7 +1,7 @@
@@ -65,9 +65,8 @@ @@ -82,10 +81,10 @@ - - - - + + + + @@ -93,11 +92,9 @@ \ No newline at end of file diff --git a/admin/models/forms/filter_local_listings.xml b/admin/forms/filter_local_listings.xml similarity index 82% rename from admin/models/forms/filter_local_listings.xml rename to admin/forms/filter_local_listings.xml index f1fc4406..19ddf671 100644 --- a/admin/models/forms/filter_local_listings.xml +++ b/admin/forms/filter_local_listings.xml @@ -1,7 +1,7 @@
@@ -26,14 +26,14 @@ name="build" label="COM_SERMONDISTRIBUTOR_LOCAL_LISTING_BUILD_LABEL" multiple="false" - onchange="this.form.submit();" + class="js-select-submit-on-change" /> @@ -42,9 +42,8 @@ @@ -70,11 +69,9 @@ \ No newline at end of file diff --git a/admin/models/forms/filter_preachers.xml b/admin/forms/filter_preachers.xml similarity index 73% rename from admin/models/forms/filter_preachers.xml rename to admin/forms/filter_preachers.xml index 7e565374..eb6a1838 100644 --- a/admin/models/forms/filter_preachers.xml +++ b/admin/forms/filter_preachers.xml @@ -1,7 +1,7 @@
@@ -37,9 +37,8 @@ @@ -59,11 +58,9 @@ \ No newline at end of file diff --git a/admin/models/forms/filter_series_list.xml b/admin/forms/filter_series_list.xml similarity index 71% rename from admin/models/forms/filter_series_list.xml rename to admin/forms/filter_series_list.xml index a26ff06b..60f0827a 100644 --- a/admin/models/forms/filter_series_list.xml +++ b/admin/forms/filter_series_list.xml @@ -1,7 +1,7 @@
@@ -37,9 +37,8 @@ @@ -57,11 +56,9 @@ \ No newline at end of file diff --git a/admin/models/forms/filter_sermons.xml b/admin/forms/filter_sermons.xml similarity index 78% rename from admin/models/forms/filter_sermons.xml rename to admin/forms/filter_sermons.xml index 5a743f01..c34ce5bc 100644 --- a/admin/models/forms/filter_sermons.xml +++ b/admin/forms/filter_sermons.xml @@ -1,7 +1,7 @@
@@ -27,49 +27,51 @@ label="COM_SERMONDISTRIBUTOR_SERMON_SERMONS_CATEGORIES" description="JOPTION_FILTER_CATEGORY_DESC" multiple="true" - class="multipleCategories" + class="js-select-submit-on-change" extension="com_sermondistributor.sermon" - onchange="this.form.submit();" + layout="joomla.form.field.list-fancy-select" published="0,1,2" /> @@ -78,9 +80,8 @@ @@ -110,11 +111,9 @@ \ No newline at end of file diff --git a/admin/models/forms/filter_statistics.xml b/admin/forms/filter_statistics.xml similarity index 78% rename from admin/models/forms/filter_statistics.xml rename to admin/forms/filter_statistics.xml index 3dfc6ae1..d57a47a9 100644 --- a/admin/models/forms/filter_statistics.xml +++ b/admin/forms/filter_statistics.xml @@ -1,7 +1,7 @@
@@ -58,9 +58,8 @@ @@ -86,11 +85,9 @@ \ No newline at end of file diff --git a/admin/models/forms/help_document.xml b/admin/forms/help_document.xml similarity index 96% rename from admin/models/forms/help_document.xml rename to admin/forms/help_document.xml index 0c309dc7..3fa146f2 100644 --- a/admin/models/forms/help_document.xml +++ b/admin/forms/help_document.xml @@ -1,8 +1,11 @@
+ + +
@@ -81,6 +84,7 @@ label="COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_VERSION_LABEL" description="COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_VERSION_DESC" size="6" + default="1" readonly="true" filter="unset" /> @@ -139,9 +143,9 @@ - + @@ -283,7 +286,7 @@ />
- +
diff --git a/admin/controllers/index.html b/admin/forms/index.html similarity index 100% rename from admin/controllers/index.html rename to admin/forms/index.html diff --git a/admin/models/forms/local_listing.xml b/admin/forms/local_listing.xml similarity index 96% rename from admin/models/forms/local_listing.xml rename to admin/forms/local_listing.xml index 460c341d..4e0003d2 100644 --- a/admin/models/forms/local_listing.xml +++ b/admin/forms/local_listing.xml @@ -1,8 +1,11 @@ + + +
@@ -73,6 +76,7 @@ label="COM_SERMONDISTRIBUTOR_LOCAL_LISTING_VERSION_LABEL" description="COM_SERMONDISTRIBUTOR_LOCAL_LISTING_VERSION_DESC" size="6" + default="1" readonly="true" filter="unset" /> @@ -173,7 +177,7 @@ hint="COM_SERMONDISTRIBUTOR_LOCAL_LISTING_URL_HINT" />
- +
diff --git a/admin/models/forms/preacher.xml b/admin/forms/preacher.xml similarity index 96% rename from admin/models/forms/preacher.xml rename to admin/forms/preacher.xml index 14881dfe..06cdae60 100644 --- a/admin/models/forms/preacher.xml +++ b/admin/forms/preacher.xml @@ -1,8 +1,11 @@ + + +
@@ -81,6 +84,7 @@ label="COM_SERMONDISTRIBUTOR_PREACHER_VERSION_LABEL" description="COM_SERMONDISTRIBUTOR_PREACHER_VERSION_DESC" size="6" + default="1" readonly="true" filter="unset" /> @@ -215,7 +219,7 @@ />
- +
diff --git a/admin/models/forms/series.xml b/admin/forms/series.xml similarity index 96% rename from admin/models/forms/series.xml rename to admin/forms/series.xml index b88debda..7442c193 100644 --- a/admin/models/forms/series.xml +++ b/admin/forms/series.xml @@ -1,8 +1,11 @@ + + +
@@ -81,6 +84,7 @@ label="COM_SERMONDISTRIBUTOR_SERIES_VERSION_LABEL" description="COM_SERMONDISTRIBUTOR_SERIES_VERSION_DESC" size="6" + default="1" readonly="true" filter="unset" /> @@ -203,7 +207,7 @@ />
- +
diff --git a/admin/models/forms/sermon.xml b/admin/forms/sermon.xml similarity index 98% rename from admin/models/forms/sermon.xml rename to admin/forms/sermon.xml index 44550ea6..ecb2c5d5 100644 --- a/admin/models/forms/sermon.xml +++ b/admin/forms/sermon.xml @@ -1,8 +1,11 @@ + + +
@@ -81,6 +84,7 @@ label="COM_SERMONDISTRIBUTOR_SERMON_VERSION_LABEL" description="COM_SERMONDISTRIBUTOR_SERMON_VERSION_DESC" size="6" + default="1" readonly="true" filter="unset" /> @@ -255,7 +259,6 @@ mode="ajax" label="COM_SERMONDISTRIBUTOR_SERMON_TAGS_LABEL" description="COM_SERMONDISTRIBUTOR_SERMON_TAGS_DESCRIPTION" - class="inputbox small" published="true" multiple="true" /> @@ -375,7 +378,7 @@ />
- +
diff --git a/admin/models/forms/statistic.xml b/admin/forms/statistic.xml similarity index 96% rename from admin/models/forms/statistic.xml rename to admin/forms/statistic.xml index 5d6af32d..c36130de 100644 --- a/admin/models/forms/statistic.xml +++ b/admin/forms/statistic.xml @@ -1,8 +1,11 @@ + + +
@@ -81,6 +84,7 @@ label="COM_SERMONDISTRIBUTOR_STATISTIC_VERSION_LABEL" description="COM_SERMONDISTRIBUTOR_STATISTIC_VERSION_DESC" size="6" + default="1" readonly="true" filter="unset" /> @@ -202,7 +206,7 @@ />
- +
diff --git a/admin/helpers/headercheck.php b/admin/helpers/headercheck.php deleted file mode 100644 index a049a32a..00000000 --- a/admin/helpers/headercheck.php +++ /dev/null @@ -1,84 +0,0 @@ - - @copyright Copyright (C) 2015. All Rights Reserved - @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html - - A sermon distributor that links to Dropbox. - -/----------------------------------------------------------------------------------------------------------------------------------*/ - -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -class sermondistributorHeaderCheck -{ - function js_loaded($script_name) - { - // UIkit check point - if (strpos($script_name,'uikit') !== false) - { - $app = JFactory::getApplication(); - $getTemplateName = $app->getTemplate('template')->template; - - if (strpos($getTemplateName,'yoo') !== false) - { - return true; - } - } - - $document = JFactory::getDocument(); - $head_data = $document->getHeadData(); - foreach (array_keys($head_data['scripts']) as $script) - { - if (stristr($script, $script_name)) - { - return true; - } - } - - return false; - } - - function css_loaded($script_name) - { - // UIkit check point - if (strpos($script_name,'uikit') !== false) - { - $app = JFactory::getApplication(); - $getTemplateName = $app->getTemplate('template')->template; - - if (strpos($getTemplateName,'yoo') !== false) - { - return true; - } - } - - $document = JFactory::getDocument(); - $head_data = $document->getHeadData(); - - foreach (array_keys($head_data['styleSheets']) as $script) - { - if (stristr($script, $script_name)) - { - return true; - } - } - - return false; - } -} \ No newline at end of file diff --git a/admin/helpers/html/batch_.php b/admin/helpers/html/batch_.php deleted file mode 100644 index ff7f840d..00000000 --- a/admin/helpers/html/batch_.php +++ /dev/null @@ -1,91 +0,0 @@ - - @copyright Copyright (C) 2015. All Rights Reserved - @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html - - A sermon distributor that links to Dropbox. - -/----------------------------------------------------------------------------------------------------------------------------------*/ - -// No direct access to this file -defined('JPATH_PLATFORM') or die; - -/** - * Utility class to render a list view batch selection options - * - * @since 3.0 - */ -abstract class JHtmlBatch_ -{ - /** - * ListSelection - * - * @var array - * @since 3.0 - */ - protected static $ListSelection = array(); - - /** - * Render the batch selection options. - * - * @return string The necessary HTML to display the batch selection options - * - * @since 3.0 - */ - public static function render() - { - // Collect display data - $data = new stdClass; - $data->ListSelection = static::getListSelection(); - - // Create a layout object and ask it to render the batch selection options - $layout = new JLayoutFile('batchselection'); - $batchHtml = $layout->render($data); - - return $batchHtml; - } - - /** - * Method to add a list selection to the batch modal - * - * @param string $label Label for the menu item. - * @param string $name Name for the filter. Also used as id. - * @param string $options Options for the select field. - * @param bool $noDefault Don't the label as the empty option - * - * @return void - * - * @since 3.0 - */ - public static function addListSelection($label, $name, $options, $noDefault = false) - { - array_push(static::$ListSelection, array('label' => $label, 'name' => $name, 'options' => $options, 'noDefault' => $noDefault)); - } - - /** - * Returns an array of all ListSelection - * - * @return array - * - * @since 3.0 - */ - public static function getListSelection() - { - return static::$ListSelection; - } -} diff --git a/admin/helpers/sermondistributor.php b/admin/helpers/sermondistributor.php deleted file mode 100644 index beee197d..00000000 --- a/admin/helpers/sermondistributor.php +++ /dev/null @@ -1,4603 +0,0 @@ - - @copyright Copyright (C) 2015. All Rights Reserved - @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html - - A sermon distributor that links to Dropbox. - -/----------------------------------------------------------------------------------------------------------------------------------*/ - -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\Filesystem\File; -use Joomla\CMS\Language\Language; -use Joomla\Registry\Registry; -use Joomla\String\StringHelper; -use Joomla\Utilities\ArrayHelper; -use PhpOffice\PhpSpreadsheet\IOFactory; -use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Writer\Xlsx; -use Joomla\CMS\Filesystem\Folder; - -/** - * Sermondistributor component helper. - */ -abstract class SermondistributorHelper -{ - /** - * Composer Switch - * - * @var array - */ - protected static $composer = array(); - - /** - * The Main Active Language - * - * @var string - */ - public static $langTag; - - /** - * The global params - **/ - protected static $params = false; - - /** - * Update Watcher - **/ - public static $updateWatch = 1; - - /** - * Update Watcher (if array is only one value) - **/ - public static $updateWatch_ = 0; - - /** - * The external source links auto - **/ - protected static $links_externalsource_auto; - - /** - * The external source links manual - **/ - protected static $links_externalsource_manual; - - /** - * The external source selection auto - **/ - protected static $select_externalsource_auto; - - /** - * The external source selection manual - **/ - protected static $select_externalsource_manual; - - /** - * The update errors - **/ - protected static $updateErrors = array(); - - /** - * prepare base64 string for url - * - * @deprecate Use urlencode(); - */ - public static function base64_urlencode($string, $encode = false) - { - if ($encode) - { - $string = base64_encode($string); - } - return str_replace(array('+', '/'), array('-', '_'), $string); - } - - /** - * prepare base64 string form url - * - * @deprecate - */ - public static function base64_urldecode($string, $decode = false) - { - $string = str_replace(array('-', '_'), array('+', '/'), $string); - if ($decode) - { - $string = base64_decode($string); - } - return $string; - } - - /** - * get Download links of a sermon - **/ - public static function getDownloadLinks(&$sermon) - { - $links = array(); - // Get local key - $localkey = self::getLocalKey(); - // decrypt the urls - $safe = new FOFEncryptAes($localkey, 128); - // internal download url - $keyCounter = new stdClass; - $keyCounter->sermon = $sermon->id; - if ($sermon->preacher) - { - $keyCounter->preacher = $sermon->preacher; - } - if ($sermon->series) - { - $keyCounter->series = $sermon->series; - } - $keyCounterRAW = $safe->encryptString(json_encode($keyCounter)); - $keyCounter = self::base64_urlencode($keyCounterRAW); - $token = JSession::getFormToken(); - $downloadURL = JURI::root().'index.php?option=com_sermondistributor&task=download.file&key='.$keyCounter.'&token='.$token; - // check if local .htaccess should be set - $setHtaccess = false; - $onclick = ' onclick="sermonCounter(\''.$keyCounterRAW.'\',\'FILENAME\');"'; - // check what source of our link - switch ($sermon->source) - { - case 1: - // local file get local folder and check if outside root (if not then allow direct) - $localFolder = JComponentHelper::getParams('com_sermondistributor')->get('localfolder', JPATH_ROOT.'/images').'/'; - // should we allow direct downloads - $allowDirect = false; - if (2 == $sermon->link_type && strpos($localFolder, JPATH_ROOT) !== false) - { - $allowDirect = true; - $localFolderURL = JURI::root().str_replace(JPATH_ROOT, '', $localFolder); - // insure no double // is in the URL - $localFolderURL = str_replace('//', '/', $localFolderURL); - $localFolderURL = str_replace(':/', '://', $localFolderURL); - } - // insure no double // is in the path name - $localFolder = str_replace('//', '/', $localFolder); - $localFolder = str_replace(':/', '://', $localFolder); - if (self::checkArray($sermon->local_files)) - { - foreach($sermon->local_files as $key) - { - if (1 == $sermon->link_type || !$allowDirect) - { - // get the file name use the same method as the auto - $filename = self::getDownloadFileName($sermon,$key,'local'); - $lockedFolderPath = $safe->encryptString($localFolder.$key); - $sermon->download_links[$filename] = $downloadURL.'&link='.self::base64_urlencode($lockedFolderPath).'&filename='.$filename; - $sermon->onclick[$filename] = ''; - } - elseif (2 == $sermon->link_type && $allowDirect) - { - $filename = $key; - $sermon->download_links[$filename] = $localFolderURL.$key; - $sermon->onclick[$filename] = str_replace('FILENAME', $filename, $onclick); - $setHtaccess = true; - } - } - } - break; - case 2: - // Dropbox get global dropbox switch - $addToButton = JComponentHelper::getParams('com_sermondistributor')->get('add_to_button', 0); - if (1 == $sermon->build) - { - if (self::checkArray($sermon->manual_files)) - { - // manual dropbox - foreach($sermon->manual_files as $key) - { - // get the link - $dropURL = self::getExternalSourceLink('manual',1,$key); - if (1 == $sermon->link_type && $dropURL) - { - // get the file name use the same method as the auto - $filename = self::getDownloadFileName($sermon,$key,'dropbox_manual'); - // should we encrypt string this string - if ('localKey34fdWEkl' == $localkey || (base64_encode(base64_decode($dropURL, true)) !== $dropURL)) // hmmm no global key has been set - { - $dropURL = $safe->encryptString($dropURL); - } - // lock the info key - $infoKey = $safe->encryptString($key); - $sermon->download_links[$filename] = $downloadURL.'&info='.self::base64_urlencode($infoKey).'&link='.self::base64_urlencode($dropURL).'&filename='.$filename; - $sermon->onclick[$filename] = ''; - } - elseif (2 == $sermon->link_type && $dropURL) - { - $filename = str_replace('VDM_pLeK_h0uEr/', '', $key); - if ('localKey34fdWEkl' == $localkey) // hmmm no global key has been set (so don't decrypt) - { - $sermon->download_links[$filename] = $dropURL; - } - else - { - $sermon->download_links[$filename] = rtrim($safe->decryptString($dropURL), "\0"); - } - $sermon->onclick[$filename] = str_replace('FILENAME', $filename, $onclick); - } - // build dropbox switch if needed - if (1 == $addToButton && $dropURL) - { - if ('localKey34fdWEkl' == $localkey) // hmmm no global key has been set (so don't decrypt) - { - $sermon->dropbox_buttons[$filename] = str_replace('?dl=1', '?dl=0', $dropURL); - } - else - { - $sermon->dropbox_buttons[$filename] = str_replace('?dl=1', '?dl=0', rtrim($safe->decryptString($dropURL), "\0")); - } - $sermon->onclick_drobox[$filename] = str_replace('FILENAME', $filename, $onclick); - } - } - } - } - elseif (2 == $sermon->build) - { - if (self::checkArray($sermon->auto_sermons)) - { - // automatic dropbox - foreach($sermon->auto_sermons as $filename => $key) - { - // get the link - $dropURL = self::getExternalSourceLink('auto',1,$key); - if (1 == $sermon->link_type && $dropURL) - { - // should we encrypt string this string - if ('localKey34fdWEkl' == $localkey || (base64_encode(base64_decode($dropURL, true)) !== $dropURL)) // hmmm no global key has been set - { - $dropURL = $safe->encryptString($dropURL); - } - // lock the info key - $infoKey = $safe->encryptString($key); - $sermon->download_links[$filename] = $downloadURL.'&info='.self::base64_urlencode($infoKey).'&link='.self::base64_urlencode($dropURL).'&filename='.$filename; - $sermon->onclick[$filename] = ''; - } - elseif (2 == $sermon->link_type && $dropURL) - { - if ('localKey34fdWEkl' == $localkey) // hmmm no global key has been set (so don't decrypt) - { - $sermon->download_links[$filename] = $dropURL; - } - else - { - $sermon->download_links[$filename] = rtrim($safe->decryptString($dropURL), "\0"); - } - $sermon->onclick[$filename] = str_replace('FILENAME', $filename, $onclick); - } - // build dropbox switch if needed - if (1 == $addToButton && $dropURL) - { - if ('localKey34fdWEkl' == $localkey) // hmmm no global key has been set (so don't decrypt) - { - $sermon->dropbox_buttons[$filename] = str_replace('?dl=1', '?dl=0', $dropURL); - } - else - { - $sermon->dropbox_buttons[$filename] = str_replace('?dl=1', '?dl=0', rtrim($safe->decryptString($dropURL), "\0")); - } - $sermon->onclick_drobox[$filename] = str_replace('FILENAME', $filename, $onclick); - } - } - } - } - break; - case 3: - // url get the file name use the same method as the auto - $filename = self::getDownloadFileName($sermon,$sermon->url,'url'); - if (1 == $sermon->link_type) - { - $lockedURL = $safe->encryptString($sermon->url); - $sermon->download_links[$filename] = $downloadURL.'&link='.self::base64_urlencode($lockedURL).'&filename='.$filename; - $sermon->onclick[$filename] = ''; - } - elseif (2 == $sermon->link_type) - { - $sermon->download_links[$filename] = $sermon->url; - $sermon->onclick[$filename] = str_replace('FILENAME', $filename, $onclick); - } - break; - } - // remove the values no longer needed - unset($sermon->local_files); - unset($sermon->manual_files); - unset($sermon->auto_sermons); - unset($sermon->url); - // should we set the local .htaccess for the download folder - if ($setHtaccess) - { - // TODO we may need to add this latter to enforce download of files. - } - return true; - } - - public static function getNextUpdateValues($asArray = false) - { - // find the next value - $next = false; - // get actual update values - $updates = self::getExternalListingUpdateKeys(); - // get last update - $updatePath = self::getFilePath('path', 'updatelast', 'txt', 'vDm', JPATH_COMPONENT_ADMINISTRATOR); - if (($lastUpdate = @file_get_contents($updatePath)) !== FALSE && self::checkArray($updates)) - { - // is it time to watch - if (self::$updateWatch_ > 0) - { - // increment the watch, as this is the start of new round - self::$updateWatch++; - // new round has started - self::$updateWatch_ = 0; - } - // now check what is next - $lastKey = array_search($lastUpdate, $updates); - if (!is_null($lastKey)) - { - $nextKey = $lastKey + 1; - if (isset($updates[$nextKey])) - { - $next = $updates[$nextKey]; - } - else - { - // last item in array, so next round about to start - self::$updateWatch_++; - } - } - } - // rest and start with the first key - if (!$next && self::checkArray($updates)) - { - // save the first set - $start = reset($updates); - $next = $start; - } - // save to file if next is found - if ($next) - { - self::writeFile($updatePath,$next); - // convert to array of needed - if ($asArray) - { - if (strpos($next, ',') !== false) - { - $next = array_map('trim', explode(',', $next)); - } - else - { - return false; - } - } - } - return $next; - } - - /** - * Get the file path or url - * - * @param string $type The (url/path) type to return - * @param string $target The Params Target name (if set) - * @param string $fileType The kind of filename to generate (if not set no file name is generated) - * @param string $key The key to adjust the filename (if not set ignored) - * @param string $default The default path if not set in Params (fallback path) - * @param bool $createIfNotSet The switch to create the folder if not found - * - * @return string On success the path or url is returned based on the type requested - * - */ - public static function getFilePath($type = 'path', $target = 'filepath', $fileType = null, $key = '', $default = '', $createIfNotSet = true) - { - // make sure to always have a string/path - if(!self::checkString($default)) - { - $default = JPATH_SITE . '/images/'; - } - // get the global settings - if (!self::checkObject(self::$params)) - { - self::$params = JComponentHelper::getParams('com_sermondistributor'); - } - $filePath = self::$params->get($target, $default); - // check the file path (revert to default only of not a hidden file path) - if ('hiddenfilepath' !== $target && strpos($filePath, JPATH_SITE) === false) - { - $filePath = $default; - } - // create the folder if it does not exist - if ($createIfNotSet && !Folder::exists($filePath)) - { - Folder::create($filePath); - } - // setup the file name - $fileName = ''; - // Get basic key - $basickey = 'Th!s_iS_n0t_sAfe_buT_b3tter_then_n0thiug'; - if (method_exists(get_called_class(), "getCryptKey")) - { - $basickey = self::getCryptKey('basic', $basickey); - } - // check the key - if (!self::checkString($key)) - { - $key = 'vDm'; - } - // set the file name - if (self::checkString($fileType)) - { - // set the name - $fileName = trim(md5($type.$target.$basickey.$key) . '.' . trim($fileType, '.')); - } - else - { - $fileName = trim(md5($type.$target.$basickey.$key)) . '.txt'; - } - // return the url - if ('url' === $type) - { - if (strpos($filePath, JPATH_SITE) !== false) - { - $filePath = trim( str_replace( JPATH_SITE, '', $filePath), '/'); - return JURI::root() . $filePath . '/' . $fileName; - } - // since the path is behind the root folder of the site, return only the root url (may be used to build the link) - return JURI::root(); - } - // sanitize the path - return '/' . trim( $filePath, '/' ) . '/' . $fileName; - } - - - /** - * Write a file to the server - * - * @param string $path The path and file name where to safe the data - * @param string $data The data to safe - * - * @return bool true On success - * - */ - public static function writeFile($path, $data) - { - $klaar = false; - if (self::checkString($data)) - { - // open the file - $fh = fopen($path, "w"); - if (!is_resource($fh)) - { - return $klaar; - } - // write to the file - if (fwrite($fh, $data)) - { - // has been done - $klaar = true; - } - // close file. - fclose($fh); - } - return $klaar; - } - - protected static function saveFile($data, $path_filename) - { - return self::writeFile($path_filename, $data); - } - - public static function getExternalListingUpdateKeys($id = null, $updateMethod = 2, $returnType = 1) - { - // first check if this file already has statistics - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select($db->quoteName(array('id','sharedurl','folder','permissiontype','dropboxoptions','build'))); - $query->from($db->quoteName('#__sermondistributor_external_source')); - if ($updateMethod && is_numeric($updateMethod)) - { - $query->where($db->quoteName('update_method') . ' = '. (int) $updateMethod); - } - if ($id && is_numeric($id)) - { - $query->where($db->quoteName('id') . ' = '. (int) $id); - } - elseif ($id && self::checkArray($id)) - { - $ids = implode(',', array_map( 'intval', $id)); - $query->where($db->quoteName('id') . ' IN (' . $ids . ')'); - } - $query->where($db->quoteName('published') . ' = 1'); - $db->setQuery($query); - $db->execute(); - if ($db->getNumRows()) - { - $results = $db->loadObjectList(); - $updates = array(); - foreach ($results as $result) - { - if ('full' == $result->permissiontype) - { - // load folder or urls - switch ($result->dropboxoptions) - { - case 1: // sharedurl - if (self::checkJson($result->sharedurl)) - { - $targets = json_decode($result->sharedurl)->tsharedurl; - } - break; - case 2: // folders - if (self::checkJson($result->folder)) - { - $targets = json_decode($result->folder)->tfolder; - } - break; - } - if (self::checkArray($targets)) - { - foreach ($targets as $key => $value) - { - $nr = $key + 1; - // id, target, type - if (1 == $returnType) - { - $updates[] = $result->id . ', '. $nr . ', ' . $result->build; - } - else // only return the targets - { - $updates[] = $nr; - } - } - } - } - else - { - // id, target, type - if (1 == $returnType) - { - $updates[] = $result->id . ', 1, '. $result->build; - } - else // only return the targets - { - $updates[] = 1; - } - } - } - return $updates; - } - return false; - } - - public static function getExternalSourceLink($type, $return = 7, $get = false, $target = 'links') - { - // make sure all defaults are set - $found = self::checkExternalSourceLocalListing($type, $target); - if ($found) - { - switch($return) - { - case 1: - // return a link - if (isset(self::${$target.'_externalsource_'.$type}[$get])) - { - return self::${$target.'_externalsource_'.$type}[$get]; - } - break; - case 2: - // return all links - return self::${$target.'_externalsource_'.$type}; - break; - default : - // just confirm that it is set - return true; - break; - } - } - return false; - } - - public static function countDownload($counter, $filename) - { - // Get local key - $localkey = self::getLocalKey(); - $opener = new FOFEncryptAes($localkey, 128); - $counter = json_decode(rtrim($opener->decryptString($counter), "\0")); - if (self::checkObject($counter)) - { - $counter->filename = $filename; - // set the date object - $date = JFactory::getDate(); - // first check if this file already has statistics - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select($db->quoteName(array('id','counter'))); - $query->from($db->quoteName('#__sermondistributor_statistic')); - $query->where($db->quoteName('sermon') . ' = '. (int) $counter->sermon); - $query->where($db->quoteName('filename') . ' = '. $db->quote($counter->filename)); - $db->setQuery($query); - $db->execute(); - if ($db->getNumRows()) - { - $statistic = $db->loadObject(); - // already has an entry - $statistic->counter++; - $statistic->modified = $date->toSql(); - // update the entry - return $db->updateObject('#__sermondistributor_statistic', $statistic, 'id'); - } - else - { - // set a new entry - $counter->counter = 1; - $counter->published = 1; - $counter->created = $date->toSql(); - $counter->access = 1; - $counter->version = 1; - // set a new entry - $done = $db->insertObject('#__sermondistributor_statistic', $counter); - // if done return last used id - if ($done) - { - $newId = $db->insertid(); - // make sure the access of asset is set - return self::setAsset($newId,'statistic'); - } - } - } - return false; - } - - public static function getFileInfo($key) - { - if (self::checkString($key) && (base64_encode(base64_decode($key, true)) === $key)) - { - // Get local key - $localkey = self::getLocalKey(); - $opener = new FOFEncryptAes($localkey, 128); - $key = rtrim($opener->decryptString($key), "\0"); - // load the links from the database - $db = JFactory::getDbo(); - // Create a new query object. - $query = $db->getQuery(true); - $query->select('size'); - $query->from($db->quoteName('#__sermondistributor_local_listing')); - $query->where($db->quoteName('key') . ' = '. $db->quote($key)); - // Reset the query using our newly populated query object. - $db->setQuery($query); - $db->execute(); - if ($db->getNumRows()) - { - $info = array(); - // get the size of the file - $info['filesize'] = $db->loadResult(); - // get the mime type - $info['type'] = self::mimeType($key); - // return info - return $info; - } - } - return false; - } - - /** - * File Extensions to Mimetypes - * https://gist.github.com/Llewellynvdm/74be373357e131b8775a7582c3de508b - * http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types - * - * @var array - */ - protected static $fileExtensionToMimeType = array( - '123' => 'application/vnd.lotus-1-2-3', - '3dml' => 'text/vnd.in3d.3dml', - '3ds' => 'image/x-3ds', - '3g2' => 'video/3gpp2', - '3gp' => 'video/3gpp', - '7z' => 'application/x-7z-compressed', - 'aab' => 'application/x-authorware-bin', - 'aac' => 'audio/x-aac', - 'aam' => 'application/x-authorware-map', - 'aas' => 'application/x-authorware-seg', - 'abw' => 'application/x-abiword', - 'ac' => 'application/pkix-attr-cert', - 'acc' => 'application/vnd.americandynamics.acc', - 'ace' => 'application/x-ace-compressed', - 'acu' => 'application/vnd.acucobol', - 'acutc' => 'application/vnd.acucorp', - 'adp' => 'audio/adpcm', - 'aep' => 'application/vnd.audiograph', - 'afm' => 'application/x-font-type1', - 'afp' => 'application/vnd.ibm.modcap', - 'ahead' => 'application/vnd.ahead.space', - 'ai' => 'application/postscript', - 'aif' => 'audio/x-aiff', - 'aifc' => 'audio/x-aiff', - 'aiff' => 'audio/x-aiff', - 'air' => 'application/vnd.adobe.air-application-installer-package+zip', - 'ait' => 'application/vnd.dvb.ait', - 'ami' => 'application/vnd.amiga.ami', - 'apk' => 'application/vnd.android.package-archive', - 'appcache' => 'text/cache-manifest', - 'application' => 'application/x-ms-application', - 'apr' => 'application/vnd.lotus-approach', - 'arc' => 'application/x-freearc', - 'asc' => 'application/pgp-signature', - 'asf' => 'video/x-ms-asf', - 'asm' => 'text/x-asm', - 'aso' => 'application/vnd.accpac.simply.aso', - 'asx' => 'video/x-ms-asf', - 'atc' => 'application/vnd.acucorp', - 'atom' => 'application/atom+xml', - 'atomcat' => 'application/atomcat+xml', - 'atomsvc' => 'application/atomsvc+xml', - 'atx' => 'application/vnd.antix.game-component', - 'au' => 'audio/basic', - 'avi' => 'video/x-msvideo', - 'aw' => 'application/applixware', - 'azf' => 'application/vnd.airzip.filesecure.azf', - 'azs' => 'application/vnd.airzip.filesecure.azs', - 'azw' => 'application/vnd.amazon.ebook', - 'bat' => 'application/x-msdownload', - 'bcpio' => 'application/x-bcpio', - 'bdf' => 'application/x-font-bdf', - 'bdm' => 'application/vnd.syncml.dm+wbxml', - 'bed' => 'application/vnd.realvnc.bed', - 'bh2' => 'application/vnd.fujitsu.oasysprs', - 'bin' => 'application/octet-stream', - 'blb' => 'application/x-blorb', - 'blorb' => 'application/x-blorb', - 'bmi' => 'application/vnd.bmi', - 'bmp' => 'image/bmp', - 'book' => 'application/vnd.framemaker', - 'box' => 'application/vnd.previewsystems.box', - 'boz' => 'application/x-bzip2', - 'bpk' => 'application/octet-stream', - 'btif' => 'image/prs.btif', - 'bz' => 'application/x-bzip', - 'bz2' => 'application/x-bzip2', - 'c' => 'text/x-c', - 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', - 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', - 'c4d' => 'application/vnd.clonk.c4group', - 'c4f' => 'application/vnd.clonk.c4group', - 'c4g' => 'application/vnd.clonk.c4group', - 'c4p' => 'application/vnd.clonk.c4group', - 'c4u' => 'application/vnd.clonk.c4group', - 'cab' => 'application/vnd.ms-cab-compressed', - 'caf' => 'audio/x-caf', - 'cap' => 'application/vnd.tcpdump.pcap', - 'car' => 'application/vnd.curl.car', - 'cat' => 'application/vnd.ms-pki.seccat', - 'cb7' => 'application/x-cbr', - 'cba' => 'application/x-cbr', - 'cbr' => 'application/x-cbr', - 'cbt' => 'application/x-cbr', - 'cbz' => 'application/x-cbr', - 'cc' => 'text/x-c', - 'cct' => 'application/x-director', - 'ccxml' => 'application/ccxml+xml', - 'cdbcmsg' => 'application/vnd.contact.cmsg', - 'cdf' => 'application/x-netcdf', - 'cdkey' => 'application/vnd.mediastation.cdkey', - 'cdmia' => 'application/cdmi-capability', - 'cdmic' => 'application/cdmi-container', - 'cdmid' => 'application/cdmi-domain', - 'cdmio' => 'application/cdmi-object', - 'cdmiq' => 'application/cdmi-queue', - 'cdx' => 'chemical/x-cdx', - 'cdxml' => 'application/vnd.chemdraw+xml', - 'cdy' => 'application/vnd.cinderella', - 'cer' => 'application/pkix-cert', - 'cfs' => 'application/x-cfs-compressed', - 'cgm' => 'image/cgm', - 'chat' => 'application/x-chat', - 'chm' => 'application/vnd.ms-htmlhelp', - 'chrt' => 'application/vnd.kde.kchart', - 'cif' => 'chemical/x-cif', - 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', - 'cil' => 'application/vnd.ms-artgalry', - 'cla' => 'application/vnd.claymore', - 'class' => 'application/java-vm', - 'clkk' => 'application/vnd.crick.clicker.keyboard', - 'clkp' => 'application/vnd.crick.clicker.palette', - 'clkt' => 'application/vnd.crick.clicker.template', - 'clkw' => 'application/vnd.crick.clicker.wordbank', - 'clkx' => 'application/vnd.crick.clicker', - 'clp' => 'application/x-msclip', - 'cmc' => 'application/vnd.cosmocaller', - 'cmdf' => 'chemical/x-cmdf', - 'cml' => 'chemical/x-cml', - 'cmp' => 'application/vnd.yellowriver-custom-menu', - 'cmx' => 'image/x-cmx', - 'cod' => 'application/vnd.rim.cod', - 'com' => 'application/x-msdownload', - 'conf' => 'text/plain', - 'cpio' => 'application/x-cpio', - 'cpp' => 'text/x-c', - 'cpt' => 'application/mac-compactpro', - 'crd' => 'application/x-mscardfile', - 'crl' => 'application/pkix-crl', - 'crt' => 'application/x-x509-ca-cert', - 'cryptonote' => 'application/vnd.rig.cryptonote', - 'csh' => 'application/x-csh', - 'csml' => 'chemical/x-csml', - 'csp' => 'application/vnd.commonspace', - 'css' => 'text/css', - 'cst' => 'application/x-director', - 'csv' => 'text/csv', - 'cu' => 'application/cu-seeme', - 'curl' => 'text/vnd.curl', - 'cww' => 'application/prs.cww', - 'cxt' => 'application/x-director', - 'cxx' => 'text/x-c', - 'dae' => 'model/vnd.collada+xml', - 'daf' => 'application/vnd.mobius.daf', - 'dart' => 'application/vnd.dart', - 'dataless' => 'application/vnd.fdsn.seed', - 'davmount' => 'application/davmount+xml', - 'dbk' => 'application/docbook+xml', - 'dcr' => 'application/x-director', - 'dcurl' => 'text/vnd.curl.dcurl', - 'dd2' => 'application/vnd.oma.dd2+xml', - 'ddd' => 'application/vnd.fujixerox.ddd', - 'deb' => 'application/x-debian-package', - 'def' => 'text/plain', - 'deploy' => 'application/octet-stream', - 'der' => 'application/x-x509-ca-cert', - 'dfac' => 'application/vnd.dreamfactory', - 'dgc' => 'application/x-dgc-compressed', - 'dic' => 'text/x-c', - 'dir' => 'application/x-director', - 'dis' => 'application/vnd.mobius.dis', - 'dist' => 'application/octet-stream', - 'distz' => 'application/octet-stream', - 'djv' => 'image/vnd.djvu', - 'djvu' => 'image/vnd.djvu', - 'dll' => 'application/x-msdownload', - 'dmg' => 'application/x-apple-diskimage', - 'dmp' => 'application/vnd.tcpdump.pcap', - 'dms' => 'application/octet-stream', - 'dna' => 'application/vnd.dna', - 'doc' => 'application/msword', - 'docm' => 'application/vnd.ms-word.document.macroenabled.12', - 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'dot' => 'application/msword', - 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', - 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', - 'dp' => 'application/vnd.osgi.dp', - 'dpg' => 'application/vnd.dpgraph', - 'dra' => 'audio/vnd.dra', - 'dsc' => 'text/prs.lines.tag', - 'dssc' => 'application/dssc+der', - 'dtb' => 'application/x-dtbook+xml', - 'dtd' => 'application/xml-dtd', - 'dts' => 'audio/vnd.dts', - 'dtshd' => 'audio/vnd.dts.hd', - 'dump' => 'application/octet-stream', - 'dvb' => 'video/vnd.dvb.file', - 'dvi' => 'application/x-dvi', - 'dwf' => 'model/vnd.dwf', - 'dwg' => 'image/vnd.dwg', - 'dxf' => 'image/vnd.dxf', - 'dxp' => 'application/vnd.spotfire.dxp', - 'dxr' => 'application/x-director', - 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', - 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', - 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', - 'ecma' => 'application/ecmascript', - 'edm' => 'application/vnd.novadigm.edm', - 'edx' => 'application/vnd.novadigm.edx', - 'efif' => 'application/vnd.picsel', - 'ei6' => 'application/vnd.pg.osasli', - 'elc' => 'application/octet-stream', - 'emf' => 'application/x-msmetafile', - 'eml' => 'message/rfc822', - 'emma' => 'application/emma+xml', - 'emz' => 'application/x-msmetafile', - 'eol' => 'audio/vnd.digital-winds', - 'eot' => 'application/vnd.ms-fontobject', - 'eps' => 'application/postscript', - 'epub' => 'application/epub+zip', - 'es3' => 'application/vnd.eszigno3+xml', - 'esa' => 'application/vnd.osgi.subsystem', - 'esf' => 'application/vnd.epson.esf', - 'et3' => 'application/vnd.eszigno3+xml', - 'etx' => 'text/x-setext', - 'eva' => 'application/x-eva', - 'evy' => 'application/x-envoy', - 'exe' => 'application/x-msdownload', - 'exi' => 'application/exi', - 'ext' => 'application/vnd.novadigm.ext', - 'ez' => 'application/andrew-inset', - 'ez2' => 'application/vnd.ezpix-album', - 'ez3' => 'application/vnd.ezpix-package', - 'f' => 'text/x-fortran', - 'f4v' => 'video/x-f4v', - 'f77' => 'text/x-fortran', - 'f90' => 'text/x-fortran', - 'fbs' => 'image/vnd.fastbidsheet', - 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', - 'fcs' => 'application/vnd.isac.fcs', - 'fdf' => 'application/vnd.fdf', - 'fe_launch' => 'application/vnd.denovo.fcselayout-link', - 'fg5' => 'application/vnd.fujitsu.oasysgp', - 'fgd' => 'application/x-director', - 'fh' => 'image/x-freehand', - 'fh4' => 'image/x-freehand', - 'fh5' => 'image/x-freehand', - 'fh7' => 'image/x-freehand', - 'fhc' => 'image/x-freehand', - 'fig' => 'application/x-xfig', - 'flac' => 'audio/x-flac', - 'fli' => 'video/x-fli', - 'flo' => 'application/vnd.micrografx.flo', - 'flv' => 'video/x-flv', - 'flw' => 'application/vnd.kde.kivio', - 'flx' => 'text/vnd.fmi.flexstor', - 'fly' => 'text/vnd.fly', - 'fm' => 'application/vnd.framemaker', - 'fnc' => 'application/vnd.frogans.fnc', - 'for' => 'text/x-fortran', - 'fpx' => 'image/vnd.fpx', - 'frame' => 'application/vnd.framemaker', - 'fsc' => 'application/vnd.fsc.weblaunch', - 'fst' => 'image/vnd.fst', - 'ftc' => 'application/vnd.fluxtime.clip', - 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', - 'fvt' => 'video/vnd.fvt', - 'fxp' => 'application/vnd.adobe.fxp', - 'fxpl' => 'application/vnd.adobe.fxp', - 'fzs' => 'application/vnd.fuzzysheet', - 'g2w' => 'application/vnd.geoplan', - 'g3' => 'image/g3fax', - 'g3w' => 'application/vnd.geospace', - 'gac' => 'application/vnd.groove-account', - 'gam' => 'application/x-tads', - 'gbr' => 'application/rpki-ghostbusters', - 'gca' => 'application/x-gca-compressed', - 'gdl' => 'model/vnd.gdl', - 'geo' => 'application/vnd.dynageo', - 'gex' => 'application/vnd.geometry-explorer', - 'ggb' => 'application/vnd.geogebra.file', - 'ggt' => 'application/vnd.geogebra.tool', - 'ghf' => 'application/vnd.groove-help', - 'gif' => 'image/gif', - 'gim' => 'application/vnd.groove-identity-message', - 'gml' => 'application/gml+xml', - 'gmx' => 'application/vnd.gmx', - 'gnumeric' => 'application/x-gnumeric', - 'gph' => 'application/vnd.flographit', - 'gpx' => 'application/gpx+xml', - 'gqf' => 'application/vnd.grafeq', - 'gqs' => 'application/vnd.grafeq', - 'gram' => 'application/srgs', - 'gramps' => 'application/x-gramps-xml', - 'gre' => 'application/vnd.geometry-explorer', - 'grv' => 'application/vnd.groove-injector', - 'grxml' => 'application/srgs+xml', - 'gsf' => 'application/x-font-ghostscript', - 'gtar' => 'application/x-gtar', - 'gtm' => 'application/vnd.groove-tool-message', - 'gtw' => 'model/vnd.gtw', - 'gv' => 'text/vnd.graphviz', - 'gxf' => 'application/gxf', - 'gxt' => 'application/vnd.geonext', - 'h' => 'text/x-c', - 'h261' => 'video/h261', - 'h263' => 'video/h263', - 'h264' => 'video/h264', - 'hal' => 'application/vnd.hal+xml', - 'hbci' => 'application/vnd.hbci', - 'hdf' => 'application/x-hdf', - 'hh' => 'text/x-c', - 'hlp' => 'application/winhlp', - 'hpgl' => 'application/vnd.hp-hpgl', - 'hpid' => 'application/vnd.hp-hpid', - 'hps' => 'application/vnd.hp-hps', - 'hqx' => 'application/mac-binhex40', - 'htke' => 'application/vnd.kenameaapp', - 'htm' => 'text/html', - 'html' => 'text/html', - 'hvd' => 'application/vnd.yamaha.hv-dic', - 'hvp' => 'application/vnd.yamaha.hv-voice', - 'hvs' => 'application/vnd.yamaha.hv-script', - 'i2g' => 'application/vnd.intergeo', - 'icc' => 'application/vnd.iccprofile', - 'ice' => 'x-conference/x-cooltalk', - 'icm' => 'application/vnd.iccprofile', - 'ico' => 'image/x-icon', - 'ics' => 'text/calendar', - 'ief' => 'image/ief', - 'ifb' => 'text/calendar', - 'ifm' => 'application/vnd.shana.informed.formdata', - 'iges' => 'model/iges', - 'igl' => 'application/vnd.igloader', - 'igm' => 'application/vnd.insors.igm', - 'igs' => 'model/iges', - 'igx' => 'application/vnd.micrografx.igx', - 'iif' => 'application/vnd.shana.informed.interchange', - 'imp' => 'application/vnd.accpac.simply.imp', - 'ims' => 'application/vnd.ms-ims', - 'in' => 'text/plain', - 'ink' => 'application/inkml+xml', - 'inkml' => 'application/inkml+xml', - 'install' => 'application/x-install-instructions', - 'iota' => 'application/vnd.astraea-software.iota', - 'ipfix' => 'application/ipfix', - 'ipk' => 'application/vnd.shana.informed.package', - 'irm' => 'application/vnd.ibm.rights-management', - 'irp' => 'application/vnd.irepository.package+xml', - 'iso' => 'application/x-iso9660-image', - 'itp' => 'application/vnd.shana.informed.formtemplate', - 'ivp' => 'application/vnd.immervision-ivp', - 'ivu' => 'application/vnd.immervision-ivu', - 'jad' => 'text/vnd.sun.j2me.app-descriptor', - 'jam' => 'application/vnd.jam', - 'jar' => 'application/java-archive', - 'java' => 'text/x-java-source', - 'jisp' => 'application/vnd.jisp', - 'jlt' => 'application/vnd.hp-jlyt', - 'jnlp' => 'application/x-java-jnlp-file', - 'joda' => 'application/vnd.joost.joda-archive', - 'jpe' => 'image/jpeg', - 'jpeg' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'jpgm' => 'video/jpm', - 'jpgv' => 'video/jpeg', - 'jpm' => 'video/jpm', - 'js' => 'application/javascript', - 'json' => 'application/json', - 'jsonml' => 'application/jsonml+json', - 'kar' => 'audio/midi', - 'karbon' => 'application/vnd.kde.karbon', - 'kfo' => 'application/vnd.kde.kformula', - 'kia' => 'application/vnd.kidspiration', - 'kml' => 'application/vnd.google-earth.kml+xml', - 'kmz' => 'application/vnd.google-earth.kmz', - 'kne' => 'application/vnd.kinar', - 'knp' => 'application/vnd.kinar', - 'kon' => 'application/vnd.kde.kontour', - 'kpr' => 'application/vnd.kde.kpresenter', - 'kpt' => 'application/vnd.kde.kpresenter', - 'kpxx' => 'application/vnd.ds-keypoint', - 'ksp' => 'application/vnd.kde.kspread', - 'ktr' => 'application/vnd.kahootz', - 'ktx' => 'image/ktx', - 'ktz' => 'application/vnd.kahootz', - 'kwd' => 'application/vnd.kde.kword', - 'kwt' => 'application/vnd.kde.kword', - 'lasxml' => 'application/vnd.las.las+xml', - 'latex' => 'application/x-latex', - 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', - 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', - 'les' => 'application/vnd.hhe.lesson-player', - 'lha' => 'application/x-lzh-compressed', - 'link66' => 'application/vnd.route66.link66+xml', - 'list' => 'text/plain', - 'list3820' => 'application/vnd.ibm.modcap', - 'listafp' => 'application/vnd.ibm.modcap', - 'lnk' => 'application/x-ms-shortcut', - 'log' => 'text/plain', - 'lostxml' => 'application/lost+xml', - 'lrf' => 'application/octet-stream', - 'lrm' => 'application/vnd.ms-lrm', - 'ltf' => 'application/vnd.frogans.ltf', - 'lvp' => 'audio/vnd.lucent.voice', - 'lwp' => 'application/vnd.lotus-wordpro', - 'lzh' => 'application/x-lzh-compressed', - 'm13' => 'application/x-msmediaview', - 'm14' => 'application/x-msmediaview', - 'm1v' => 'video/mpeg', - 'm21' => 'application/mp21', - 'm2a' => 'audio/mpeg', - 'm2v' => 'video/mpeg', - 'm3a' => 'audio/mpeg', - 'm3u' => 'audio/x-mpegurl', - 'm3u8' => 'application/vnd.apple.mpegurl', - 'm4a' => 'audio/mp4', - 'm4u' => 'video/vnd.mpegurl', - 'm4v' => 'video/x-m4v', - 'ma' => 'application/mathematica', - 'mads' => 'application/mads+xml', - 'mag' => 'application/vnd.ecowin.chart', - 'maker' => 'application/vnd.framemaker', - 'man' => 'text/troff', - 'mar' => 'application/octet-stream', - 'mathml' => 'application/mathml+xml', - 'mb' => 'application/mathematica', - 'mbk' => 'application/vnd.mobius.mbk', - 'mbox' => 'application/mbox', - 'mc1' => 'application/vnd.medcalcdata', - 'mcd' => 'application/vnd.mcd', - 'mcurl' => 'text/vnd.curl.mcurl', - 'mdb' => 'application/x-msaccess', - 'mdi' => 'image/vnd.ms-modi', - 'me' => 'text/troff', - 'mesh' => 'model/mesh', - 'meta4' => 'application/metalink4+xml', - 'metalink' => 'application/metalink+xml', - 'mets' => 'application/mets+xml', - 'mfm' => 'application/vnd.mfmp', - 'mft' => 'application/rpki-manifest', - 'mgp' => 'application/vnd.osgeo.mapguide.package', - 'mgz' => 'application/vnd.proteus.magazine', - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mie' => 'application/x-mie', - 'mif' => 'application/vnd.mif', - 'mime' => 'message/rfc822', - 'mj2' => 'video/mj2', - 'mjp2' => 'video/mj2', - 'mk3d' => 'video/x-matroska', - 'mka' => 'audio/x-matroska', - 'mks' => 'video/x-matroska', - 'mkv' => 'video/x-matroska', - 'mlp' => 'application/vnd.dolby.mlp', - 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', - 'mmf' => 'application/vnd.smaf', - 'mmr' => 'image/vnd.fujixerox.edmics-mmr', - 'mng' => 'video/x-mng', - 'mny' => 'application/x-msmoney', - 'mobi' => 'application/x-mobipocket-ebook', - 'mods' => 'application/mods+xml', - 'mov' => 'video/quicktime', - 'movie' => 'video/x-sgi-movie', - 'mp2' => 'audio/mpeg', - 'mp21' => 'application/mp21', - 'mp2a' => 'audio/mpeg', - 'mp3' => 'audio/mpeg', - 'mp4' => 'video/mp4', - 'mp4a' => 'audio/mp4', - 'mp4s' => 'application/mp4', - 'mp4v' => 'video/mp4', - 'mpc' => 'application/vnd.mophun.certificate', - 'mpe' => 'video/mpeg', - 'mpeg' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mpg4' => 'video/mp4', - 'mpga' => 'audio/mpeg', - 'mpkg' => 'application/vnd.apple.installer+xml', - 'mpm' => 'application/vnd.blueice.multipass', - 'mpn' => 'application/vnd.mophun.application', - 'mpp' => 'application/vnd.ms-project', - 'mpt' => 'application/vnd.ms-project', - 'mpy' => 'application/vnd.ibm.minipay', - 'mqy' => 'application/vnd.mobius.mqy', - 'mrc' => 'application/marc', - 'mrcx' => 'application/marcxml+xml', - 'ms' => 'text/troff', - 'mscml' => 'application/mediaservercontrol+xml', - 'mseed' => 'application/vnd.fdsn.mseed', - 'mseq' => 'application/vnd.mseq', - 'msf' => 'application/vnd.epson.msf', - 'msh' => 'model/mesh', - 'msi' => 'application/x-msdownload', - 'msl' => 'application/vnd.mobius.msl', - 'msty' => 'application/vnd.muvee.style', - 'mts' => 'model/vnd.mts', - 'mus' => 'application/vnd.musician', - 'musicxml' => 'application/vnd.recordare.musicxml+xml', - 'mvb' => 'application/x-msmediaview', - 'mwf' => 'application/vnd.mfer', - 'mxf' => 'application/mxf', - 'mxl' => 'application/vnd.recordare.musicxml', - 'mxml' => 'application/xv+xml', - 'mxs' => 'application/vnd.triscape.mxs', - 'mxu' => 'video/vnd.mpegurl', - 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', - 'n3' => 'text/n3', - 'nb' => 'application/mathematica', - 'nbp' => 'application/vnd.wolfram.player', - 'nc' => 'application/x-netcdf', - 'ncx' => 'application/x-dtbncx+xml', - 'nfo' => 'text/x-nfo', - 'ngdat' => 'application/vnd.nokia.n-gage.data', - 'nitf' => 'application/vnd.nitf', - 'nlu' => 'application/vnd.neurolanguage.nlu', - 'nml' => 'application/vnd.enliven', - 'nnd' => 'application/vnd.noblenet-directory', - 'nns' => 'application/vnd.noblenet-sealer', - 'nnw' => 'application/vnd.noblenet-web', - 'npx' => 'image/vnd.net-fpx', - 'nsc' => 'application/x-conference', - 'nsf' => 'application/vnd.lotus-notes', - 'ntf' => 'application/vnd.nitf', - 'nzb' => 'application/x-nzb', - 'oa2' => 'application/vnd.fujitsu.oasys2', - 'oa3' => 'application/vnd.fujitsu.oasys3', - 'oas' => 'application/vnd.fujitsu.oasys', - 'obd' => 'application/x-msbinder', - 'obj' => 'application/x-tgif', - 'oda' => 'application/oda', - 'odb' => 'application/vnd.oasis.opendocument.database', - 'odc' => 'application/vnd.oasis.opendocument.chart', - 'odf' => 'application/vnd.oasis.opendocument.formula', - 'odft' => 'application/vnd.oasis.opendocument.formula-template', - 'odg' => 'application/vnd.oasis.opendocument.graphics', - 'odi' => 'application/vnd.oasis.opendocument.image', - 'odm' => 'application/vnd.oasis.opendocument.text-master', - 'odp' => 'application/vnd.oasis.opendocument.presentation', - 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', - 'odt' => 'application/vnd.oasis.opendocument.text', - 'oga' => 'audio/ogg', - 'ogg' => 'audio/ogg', - 'ogv' => 'video/ogg', - 'ogx' => 'application/ogg', - 'omdoc' => 'application/omdoc+xml', - 'onepkg' => 'application/onenote', - 'onetmp' => 'application/onenote', - 'onetoc' => 'application/onenote', - 'onetoc2' => 'application/onenote', - 'opf' => 'application/oebps-package+xml', - 'opml' => 'text/x-opml', - 'oprc' => 'application/vnd.palm', - 'opus' => 'audio/ogg', - 'org' => 'application/vnd.lotus-organizer', - 'osf' => 'application/vnd.yamaha.openscoreformat', - 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', - 'otc' => 'application/vnd.oasis.opendocument.chart-template', - 'otf' => 'font/otf', - 'otg' => 'application/vnd.oasis.opendocument.graphics-template', - 'oth' => 'application/vnd.oasis.opendocument.text-web', - 'oti' => 'application/vnd.oasis.opendocument.image-template', - 'otp' => 'application/vnd.oasis.opendocument.presentation-template', - 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', - 'ott' => 'application/vnd.oasis.opendocument.text-template', - 'oxps' => 'application/oxps', - 'oxt' => 'application/vnd.openofficeorg.extension', - 'p' => 'text/x-pascal', - 'p10' => 'application/pkcs10', - 'p12' => 'application/x-pkcs12', - 'p7b' => 'application/x-pkcs7-certificates', - 'p7c' => 'application/pkcs7-mime', - 'p7m' => 'application/pkcs7-mime', - 'p7r' => 'application/x-pkcs7-certreqresp', - 'p7s' => 'application/pkcs7-signature', - 'p8' => 'application/pkcs8', - 'pas' => 'text/x-pascal', - 'paw' => 'application/vnd.pawaafile', - 'pbd' => 'application/vnd.powerbuilder6', - 'pbm' => 'image/x-portable-bitmap', - 'pcap' => 'application/vnd.tcpdump.pcap', - 'pcf' => 'application/x-font-pcf', - 'pcl' => 'application/vnd.hp-pcl', - 'pclxl' => 'application/vnd.hp-pclxl', - 'pct' => 'image/x-pict', - 'pcurl' => 'application/vnd.curl.pcurl', - 'pcx' => 'image/x-pcx', - 'pdb' => 'application/vnd.palm', - 'pdf' => 'application/pdf', - 'pfa' => 'application/x-font-type1', - 'pfb' => 'application/x-font-type1', - 'pfm' => 'application/x-font-type1', - 'pfr' => 'application/font-tdpfr', - 'pfx' => 'application/x-pkcs12', - 'pgm' => 'image/x-portable-graymap', - 'pgn' => 'application/x-chess-pgn', - 'pgp' => 'application/pgp-encrypted', - 'pic' => 'image/x-pict', - 'pkg' => 'application/octet-stream', - 'pki' => 'application/pkixcmp', - 'pkipath' => 'application/pkix-pkipath', - 'plb' => 'application/vnd.3gpp.pic-bw-large', - 'plc' => 'application/vnd.mobius.plc', - 'plf' => 'application/vnd.pocketlearn', - 'pls' => 'application/pls+xml', - 'pml' => 'application/vnd.ctc-posml', - 'png' => 'image/png', - 'pnm' => 'image/x-portable-anymap', - 'portpkg' => 'application/vnd.macports.portpkg', - 'pot' => 'application/vnd.ms-powerpoint', - 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', - 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', - 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', - 'ppd' => 'application/vnd.cups-ppd', - 'ppm' => 'image/x-portable-pixmap', - 'pps' => 'application/vnd.ms-powerpoint', - 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', - 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', - 'ppt' => 'application/vnd.ms-powerpoint', - 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', - 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', - 'pqa' => 'application/vnd.palm', - 'prc' => 'application/x-mobipocket-ebook', - 'pre' => 'application/vnd.lotus-freelance', - 'prf' => 'application/pics-rules', - 'ps' => 'application/postscript', - 'psb' => 'application/vnd.3gpp.pic-bw-small', - 'psd' => 'image/vnd.adobe.photoshop', - 'psf' => 'application/x-font-linux-psf', - 'pskcxml' => 'application/pskc+xml', - 'ptid' => 'application/vnd.pvi.ptid1', - 'pub' => 'application/x-mspublisher', - 'pvb' => 'application/vnd.3gpp.pic-bw-var', - 'pwn' => 'application/vnd.3m.post-it-notes', - 'pya' => 'audio/vnd.ms-playready.media.pya', - 'pyv' => 'video/vnd.ms-playready.media.pyv', - 'qam' => 'application/vnd.epson.quickanime', - 'qbo' => 'application/vnd.intu.qbo', - 'qfx' => 'application/vnd.intu.qfx', - 'qps' => 'application/vnd.publishare-delta-tree', - 'qt' => 'video/quicktime', - 'qwd' => 'application/vnd.quark.quarkxpress', - 'qwt' => 'application/vnd.quark.quarkxpress', - 'qxb' => 'application/vnd.quark.quarkxpress', - 'qxd' => 'application/vnd.quark.quarkxpress', - 'qxl' => 'application/vnd.quark.quarkxpress', - 'qxt' => 'application/vnd.quark.quarkxpress', - 'ra' => 'audio/x-pn-realaudio', - 'ram' => 'audio/x-pn-realaudio', - 'rar' => 'application/x-rar-compressed', - 'ras' => 'image/x-cmu-raster', - 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', - 'rdf' => 'application/rdf+xml', - 'rdz' => 'application/vnd.data-vision.rdz', - 'rep' => 'application/vnd.businessobjects', - 'res' => 'application/x-dtbresource+xml', - 'rgb' => 'image/x-rgb', - 'rif' => 'application/reginfo+xml', - 'rip' => 'audio/vnd.rip', - 'ris' => 'application/x-research-info-systems', - 'rl' => 'application/resource-lists+xml', - 'rlc' => 'image/vnd.fujixerox.edmics-rlc', - 'rld' => 'application/resource-lists-diff+xml', - 'rm' => 'application/vnd.rn-realmedia', - 'rmi' => 'audio/midi', - 'rmp' => 'audio/x-pn-realaudio-plugin', - 'rms' => 'application/vnd.jcp.javame.midlet-rms', - 'rmvb' => 'application/vnd.rn-realmedia-vbr', - 'rnc' => 'application/relax-ng-compact-syntax', - 'roa' => 'application/rpki-roa', - 'roff' => 'text/troff', - 'rp9' => 'application/vnd.cloanto.rp9', - 'rpss' => 'application/vnd.nokia.radio-presets', - 'rpst' => 'application/vnd.nokia.radio-preset', - 'rq' => 'application/sparql-query', - 'rs' => 'application/rls-services+xml', - 'rsd' => 'application/rsd+xml', - 'rss' => 'application/rss+xml', - 'rtf' => 'application/rtf', - 'rtx' => 'text/richtext', - 's' => 'text/x-asm', - 's3m' => 'audio/s3m', - 'saf' => 'application/vnd.yamaha.smaf-audio', - 'sbml' => 'application/sbml+xml', - 'sc' => 'application/vnd.ibm.secure-container', - 'scd' => 'application/x-msschedule', - 'scm' => 'application/vnd.lotus-screencam', - 'scq' => 'application/scvp-cv-request', - 'scs' => 'application/scvp-cv-response', - 'scurl' => 'text/vnd.curl.scurl', - 'sda' => 'application/vnd.stardivision.draw', - 'sdc' => 'application/vnd.stardivision.calc', - 'sdd' => 'application/vnd.stardivision.impress', - 'sdkd' => 'application/vnd.solent.sdkm+xml', - 'sdkm' => 'application/vnd.solent.sdkm+xml', - 'sdp' => 'application/sdp', - 'sdw' => 'application/vnd.stardivision.writer', - 'see' => 'application/vnd.seemail', - 'seed' => 'application/vnd.fdsn.seed', - 'sema' => 'application/vnd.sema', - 'semd' => 'application/vnd.semd', - 'semf' => 'application/vnd.semf', - 'ser' => 'application/java-serialized-object', - 'setpay' => 'application/set-payment-initiation', - 'setreg' => 'application/set-registration-initiation', - 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', - 'sfs' => 'application/vnd.spotfire.sfs', - 'sfv' => 'text/x-sfv', - 'sgi' => 'image/sgi', - 'sgl' => 'application/vnd.stardivision.writer-global', - 'sgm' => 'text/sgml', - 'sgml' => 'text/sgml', - 'sh' => 'application/x-sh', - 'shar' => 'application/x-shar', - 'shf' => 'application/shf+xml', - 'sid' => 'image/x-mrsid-image', - 'sig' => 'application/pgp-signature', - 'sil' => 'audio/silk', - 'silo' => 'model/mesh', - 'sis' => 'application/vnd.symbian.install', - 'sisx' => 'application/vnd.symbian.install', - 'sit' => 'application/x-stuffit', - 'sitx' => 'application/x-stuffitx', - 'skd' => 'application/vnd.koan', - 'skm' => 'application/vnd.koan', - 'skp' => 'application/vnd.koan', - 'skt' => 'application/vnd.koan', - 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', - 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', - 'slt' => 'application/vnd.epson.salt', - 'sm' => 'application/vnd.stepmania.stepchart', - 'smf' => 'application/vnd.stardivision.math', - 'smi' => 'application/smil+xml', - 'smil' => 'application/smil+xml', - 'smv' => 'video/x-smv', - 'smzip' => 'application/vnd.stepmania.package', - 'snd' => 'audio/basic', - 'snf' => 'application/x-font-snf', - 'so' => 'application/octet-stream', - 'spc' => 'application/x-pkcs7-certificates', - 'spf' => 'application/vnd.yamaha.smaf-phrase', - 'spl' => 'application/x-futuresplash', - 'spot' => 'text/vnd.in3d.spot', - 'spp' => 'application/scvp-vp-response', - 'spq' => 'application/scvp-vp-request', - 'spx' => 'audio/ogg', - 'sql' => 'application/x-sql', - 'src' => 'application/x-wais-source', - 'srt' => 'application/x-subrip', - 'sru' => 'application/sru+xml', - 'srx' => 'application/sparql-results+xml', - 'ssdl' => 'application/ssdl+xml', - 'sse' => 'application/vnd.kodak-descriptor', - 'ssf' => 'application/vnd.epson.ssf', - 'ssml' => 'application/ssml+xml', - 'st' => 'application/vnd.sailingtracker.track', - 'stc' => 'application/vnd.sun.xml.calc.template', - 'std' => 'application/vnd.sun.xml.draw.template', - 'stf' => 'application/vnd.wt.stf', - 'sti' => 'application/vnd.sun.xml.impress.template', - 'stk' => 'application/hyperstudio', - 'stl' => 'application/vnd.ms-pki.stl', - 'str' => 'application/vnd.pg.format', - 'stw' => 'application/vnd.sun.xml.writer.template', - 'sub' => 'text/vnd.dvb.subtitle', - 'sus' => 'application/vnd.sus-calendar', - 'susp' => 'application/vnd.sus-calendar', - 'sv4cpio' => 'application/x-sv4cpio', - 'sv4crc' => 'application/x-sv4crc', - 'svc' => 'application/vnd.dvb.service', - 'svd' => 'application/vnd.svd', - 'svg' => 'image/svg+xml', - 'svgz' => 'image/svg+xml', - 'swa' => 'application/x-director', - 'swf' => 'application/x-shockwave-flash', - 'swi' => 'application/vnd.aristanetworks.swi', - 'sxc' => 'application/vnd.sun.xml.calc', - 'sxd' => 'application/vnd.sun.xml.draw', - 'sxg' => 'application/vnd.sun.xml.writer.global', - 'sxi' => 'application/vnd.sun.xml.impress', - 'sxm' => 'application/vnd.sun.xml.math', - 'sxw' => 'application/vnd.sun.xml.writer', - 't' => 'text/troff', - 't3' => 'application/x-t3vm-image', - 'taglet' => 'application/vnd.mynfc', - 'tao' => 'application/vnd.tao.intent-module-archive', - 'tar' => 'application/x-tar', - 'tcap' => 'application/vnd.3gpp2.tcap', - 'tcl' => 'application/x-tcl', - 'teacher' => 'application/vnd.smart.teacher', - 'tei' => 'application/tei+xml', - 'teicorpus' => 'application/tei+xml', - 'tex' => 'application/x-tex', - 'texi' => 'application/x-texinfo', - 'texinfo' => 'application/x-texinfo', - 'text' => 'text/plain', - 'tfi' => 'application/thraud+xml', - 'tfm' => 'application/x-tex-tfm', - 'tga' => 'image/x-tga', - 'thmx' => 'application/vnd.ms-officetheme', - 'tif' => 'image/tiff', - 'tiff' => 'image/tiff', - 'tmo' => 'application/vnd.tmobile-livetv', - 'torrent' => 'application/x-bittorrent', - 'tpl' => 'application/vnd.groove-tool-template', - 'tpt' => 'application/vnd.trid.tpt', - 'tr' => 'text/troff', - 'tra' => 'application/vnd.trueapp', - 'trm' => 'application/x-msterminal', - 'tsd' => 'application/timestamped-data', - 'tsv' => 'text/tab-separated-values', - 'ttc' => 'font/collection', - 'ttf' => 'font/ttf', - 'ttl' => 'text/turtle', - 'twd' => 'application/vnd.simtech-mindmapper', - 'twds' => 'application/vnd.simtech-mindmapper', - 'txd' => 'application/vnd.genomatix.tuxedo', - 'txf' => 'application/vnd.mobius.txf', - 'txt' => 'text/plain', - 'u32' => 'application/x-authorware-bin', - 'udeb' => 'application/x-debian-package', - 'ufd' => 'application/vnd.ufdl', - 'ufdl' => 'application/vnd.ufdl', - 'ulx' => 'application/x-glulx', - 'umj' => 'application/vnd.umajin', - 'unityweb' => 'application/vnd.unity', - 'uoml' => 'application/vnd.uoml+xml', - 'uri' => 'text/uri-list', - 'uris' => 'text/uri-list', - 'urls' => 'text/uri-list', - 'ustar' => 'application/x-ustar', - 'utz' => 'application/vnd.uiq.theme', - 'uu' => 'text/x-uuencode', - 'uva' => 'audio/vnd.dece.audio', - 'uvd' => 'application/vnd.dece.data', - 'uvf' => 'application/vnd.dece.data', - 'uvg' => 'image/vnd.dece.graphic', - 'uvh' => 'video/vnd.dece.hd', - 'uvi' => 'image/vnd.dece.graphic', - 'uvm' => 'video/vnd.dece.mobile', - 'uvp' => 'video/vnd.dece.pd', - 'uvs' => 'video/vnd.dece.sd', - 'uvt' => 'application/vnd.dece.ttml+xml', - 'uvu' => 'video/vnd.uvvu.mp4', - 'uvv' => 'video/vnd.dece.video', - 'uvva' => 'audio/vnd.dece.audio', - 'uvvd' => 'application/vnd.dece.data', - 'uvvf' => 'application/vnd.dece.data', - 'uvvg' => 'image/vnd.dece.graphic', - 'uvvh' => 'video/vnd.dece.hd', - 'uvvi' => 'image/vnd.dece.graphic', - 'uvvm' => 'video/vnd.dece.mobile', - 'uvvp' => 'video/vnd.dece.pd', - 'uvvs' => 'video/vnd.dece.sd', - 'uvvt' => 'application/vnd.dece.ttml+xml', - 'uvvu' => 'video/vnd.uvvu.mp4', - 'uvvv' => 'video/vnd.dece.video', - 'uvvx' => 'application/vnd.dece.unspecified', - 'uvvz' => 'application/vnd.dece.zip', - 'uvx' => 'application/vnd.dece.unspecified', - 'uvz' => 'application/vnd.dece.zip', - 'vcard' => 'text/vcard', - 'vcd' => 'application/x-cdlink', - 'vcf' => 'text/x-vcard', - 'vcg' => 'application/vnd.groove-vcard', - 'vcs' => 'text/x-vcalendar', - 'vcx' => 'application/vnd.vcx', - 'vis' => 'application/vnd.visionary', - 'viv' => 'video/vnd.vivo', - 'vob' => 'video/x-ms-vob', - 'vor' => 'application/vnd.stardivision.writer', - 'vox' => 'application/x-authorware-bin', - 'vrml' => 'model/vrml', - 'vsd' => 'application/vnd.visio', - 'vsf' => 'application/vnd.vsf', - 'vss' => 'application/vnd.visio', - 'vst' => 'application/vnd.visio', - 'vsw' => 'application/vnd.visio', - 'vtu' => 'model/vnd.vtu', - 'vxml' => 'application/voicexml+xml', - 'w3d' => 'application/x-director', - 'wad' => 'application/x-doom', - 'wav' => 'audio/x-wav', - 'wax' => 'audio/x-ms-wax', - 'wbmp' => 'image/vnd.wap.wbmp', - 'wbs' => 'application/vnd.criticaltools.wbs+xml', - 'wbxml' => 'application/vnd.wap.wbxml', - 'wcm' => 'application/vnd.ms-works', - 'wdb' => 'application/vnd.ms-works', - 'wdp' => 'image/vnd.ms-photo', - 'weba' => 'audio/webm', - 'webm' => 'video/webm', - 'webp' => 'image/webp', - 'wg' => 'application/vnd.pmi.widget', - 'wgt' => 'application/widget', - 'wks' => 'application/vnd.ms-works', - 'wm' => 'video/x-ms-wm', - 'wma' => 'audio/x-ms-wma', - 'wmd' => 'application/x-ms-wmd', - 'wmf' => 'application/x-msmetafile', - 'wml' => 'text/vnd.wap.wml', - 'wmlc' => 'application/vnd.wap.wmlc', - 'wmls' => 'text/vnd.wap.wmlscript', - 'wmlsc' => 'application/vnd.wap.wmlscriptc', - 'wmv' => 'video/x-ms-wmv', - 'wmx' => 'video/x-ms-wmx', - 'wmz' => 'application/x-msmetafile', - 'woff' => 'font/woff', - 'woff2' => 'font/woff2', - 'wpd' => 'application/vnd.wordperfect', - 'wpl' => 'application/vnd.ms-wpl', - 'wps' => 'application/vnd.ms-works', - 'wqd' => 'application/vnd.wqd', - 'wri' => 'application/x-mswrite', - 'wrl' => 'model/vrml', - 'wsdl' => 'application/wsdl+xml', - 'wspolicy' => 'application/wspolicy+xml', - 'wtb' => 'application/vnd.webturbo', - 'wvx' => 'video/x-ms-wvx', - 'x32' => 'application/x-authorware-bin', - 'x3d' => 'model/x3d+xml', - 'x3db' => 'model/x3d+binary', - 'x3dbz' => 'model/x3d+binary', - 'x3dv' => 'model/x3d+vrml', - 'x3dvz' => 'model/x3d+vrml', - 'x3dz' => 'model/x3d+xml', - 'xaml' => 'application/xaml+xml', - 'xap' => 'application/x-silverlight-app', - 'xar' => 'application/vnd.xara', - 'xbap' => 'application/x-ms-xbap', - 'xbd' => 'application/vnd.fujixerox.docuworks.binder', - 'xbm' => 'image/x-xbitmap', - 'xdf' => 'application/xcap-diff+xml', - 'xdm' => 'application/vnd.syncml.dm+xml', - 'xdp' => 'application/vnd.adobe.xdp+xml', - 'xdssc' => 'application/dssc+xml', - 'xdw' => 'application/vnd.fujixerox.docuworks', - 'xenc' => 'application/xenc+xml', - 'xer' => 'application/patch-ops-error+xml', - 'xfdf' => 'application/vnd.adobe.xfdf', - 'xfdl' => 'application/vnd.xfdl', - 'xht' => 'application/xhtml+xml', - 'xhtml' => 'application/xhtml+xml', - 'xhvml' => 'application/xv+xml', - 'xif' => 'image/vnd.xiff', - 'xla' => 'application/vnd.ms-excel', - 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', - 'xlc' => 'application/vnd.ms-excel', - 'xlf' => 'application/x-xliff+xml', - 'xlm' => 'application/vnd.ms-excel', - 'xls' => 'application/vnd.ms-excel', - 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', - 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', - 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - 'xlt' => 'application/vnd.ms-excel', - 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', - 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', - 'xlw' => 'application/vnd.ms-excel', - 'xm' => 'audio/xm', - 'xml' => 'application/xml', - 'xo' => 'application/vnd.olpc-sugar', - 'xop' => 'application/xop+xml', - 'xpi' => 'application/x-xpinstall', - 'xpl' => 'application/xproc+xml', - 'xpm' => 'image/x-xpixmap', - 'xpr' => 'application/vnd.is-xpr', - 'xps' => 'application/vnd.ms-xpsdocument', - 'xpw' => 'application/vnd.intercon.formnet', - 'xpx' => 'application/vnd.intercon.formnet', - 'xsl' => 'application/xml', - 'xslt' => 'application/xslt+xml', - 'xsm' => 'application/vnd.syncml+xml', - 'xspf' => 'application/xspf+xml', - 'xul' => 'application/vnd.mozilla.xul+xml', - 'xvm' => 'application/xv+xml', - 'xvml' => 'application/xv+xml', - 'xwd' => 'image/x-xwindowdump', - 'xyz' => 'chemical/x-xyz', - 'xz' => 'application/x-xz', - 'yang' => 'application/yang', - 'yin' => 'application/yin+xml', - 'z1' => 'application/x-zmachine', - 'z2' => 'application/x-zmachine', - 'z3' => 'application/x-zmachine', - 'z4' => 'application/x-zmachine', - 'z5' => 'application/x-zmachine', - 'z6' => 'application/x-zmachine', - 'z7' => 'application/x-zmachine', - 'z8' => 'application/x-zmachine', - 'zaz' => 'application/vnd.zzazz.deck+xml', - 'zip' => 'application/zip', - 'zir' => 'application/vnd.zul', - 'zirz' => 'application/vnd.zul', - 'zmm' => 'application/vnd.handheld-entertainment+xml' - ); - - /** - * Get the mime type based on file extension - * - * @param string $file The file name or path - * - * @return string the mime type on success - * - */ - public static function mimeType($file) - { - /** - * **DISCLAIMER** - * This will just match the file extension to the following - * array. It does not guarantee that the file is TRULY that - * of the extension that this function returns. - * https://gist.github.com/Llewellynvdm/74be373357e131b8775a7582c3de508b - */ - - // get the extension form file - $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); - // check if we have the extension listed - if (isset(self::$fileExtensionToMimeType[$extension])) - { - return self::$fileExtensionToMimeType[$extension]; - } - elseif (function_exists('mime_content_type')) - { - return mime_content_type($file); - } - elseif (function_exists('finfo_open')) - { - $finfo = finfo_open(FILEINFO_MIME); - $mimetype = finfo_file($finfo, $file); - finfo_close($finfo); - return $mimetype; - } - return 'application/octet-stream'; - } - - /** - * Get the file extensions - * - * @param string $target The targeted/filter option - * @param boolean $sorted The multidimensional grouping sort (only if targeted filter is used) - * - * @return array All the extensions (targeted & sorted) - * - */ - public static function getFileExtensions($target = null, $sorted = false) - { - // we have some in-house grouping/filters :) - $filters = array( - 'image' => array('image', 'font', 'model'), - 'document' => array('application', 'text', 'chemical', 'message'), - 'media' => array('video', 'audio'), - 'file' => array('image', 'application', 'text', 'video', 'audio'), - 'all' => array('application', 'text', 'chemical', 'message', 'image', 'font', 'model', 'video', 'audio', 'x-conference') - ); - // sould we filter - if ($target) - { - // the bucket to get extensions - $fileextensions = array(); - // check if filter exist (if not return empty array) - if (isset($filters[$target])) - { - foreach (self::$fileExtensionToMimeType as $extension => $mimetype) - { - // get the key mime type - $mimearr = explode("/", $mimetype, 2); - // check if this file extension should be added - if (in_array($mimearr[0], $filters[$target])) - { - if ($sorted) - { - if (!isset($fileextensions[$mimearr[0]])) - { - $fileextensions[$mimearr[0]] = array(); - } - $fileextensions[$mimearr[0]][$extension] = $extension; - } - else - { - $fileextensions[$extension] = $extension; - } - } - } - } - return $fileextensions; - } - // we just return all file extensions - return array_keys(self::$fileExtensionToMimeType); - } - - protected static function getDownloadFileName(&$sermon, $file, $type) - { - // first get file name and file type - $file = str_replace('VDM_pLeK_h0uEr/', '', $file); - $fileType = pathinfo($file, PATHINFO_EXTENSION); - if ($fileType) - { - $file = str_replace('.'.$fileType, '', $file); - } - else - { - $fileType = 'error'; - } - // now build download name - $downloadName = array(); - // build the Download File Name - first add the preacher name if set - if ($sermon->preacher) - { - $downloadName[] = self::safeString($sermon->preacher_name,'U'); - } - // add the series name if set - if ($sermon->series) - { - $downloadName[] = self::safeString($sermon->series_name,'F'); - } - // add the category name if set - if ($sermon->catid && self::checkString($sermon->category)) - { - $downloadName[] = self::safeString($sermon->category, 'F'); - } - if ('dropbox_manual' == $type || 'local' == $type) - { - // add the main file name - $downloadName[] = self::safeString($sermon->name,'F'); - $downloadName[] = self::safeString($file,'F'); - } - else - { - $downloadName[] = self::safeString($sermon->name,'F'); - if ('error' == $fileType || strpos('?', $fileType) !== false || strpos('&', $fileType) !== false ) - { - $fileType = 'mp3'; // TODO we don't know the url filetype (setting to mp3 but this could be wrong) - } - } - // now build the download file name - return implode('__', $downloadName).'.'.$fileType; - } - - /** - * check External Source Local Listing (do we have the files) - **/ - public static function checkExternalSourceLocalListing($type, $get = 'links') - { - // get the local links - if (isset(self::${$get.'_externalsource_'.$type}) && self::checkArray(self::${$get.'_externalsource_'.$type})) - { - // return true we have links loaded - return true; - } - else - { - $target = array('links' => 'url', 'select' => 'name'); - $build = array( 'auto' => 2, 'manual' => 1); - if (isset($build[$type])) - { - // load the links from the database - $db = JFactory::getDbo(); - // Create a new query object. - $query = $db->getQuery(true); - $query->select($db->quoteName(array('key', $target[$get]))); - $query->from($db->quoteName('#__sermondistributor_local_listing')); - $query->where($db->quoteName('build') . ' = '. (int) $build[$type]); - $query->where($db->quoteName('published') . ' = 1'); // TODO we can now limit the links to access groups - // Reset the query using our newly populated query object. - $db->setQuery($query); - $db->execute(); - if ($db->getNumRows()) - { - self::${$get.'_externalsource_'.$type} = $db->loadAssocList('key', $target[$get]); - // return true we have links loaded - return true; - } - } - } - return false; - } - - /** - * get the localkey - **/ - protected static $localkey = array(); - - public static function getLocalKey($type = 'basic_key') - { - if (!isset(self::$localkey[$type])) - { - // get the main key - self::$localkey[$type] = JComponentHelper::getParams('com_sermondistributor')->get($type, 'localKey34fdWEkl'); - } - return self::$localkey[$type]; - } - - public static function updateExternalSource($id, $target = 0, $type = false, $force = false, $sleutel = null) - { - $source = self::getVar('external_source', (int) $id, 'id', 'externalsources'); - if (1 == $source) // Dropbox is the source - { - // load the file - JLoader::import('dropboxupdater', JPATH_COMPONENT_SITE.'/helpers'); - // update types - $types = array('manual','auto'); - // okay now update this type - if (self::checkString($type) && in_array($type,$types)) - { - $dropbox = new Dropboxupdater(); - if ($dropbox->update($id, $target, $type, $force, $sleutel)) - { - return true; - } - self::setUpdateError($id, $dropbox->getErrors()); - return false; - } - } - self::setUpdateError($id, array(JText::_('COM_SERMONDISTRIBUTOR_THE_EXTERNAL_SOURCE_COULD_NOT_BE_FOUND'))); - return false; - } - - public static function getSourceStatus($id) - { - // fist get errors if any is found - $errors = array(); - if ($targets = self::getExternalListingUpdateKeys($id, null, 1)) - { - foreach ($targets as $target) - { - $key = preg_replace('/[ ,]+/', '', trim($target)); - if ($error = self::getUpdateError(0, $key)) - { - $errors[] = $error; - } - } - } - // check when was the last update - $updateInfo = self::updateInfo($id); - if (!$updateInfo) - { - $errors[] = JText::_('COM_SERMONDISTRIBUTOR_THIS_SOURCE_HAS_NO_LOCAL_LISTING_SET'); - } - // build the return string - if (isset($updateInfo['last']) || self::checkArray($errors)) - { - $body = array(); - // great we have source status - if (isset($updateInfo['last'])) - { - $body[] = '

'. JText::_('COM_SERMONDISTRIBUTOR_LISTING_INFO') . '

'; - $body[] = '

'. JText::_('COM_SERMONDISTRIBUTOR_LAST_UPDATE') . ': '.$updateInfo['last']; - $body[] = '
'. JText::_('COM_SERMONDISTRIBUTOR_NUMBER_OF_FILES_LISTED') . ': '.$updateInfo['qty']; - $body[] = '

'; - } - // now set any errors found - if (self::checkArray($errors)) - { - $body[] = '

'. JText::_('COM_SERMONDISTRIBUTOR_NOTICE') . '

'; - $body[] = implode('', $errors); - } - return ''.JText::_('COM_SERMONDISTRIBUTOR_VIEW_UPDATE_STATUS').'' - . JHtml::_('bootstrap.renderModal', 'source-status'.$id, array('title' => JText::_('COM_SERMONDISTRIBUTOR_SOURCE_STATUS_REPORT')), implode('', $body)); - } - // no status found - return false; - } - - public static function updateInfo($id) - { - $db = JFactory::getDbo(); - // Create a new query object. - $query = $db->getQuery(true); - $query->select($db->quoteName(array('a.created','a.modified'))); - $query->from($db->quoteName('#__sermondistributor_local_listing', 'a')); - $query->where($db->quoteName('a.external_source') . ' = ' . (int) $id); - // Reset the query using our newly populated query object. - $db->setQuery($query); - $db->execute(); - if ($qty = $db->getNumRows()) - { - $data = $db->loadRowList(); - $last = 0; - foreach ($data as $dates) - { - foreach ($dates as $date) - { - $time = strtotime($date); - if ($time > $last) - { - $last = $time; - } - } - } - $info['qty'] = (int) $qty; - $info['last'] = self::fancyDate($last); - return $info; - } - return false; - } - - public static function getUpdateError($id, $fileKey = null) - { - // get update error from file - if ($fileKey) - { - $file_path = self::getFilePath('path', 'updateerror', 'txt', $fileKey, JPATH_COMPONENT_ADMINISTRATOR); - // check if it is set - if (($text = @file_get_contents($file_path)) !== FALSE) - { - // no error on success - if ('success' != $text) - { - return $text; - } - } - return false; - } - elseif (isset(self::$updateErrors[$id]) && self::checkArray(self::$updateErrors[$id])) - { - return '
  • '.implode('
  • ', self::$updateErrors[$id]).'
'; - } - return JText::_('COM_SERMONDISTRIBUTOR_UNKNOWN_ERROR_HAS_OCCURRED'); - } - - protected static function setUpdateError($id, $errorArray) - { - if (self::checkArray($errorArray) && $id > 0) - { - foreach ($errorArray as $error) - { - if (!isset(self::$updateErrors[$id])) - { - self::$updateErrors[$id] = array(); - } - self::$updateErrors[$id][] = $error; - } - } - } - - /** - * Change to nice fancy date - */ - public static function fancyDate($date, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - return date('jS \o\f F Y',$date); - } - - /** - * get date based in period past - */ - public static function fancyDynamicDate($date, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - // older then year - $lastyear = date("Y", strtotime("-1 year")); - $tragetyear = date("Y", $date); - if ($tragetyear <= $lastyear) - { - return date('m/d/y', $date); - } - // same day - $yesterday = strtotime("-1 day"); - if ($date > $yesterday) - { - return date('g:i A', $date); - } - // just month day - return date('M j', $date); - } - - /** - * Change to nice fancy day time and date - */ - public static function fancyDayTimeDate($time, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($time)) - { - $time = strtotime($time); - } - return date('D ga jS \o\f F Y',$time); - } - - /** - * Change to nice fancy time and date - */ - public static function fancyDateTime($time, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($time)) - { - $time = strtotime($time); - } - return date('(G:i) jS \o\f F Y',$time); - } - - /** - * Change to nice hour:minutes time - */ - public static function fancyTime($time, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($time)) - { - $time = strtotime($time); - } - return date('G:i',$time); - } - - /** - * set the date day as Sunday through Saturday - */ - public static function setDayName($date, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - return date('l', $date); - } - - /** - * set the date month as January through December - */ - public static function setMonthName($date, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - return date('F', $date); - } - - /** - * set the date day as 1st - */ - public static function setDay($date, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - return date('jS', $date); - } - - /** - * set the date month as 5 - */ - public static function setMonth($date, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - return date('n', $date); - } - - /** - * set the date year as 2004 (for charts) - */ - public static function setYear($date, $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - return date('Y', $date); - } - - /** - * set the date as 2004/05 (for charts) - */ - public static function setYearMonth($date, $spacer = '/', $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - return date('Y' . $spacer . 'm', $date); - } - - /** - * set the date as 2004/05/03 (for charts) - */ - public static function setYearMonthDay($date, $spacer = '/', $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - return date('Y' . $spacer . 'm' . $spacer . 'd', $date); - } - - /** - * set the date as 03/05/2004 - */ - public static function setDayMonthYear($date, $spacer = '/', $check_stamp = true) - { - if ($check_stamp && !self::isValidTimeStamp($date)) - { - $date = strtotime($date); - } - return date('d' . $spacer . 'm' . $spacer . 'Y', $date); - } - - /** - * Check if string is a valid time stamp - */ - public static function isValidTimeStamp($timestamp) - { - return ((int) $timestamp === $timestamp) - && ($timestamp <= PHP_INT_MAX) - && ($timestamp >= ~PHP_INT_MAX); - } - - /** - * Check if string is a valid date - * https://www.php.net/manual/en/function.checkdate.php#113205 - */ - public static function isValidateDate($date, $format = 'Y-m-d H:i:s') - { - $d = DateTime::createFromFormat($format, $date); - return $d && $d->format($format) == $date; - } - - - /** - * Workers to load tasks - * - * @var array - */ - protected static $worker = array(); - - /** - * Set a worker dynamic URLs - * - * @var array - */ - protected static $workerURL = array(); - - /** - * Set a worker dynamic HEADERs - * - * @var array - */ - protected static $workerHEADER = array(); - - /** - * Curl Error Notice - * - * @var bool - */ - protected static $curlErrorLoaded = false; - - /** - * check if a worker has more work - * - * @param string $function The function to target to perform the task - * - * @return bool - * - */ - public static function hasWork(&$function) - { - if (isset(self::$worker[$function]) && self::checkArray(self::$worker[$function])) - { - return count( (array) self::$worker[$function]); - } - return false; - } - - /** - * Set a worker url - * - * @param string $function The function to target to perform the task - * @param string $url The url of where the task is to be performed - * - * @return void - * - */ - public static function setWorkerUrl(&$function, &$url) - { - // set the URL if found - if (self::checkString($url)) - { - // make sure task function url is up - self::$workerURL[$function] = $url; - } - } - - /** - * Set a worker headers - * - * @param string $function The function to target to perform the task - * @param array $headers The headers needed for these workers/function - * - * @return void - * - */ - public static function setWorkerHeaders(&$function, &$headers) - { - // set the Headers if found - if (self::checkArray($headers)) - { - // make sure task function headers are set - self::$workerHEADER[$function] = $headers; - } - } - - /** - * Set a worker that needs to perform a task - * - * @param mixed $data The data to pass to the task - * @param string $function The function to target to perform the task - * @param string $url The url of where the task is to be performed - * @param array $headers The headers needed for these workers/function - * - * @return void - * - */ - public static function setWorker($data, $function, $url = null, $headers = null) - { - // make sure task function is up - if (!isset(self::$worker[$function])) - { - self::$worker[$function] = array(); - } - // load the task - self::$worker[$function][] = self::lock($data); - // set the Headers if found - if ($headers && !isset(self::$workerHEADER[$function])) - { - self::setWorkerHeaders($function, $headers); - } - // set the URL if found - if ($url && !isset(self::$workerURL[$function])) - { - self::setWorkerUrl($function, $url); - } - } - - /** - * Run set Workers - * - * @param string $function The function to target to perform the task - * @param string $perTask The amount of task per worker - * @param function $callback The option to do a call back when task is completed - * @param int $threadSize The size of the thread - * - * @return bool true On success - * - */ - public static function runWorker($function, $perTask = 50, $callback = null, $threadSize = 20) - { - // set task - $task = self::lock($function); - // build headers - $headers = array('VDM-TASK: ' .$task); - // build dynamic headers - if (isset(self::$workerHEADER[$function]) && self::checkArray(self::$workerHEADER[$function])) - { - foreach (self::$workerHEADER[$function] as $header) - { - $headers[] = $header; - } - } - // build worker options - $options = array(); - // make sure worker is up - if (isset(self::$worker[$function]) && self::checkArray(self::$worker[$function])) - { - // this load method is for each - if (1 == $perTask) - { - // working with a string = 1 - $headers[] = 'VDM-VALUE-TYPE: ' .self::lock(1); - // now load the options - foreach (self::$worker[$function] as $data) - { - $options[] = array(CURLOPT_HTTPHEADER => $headers, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => 'VDM_DATA='. $data); - } - } - // this load method is for bundles - else - { - // working with an array = 2 - $headers[] = 'VDM-VALUE-TYPE: ' .self::lock(2); - // now load the options - $work = array_chunk(self::$worker[$function], $perTask); - foreach ($work as $data) - { - $options[] = array(CURLOPT_HTTPHEADER => $headers, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => 'VDM_DATA='. implode('___VDM___', $data)); - } - } - // relieve worker of task/function - self::$worker[$function] = array(); - } - // do the execution - if (self::checkArray($options)) - { - if (isset(self::$workerURL[$function])) - { - $url = self::$workerURL[$function]; - } - else - { - $url = JURI::root() . '/index.php?option=com_sermondistributor&task=api.worker'; - } - return self::curlMultiExec($url, $options, $callback, $threadSize); - } - return false; - } - - /** - * Do a multi curl execution of tasks - * - * @param string $url The url of where the task is to be performed - * @param array $_options The array of curl options/headers to set - * @param function $callback The option to do a call back when task is completed - * @param int $threadSize The size of the thread - * - * @return bool true On success - * - */ - public static function curlMultiExec(&$url, &$_options, $callback = null, $threadSize = 20) - { - // make sure we have curl available - if (!function_exists('curl_version')) - { - if (!self::$curlErrorLoaded) - { - // set the notice - JFactory::getApplication()->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_HTWOCURL_NOT_FOUNDHTWOPPLEASE_SETUP_CURL_ON_YOUR_SYSTEM_OR_BSERMONDISTRIBUTORB_WILL_NOT_FUNCTION_CORRECTLYP'), 'Error'); - // load the notice only once - self::$curlErrorLoaded = true; - } - return false; - } - // make sure we have an url - if (self::checkString($url)) - { - // make sure the thread size isn't greater than the # of _options - $threadSize = (count($_options) < $threadSize) ? count($_options) : $threadSize; - // set the options - $options = array(); - $options[CURLOPT_URL] = $url; - $options[CURLOPT_USERAGENT] = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12'; - $options[CURLOPT_RETURNTRANSFER] = TRUE; - $options[CURLOPT_SSL_VERIFYPEER] = FALSE; - // start multi threading :) - $handle = curl_multi_init(); - // start the first batch of requests - for ($i = 0; $i < $threadSize; $i++) - { - if (isset($_options[$i])) - { - $ch = curl_init(); - foreach ($_options[$i] as $curlopt => $string) - { - $options[$curlopt] = $string; - } - curl_setopt_array($ch, $options); - curl_multi_add_handle($handle, $ch); - } - } - // we wait for all the calls to finish (should not take long) - do { - while(($execrun = curl_multi_exec($handle, $working)) == CURLM_CALL_MULTI_PERFORM); - if($execrun != CURLM_OK) - break; - // a request was just completed -- find out which one - while($done = curl_multi_info_read($handle)) - { - if (is_callable($callback)) - { - // $info = curl_getinfo($done['handle']); - // request successful. process output using the callback function. - $output = curl_multi_getcontent($done['handle']); - $callback($output); - } - $key = $i + 1; - if(isset($_options[$key])) - { - // start a new request (it's important to do this before removing the old one) - $ch = curl_init(); $i++; - // add options - foreach ($_options[$key] as $curlopt => $string) - { - $options[$curlopt] = $string; - } - curl_setopt_array($ch, $options); - curl_multi_add_handle($handle, $ch); - // remove options again - foreach ($_options[$key] as $curlopt => $string) - { - unset($options[$curlopt]); - } - } - // remove the curl handle that just completed - curl_multi_remove_handle($handle, $done['handle']); - } - // stop wasting CPU cycles and rest for a couple ms - usleep(10000); - } while ($working); - // close the curl multi thread - curl_multi_close($handle); - // okay done - return true; - } - return false; - } - - /** - * the locker - * - * @var array - **/ - protected static $locker = array(); - - /** - * the dynamic replacement salt - * - * @var array - **/ - protected static $globalSalt = array(); - - /** - * the timer - * - * @var object - **/ - protected static $keytimer; - - /** - * To Lock string - * - * @param string $string The string/array to lock - * @param string $key The custom key to use - * @param int $salt The switch to add salt and type of salt - * @param int $dynamic The dynamic replacement array of salt build string - * @param int $urlencode The switch to control url encoding - * - * @return string Encrypted String - * - **/ - public static function lock($string, $key = null, $salt = 2, $dynamic = null, $urlencode = true) - { - // get the global settings - if (!$key || !self::checkString($key)) - { - // set temp timer - $timer = 2; - // if we have a timer use it - if ($salt > 0) - { - $timer = $salt; - } - // set the default key - $key = self::salt($timer, $dynamic); - // try getting the system key - if (method_exists(get_called_class(), "getCryptKey")) - { - // try getting the medium key first the fall back to basic, and then default - $key = self::getCryptKey('medium', self::getCryptKey('basic', $key)); - } - } - // check if we have a salt timer - if ($salt > 0) - { - $key .= self::salt($salt, $dynamic); - } - // get the locker settings - if (!isset(self::$locker[$key]) || !self::checkObject(self::$locker[$key])) - { - self::$locker[$key] = new FOFEncryptAes($key, 128); - } - // convert array or object to string - if (self::checkArray($string) || self::checkObject($string)) - { - $string = serialize($string); - } - // prep for url - if ($urlencode && method_exists(get_called_class(), "base64_urlencode")) - { - return self::base64_urlencode(self::$locker[$key]->encryptString($string)); - } - return self::$locker[$key]->encryptString($string); - } - - /** - * To un-Lock string - * - * @param string $string The string to unlock - * @param string $key The custom key to use - * @param int $salt The switch to add salt and type of salt - * @param int $dynamic The dynamic replacement array of salt build string - * @param int $urlencode The switch to control url decoding - * - * @return string Decrypted String - * - **/ - public static function unlock($string, $key = null, $salt = 2, $dynamic = null, $urlencode = true) - { - // get the global settings - if (!$key || !self::checkString($key)) - { - // set temp timer - $timer = 2; - // if we have a timer use it - if ($salt > 0) - { - $timer = $salt; - } - // set the default key - $key = self::salt($timer, $dynamic); - // try getting the system key - if (method_exists(get_called_class(), "getCryptKey")) - { - // try getting the medium key first the fall back to basic, and then default - $key = self::getCryptKey('medium', self::getCryptKey('basic', $key)); - } - } - // check if we have a salt timer - if ($salt > 0) - { - $key .= self::salt($salt, $dynamic); - } - // get the locker settings - if (!isset(self::$locker[$key]) || !self::checkObject(self::$locker[$key])) - { - self::$locker[$key] = new FOFEncryptAes($key, 128); - } - // make sure we have real base64 - if ($urlencode && method_exists(get_called_class(), "base64_urldecode")) - { - $string = self::base64_urldecode($string); - } - // basic decrypt string. - if (!empty($string) && !is_numeric($string) && $string === base64_encode(base64_decode($string, true))) - { - $string = rtrim(self::$locker[$key]->decryptString($string), "\0"); - // convert serial string to array - if (self::is_serial($string)) - { - $string = unserialize($string); - } - } - return $string; - } - - /** - * The Salt - * - * @param int $type The type of length the salt should be valid - * @param int $dynamic The dynamic replacement array of salt build string - * - * @return string - * - **/ - public static function salt($type = 1, $dynamic = null) - { - // get dynamic replacement salt - $dynamic = self::getDynamicSalt($dynamic); - // get the key timer - if (!self::checkObject(self::$keytimer)) - { - // load the date time object - self::$keytimer = new DateTime; - // set the correct time stamp - $vdmLocalTime = new DateTimeZone('Africa/Windhoek'); - self::$keytimer->setTimezone($vdmLocalTime); - } - // set type - if ($type == 2) - { - // hour - $format = 'Y-m-d \o\n ' . self::periodFix(self::$keytimer->format('H')); - } - elseif ($type == 3) - { - // day - $format = 'Y-m-' . self::periodFix(self::$keytimer->format('d')); - } - elseif ($type == 4) - { - // month - $format = 'Y-' . self::periodFix(self::$keytimer->format('m')); - } - else - { - // minute - $format = 'Y-m-d \o\n H:' . self::periodFix(self::$keytimer->format('i')); - } - // get key - if (self::checkArray($dynamic)) - { - return md5(str_replace(array_keys($dynamic), array_values($dynamic), self::$keytimer->format($format) . ' @ VDM.I0')); - } - return md5(self::$keytimer->format($format) . ' @ VDM.I0'); - } - - /** - * The function to insure the salt is valid within the given period (third try) - * - * @param int $main The main number - */ - protected static function periodFix($main) - { - return round($main / 3) * 3; - } - - /** - * Check if a string is serialized - * - * @param string $string - * - * @return Boolean - * - */ - public static function is_serial($string) - { - return (@unserialize($string) !== false); - } - - /** - * Get dynamic replacement salt - */ - public static function getDynamicSalt($dynamic = null) - { - // load global if not manually set - if (!self::checkArray($dynamic)) - { - return self::getGlobalSalt(); - } - // return manual values if set - else - { - return $dynamic; - } - } - - /** - * The random or dynamic secret salt - */ - public static function getSecretSalt($string = null, $size = 9) - { - // set the string - if (!$string) - { - // get random string - $string = self::randomkey($size); - } - // convert string to array - $string = self::safeString($string); - // convert string to array - $array = str_split($string); - // insure only unique values are used - $array = array_unique($array); - // set the size - $size = ($size <= count($array)) ? $size : count($array); - // down size the - return array_slice($array, 0, $size); - } - - /** - * Get global replacement salt - */ - public static function getGlobalSalt() - { - // load from memory if found - if (!self::checkArray(self::$globalSalt)) - { - // get the global settings - if (!self::checkObject(self::$params)) - { - self::$params = JComponentHelper::getParams('com_sermondistributor'); - } - // check if we have a global dynamic replacement array available (format --> ' 1->!,3->E,4->A') - $tmp = self::$params->get('dynamic_salt', null); - if (self::checkString($tmp) && strpos($tmp, ',') !== false && strpos($tmp, '->') !== false) - { - $salt = array_map('trim', (array) explode(',', $tmp)); - if (self::checkArray($salt )) - { - foreach($salt as $replace) - { - $dynamic = array_map('trim', (array) explode('->', $replace)); - if (isset($dynamic[0]) && isset($dynamic[1])) - { - self::$globalSalt[$dynamic[0]] = $dynamic[1]; - } - } - } - } - } - // return global if found - if (self::checkArray(self::$globalSalt)) - { - return self::$globalSalt; - } - // return default as fail safe - return array('1' => '!', '3' => 'E', '4' => 'A'); - } - - /** - * Close public protocol - */ - public static function closePublicProtocol($id, $public) - { - // get secret salt - $secretSalt = self::getSecretSalt(self::salt(1,array('4' => 'R','1' => 'E','2' => 'G','7' => 'J','8' => 'A'))); - // get the key - $key = self::salt(1, $secretSalt); - // get secret salt - $secret = self::getSecretSalt(); - // set the secret - $close['SECRET'] = self::lock($secret, $key, 1, array('1' => 's', '3' => 'R', '4' => 'D')); - // get the key - $key = self::salt(1, $secret); - // get the public key - $close['PUBLIC'] = self::lock($public, $key, 1, array('1' => '!', '3' => 'E', '4' => 'A')); - // get secret salt - $secretSalt = self::getSecretSalt($public); - // get the key - $key = self::salt(1, $secretSalt); - // get the ID - $close['ID'] = self::unlock($id, $key, 1, array('1' => 'i', '3' => 'e', '4' => 'B')); - // return closed values - return $close; - } - - /** - * Open public protocol - */ - public static function openPublicProtocol($SECRET, $ID, $PUBLIC) - { - // get secret salt - $secretSalt = self::getSecretSalt(self::salt(1,array('4' => 'R','1' => 'E','2' => 'G','7' => 'J','8' => 'A'))); - // get the key - $key = self::salt(1, $secretSalt); - // get the $SECRET - $SECRET = self::unlock($SECRET, $key, 1, array('1' => 's', '3' => 'R', '4' => 'D')); - // get the key - $key = self::salt(1, $SECRET); - // get the public key - $open['public'] = self::unlock($PUBLIC, $key, 1, array('1' => '!', '3' => 'E', '4' => 'A')); - // get secret salt - $secretSalt = self::getSecretSalt($open['public']); - // get the key - $key = self::salt(1, $secretSalt); - // get the ID - $open['id'] = self::unlock($ID, $key, 1, array('1' => 'i', '3' => 'e', '4' => 'B')); - // return opened values - return $open; - } - - /** - * Load the Composer Vendors - */ - public static function composerAutoload($target) - { - // insure we load the composer vendor only once - if (!isset(self::$composer[$target])) - { - // get the function name - $functionName = self::safeString('compose' . $target); - // check if method exist - if (method_exists(__CLASS__, $functionName)) - { - return self::{$functionName}(); - } - return false; - } - return self::$composer[$target]; - } - - /** - * Load the Component xml manifest. - */ - public static function manifest() - { - $manifestUrl = JPATH_ADMINISTRATOR."/components/com_sermondistributor/sermondistributor.xml"; - return simplexml_load_file($manifestUrl); - } - - /** - * Joomla version object - */ - protected static $JVersion; - - /** - * set/get Joomla version - */ - public static function jVersion() - { - // check if set - if (!self::checkObject(self::$JVersion)) - { - self::$JVersion = new JVersion(); - } - return self::$JVersion; - } - - /** - * Load the Contributors details. - */ - public static function getContributors() - { - // get params - $params = JComponentHelper::getParams('com_sermondistributor'); - // start contributors array - $contributors = array(); - // get all Contributors (max 20) - $searchArray = range('0','20'); - foreach($searchArray as $nr) - { - if ((NULL !== $params->get("showContributor".$nr)) && ($params->get("showContributor".$nr) == 1 || $params->get("showContributor".$nr) == 3)) - { - // set link based of selected option - if($params->get("useContributor".$nr) == 1) - { - $link_front = ''; - $link_back = ''; - } - elseif($params->get("useContributor".$nr) == 2) - { - $link_front = ''; - $link_back = ''; - } - else - { - $link_front = ''; - $link_back = ''; - } - $contributors[$nr]['title'] = self::htmlEscape($params->get("titleContributor".$nr)); - $contributors[$nr]['name'] = $link_front.self::htmlEscape($params->get("nameContributor".$nr)).$link_back; - } - } - return $contributors; - } - - /** - * Load the Component Help URLs. - **/ - public static function getHelpUrl($view) - { - $user = JFactory::getUser(); - $groups = $user->get('groups'); - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select(array('a.id','a.groups','a.target','a.type','a.article','a.url')); - $query->from('#__sermondistributor_help_document AS a'); - $query->where('a.admin_view = '.$db->quote($view)); - $query->where('a.location = 1'); - $query->where('a.published = 1'); - $db->setQuery($query); - $db->execute(); - if($db->getNumRows()) - { - $helps = $db->loadObjectList(); - if (self::checkArray($helps)) - { - foreach ($helps as $nr => $help) - { - if ($help->target == 1) - { - $targetgroups = json_decode($help->groups, true); - if (!array_intersect($targetgroups, $groups)) - { - // if user not in those target groups then remove the item - unset($helps[$nr]); - continue; - } - } - // set the return type - switch ($help->type) - { - // set joomla article - case 1: - return self::loadArticleLink($help->article); - break; - // set help text - case 2: - return self::loadHelpTextLink($help->id); - break; - // set Link - case 3: - return $help->url; - break; - } - } - } - } - return false; - } - - /** - * Get the Article Link. - **/ - protected static function loadArticleLink($id) - { - return JURI::root().'index.php?option=com_content&view=article&id='.$id.'&tmpl=component&layout=modal'; - } - - /** - * Get the Help Text Link. - **/ - protected static function loadHelpTextLink($id) - { - $token = JSession::getFormToken(); - return 'index.php?option=com_sermondistributor&task=help.getText&id=' . (int) $id . '&token=' . $token; - } - - /** - * Configure the Linkbar. - */ - public static function addSubmenu($submenu) - { - // load user for access menus - $user = JFactory::getUser(); - // load the submenus to sidebar - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SUBMENU_DASHBOARD'), 'index.php?option=com_sermondistributor&view=sermondistributor', $submenu === 'sermondistributor'); - if ($user->authorise('preacher.access', 'com_sermondistributor') && $user->authorise('preacher.submenu', 'com_sermondistributor')) - { - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SUBMENU_PREACHERS'), 'index.php?option=com_sermondistributor&view=preachers', $submenu === 'preachers'); - } - if ($user->authorise('sermon.access', 'com_sermondistributor') && $user->authorise('sermon.submenu', 'com_sermondistributor')) - { - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SUBMENU_SERMONS'), 'index.php?option=com_sermondistributor&view=sermons', $submenu === 'sermons'); - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SERMON_SERMONS_CATEGORIES'), 'index.php?option=com_categories&view=categories&extension=com_sermondistributor.sermon', $submenu === 'categories.sermon'); - } - if ($user->authorise('series.access', 'com_sermondistributor') && $user->authorise('series.submenu', 'com_sermondistributor')) - { - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SUBMENU_SERIES_LIST'), 'index.php?option=com_sermondistributor&view=series_list', $submenu === 'series_list'); - } - if ($user->authorise('statistic.access', 'com_sermondistributor') && $user->authorise('statistic.submenu', 'com_sermondistributor')) - { - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SUBMENU_STATISTICS'), 'index.php?option=com_sermondistributor&view=statistics', $submenu === 'statistics'); - } - if ($user->authorise('external_source.access', 'com_sermondistributor') && $user->authorise('external_source.submenu', 'com_sermondistributor')) - { - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SUBMENU_EXTERNAL_SOURCES'), 'index.php?option=com_sermondistributor&view=external_sources', $submenu === 'external_sources'); - } - // Access control (manual_updater.access && manual_updater.submenu). - if ($user->authorise('manual_updater.access', 'com_sermondistributor') && $user->authorise('manual_updater.submenu', 'com_sermondistributor')) - { - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SUBMENU_MANUAL_UPDATER'), 'index.php?option=com_sermondistributor&view=manual_updater', $submenu === 'manual_updater'); - } - if ($user->authorise('local_listing.access', 'com_sermondistributor') && $user->authorise('local_listing.submenu', 'com_sermondistributor')) - { - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SUBMENU_LOCAL_LISTINGS'), 'index.php?option=com_sermondistributor&view=local_listings', $submenu === 'local_listings'); - } - if ($user->authorise('help_document.access', 'com_sermondistributor') && $user->authorise('help_document.submenu', 'com_sermondistributor')) - { - JHtmlSidebar::addEntry(JText::_('COM_SERMONDISTRIBUTOR_SUBMENU_HELP_DOCUMENTS'), 'index.php?option=com_sermondistributor&view=help_documents', $submenu === 'help_documents'); - } - } - - /** - * UIKIT Component Classes - **/ - public static $uk_components = array( - 'data-uk-grid' => array( - 'grid' ), - 'uk-accordion' => array( - 'accordion' ), - 'uk-autocomplete' => array( - 'autocomplete' ), - 'data-uk-datepicker' => array( - 'datepicker' ), - 'uk-form-password' => array( - 'form-password' ), - 'uk-form-select' => array( - 'form-select' ), - 'data-uk-htmleditor' => array( - 'htmleditor' ), - 'data-uk-lightbox' => array( - 'lightbox' ), - 'uk-nestable' => array( - 'nestable' ), - 'UIkit.notify' => array( - 'notify' ), - 'data-uk-parallax' => array( - 'parallax' ), - 'uk-search' => array( - 'search' ), - 'uk-slider' => array( - 'slider' ), - 'uk-slideset' => array( - 'slideset' ), - 'uk-slideshow' => array( - 'slideshow', - 'slideshow-fx' ), - 'uk-sortable' => array( - 'sortable' ), - 'data-uk-sticky' => array( - 'sticky' ), - 'data-uk-timepicker' => array( - 'timepicker' ), - 'data-uk-tooltip' => array( - 'tooltip' ), - 'uk-placeholder' => array( - 'placeholder' ), - 'uk-dotnav' => array( - 'dotnav' ), - 'uk-slidenav' => array( - 'slidenav' ), - 'uk-form' => array( - 'form-advanced' ), - 'uk-progress' => array( - 'progress' ), - 'upload-drop' => array( - 'upload', 'form-file' ) - ); - - /** - * Add UIKIT Components - **/ - public static $uikit = false; - - /** - * Get UIKIT Components - **/ - public static function getUikitComp($content,$classes = array()) - { - if (strpos($content,'class="uk-') !== false) - { - // reset - $temp = array(); - foreach (self::$uk_components as $looking => $add) - { - if (strpos($content,$looking) !== false) - { - $temp[] = $looking; - } - } - // make sure uikit is loaded to config - if (strpos($content,'class="uk-') !== false) - { - self::$uikit = true; - } - // sorter - if (self::checkArray($temp)) - { - // merger - if (self::checkArray($classes)) - { - $newTemp = array_merge($temp,$classes); - $temp = array_unique($newTemp); - } - return $temp; - } - } - if (self::checkArray($classes)) - { - return $classes; - } - return false; - } - - /** - * Prepares the xml document - */ - public static function xls($rows, $fileName = null, $title = null, $subjectTab = null, $creator = 'Vast Development Method', $description = null, $category = null,$keywords = null, $modified = null) - { - // set the user - $user = JFactory::getUser(); - // set fileName if not set - if (!$fileName) - { - $fileName = 'exported_'.JFactory::getDate()->format('jS_F_Y'); - } - // set modified if not set - if (!$modified) - { - $modified = $user->name; - } - // set title if not set - if (!$title) - { - $title = 'Book1'; - } - // set tab name if not set - if (!$subjectTab) - { - $subjectTab = 'Sheet1'; - } - - // make sure we have the composer classes loaded - self::composerAutoload('phpspreadsheet'); - - // Create new Spreadsheet object - $spreadsheet = new Spreadsheet(); - - // Set document properties - $spreadsheet->getProperties() - ->setCreator($creator) - ->setCompany('Vast Development Method') - ->setLastModifiedBy($modified) - ->setTitle($title) - ->setSubject($subjectTab); - // The file type - $file_type = 'Xls'; - // set description - if ($description) - { - $spreadsheet->getProperties()->setDescription($description); - } - // set keywords - if ($keywords) - { - $spreadsheet->getProperties()->setKeywords($keywords); - } - // set category - if ($category) - { - $spreadsheet->getProperties()->setCategory($category); - } - - // Some styles - $headerStyles = array( - 'font' => array( - 'bold' => true, - 'color' => array('rgb' => '1171A3'), - 'size' => 12, - 'name' => 'Verdana' - )); - $sideStyles = array( - 'font' => array( - 'bold' => true, - 'color' => array('rgb' => '444444'), - 'size' => 11, - 'name' => 'Verdana' - )); - $normalStyles = array( - 'font' => array( - 'color' => array('rgb' => '444444'), - 'size' => 11, - 'name' => 'Verdana' - )); - - // Add some data - if (($size = self::checkArray($rows)) !== false) - { - $i = 1; - - // Based on data size we adapt the behaviour. - $xls_mode = 1; - if ($size > 3000) - { - $xls_mode = 3; - $file_type = 'Csv'; - } - elseif ($size > 2000) - { - $xls_mode = 2; - } - - // Set active sheet and get it. - $active_sheet = $spreadsheet->setActiveSheetIndex(0); - foreach ($rows as $array) - { - $a = 'A'; - foreach ($array as $value) - { - $active_sheet->setCellValue($a.$i, $value); - if ($xls_mode != 3) - { - if ($i == 1) - { - $active_sheet->getColumnDimension($a)->setAutoSize(true); - $active_sheet->getStyle($a.$i)->applyFromArray($headerStyles); - $active_sheet->getStyle($a.$i)->getAlignment()->setHorizontal(PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); - } - elseif ($a === 'A') - { - $active_sheet->getStyle($a.$i)->applyFromArray($sideStyles); - } - elseif ($xls_mode == 1) - { - $active_sheet->getStyle($a.$i)->applyFromArray($normalStyles); - } - } - $a++; - } - $i++; - } - } - else - { - return false; - } - - // Rename worksheet - $spreadsheet->getActiveSheet()->setTitle($subjectTab); - - // Set active sheet index to the first sheet, so Excel opens this as the first sheet - $spreadsheet->setActiveSheetIndex(0); - - // Redirect output to a client's web browser (Excel5) - header('Content-Type: application/vnd.ms-excel'); - header('Content-Disposition: attachment;filename="' . $fileName . '.' . strtolower($file_type) .'"'); - header('Cache-Control: max-age=0'); - // If you're serving to IE 9, then the following may be needed - header('Cache-Control: max-age=1'); - - // If you're serving to IE over SSL, then the following may be needed - header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past - header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified - header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 - header ('Pragma: public'); // HTTP/1.0 - - $writer = IOFactory::createWriter($spreadsheet, $file_type); - $writer->save('php://output'); - jexit(); - } - - /** - * Get CSV Headers - */ - public static function getFileHeaders($dataType) - { - // make sure we have the composer classes loaded - self::composerAutoload('phpspreadsheet'); - // get session object - $session = JFactory::getSession(); - $package = $session->get('package', null); - $package = json_decode($package, true); - // set the headers - if(isset($package['dir'])) - { - // only load first three rows - $chunkFilter = new PhpOffice\PhpSpreadsheet\Reader\chunkReadFilter(2,1); - // identify the file type - $inputFileType = IOFactory::identify($package['dir']); - // create the reader for this file type - $excelReader = IOFactory::createReader($inputFileType); - // load the limiting filter - $excelReader->setReadFilter($chunkFilter); - $excelReader->setReadDataOnly(true); - // load the rows (only first three) - $excelObj = $excelReader->load($package['dir']); - $headers = array(); - foreach ($excelObj->getActiveSheet()->getRowIterator() as $row) - { - if($row->getRowIndex() == 1) - { - $cellIterator = $row->getCellIterator(); - $cellIterator->setIterateOnlyExistingCells(false); - foreach ($cellIterator as $cell) - { - if (!is_null($cell)) - { - $headers[$cell->getColumn()] = $cell->getValue(); - } - } - $excelObj->disconnectWorksheets(); - unset($excelObj); - break; - } - } - return $headers; - } - return false; - } - - /** - * Load the Composer Vendor phpspreadsheet - */ - protected static function composephpspreadsheet() - { - // load the autoloader for phpspreadsheet - require_once JPATH_SITE . '/libraries/phpspreadsheet/vendor/autoload.php'; - // do not load again - self::$composer['phpspreadsheet'] = true; - - return true; - } - - /** - * Get a Variable - * - * @param string $table The table from which to get the variable - * @param string $where The value where - * @param string $whereString The target/field string where/name - * @param string $what The return field - * @param string $operator The operator between $whereString/field and $where/value - * @param string $main The component in which the table is found - * - * @return mix string/int/float - * - */ - public static function getVar($table, $where = null, $whereString = 'user', $what = 'id', $operator = '=', $main = 'sermondistributor') - { - if(!$where) - { - $where = JFactory::getUser()->id; - } - // Get a db connection. - $db = JFactory::getDbo(); - // Create a new query object. - $query = $db->getQuery(true); - $query->select($db->quoteName(array($what))); - if (empty($table)) - { - $query->from($db->quoteName('#__'.$main)); - } - else - { - $query->from($db->quoteName('#__'.$main.'_'.$table)); - } - if (is_numeric($where)) - { - $query->where($db->quoteName($whereString) . ' '.$operator.' '.(int) $where); - } - elseif (is_string($where)) - { - $query->where($db->quoteName($whereString) . ' '.$operator.' '. $db->quote((string)$where)); - } - else - { - return false; - } - $db->setQuery($query); - $db->execute(); - if ($db->getNumRows()) - { - return $db->loadResult(); - } - return false; - } - - /** - * Get array of variables - * - * @param string $table The table from which to get the variables - * @param string $where The value where - * @param string $whereString The target/field string where/name - * @param string $what The return field - * @param string $operator The operator between $whereString/field and $where/value - * @param string $main The component in which the table is found - * @param bool $unique The switch to return a unique array - * - * @return array - * - */ - public static function getVars($table, $where = null, $whereString = 'user', $what = 'id', $operator = 'IN', $main = 'sermondistributor', $unique = true) - { - if(!$where) - { - $where = JFactory::getUser()->id; - } - - if (!self::checkArray($where) && $where > 0) - { - $where = array($where); - } - - if (self::checkArray($where)) - { - // prep main <-- why? well if $main='' is empty then $table can be categories or users - if (self::checkString($main)) - { - $main = '_'.ltrim($main, '_'); - } - // Get a db connection. - $db = JFactory::getDbo(); - // Create a new query object. - $query = $db->getQuery(true); - - $query->select($db->quoteName(array($what))); - if (empty($table)) - { - $query->from($db->quoteName('#__'.$main)); - } - else - { - $query->from($db->quoteName('#_'.$main.'_'.$table)); - } - // add strings to array search - if ('IN_STRINGS' === $operator || 'NOT IN_STRINGS' === $operator) - { - $query->where($db->quoteName($whereString) . ' ' . str_replace('_STRINGS', '', $operator) . ' ("' . implode('","',$where) . '")'); - } - else - { - $query->where($db->quoteName($whereString) . ' ' . $operator . ' (' . implode(',',$where) . ')'); - } - $db->setQuery($query); - $db->execute(); - if ($db->getNumRows()) - { - if ($unique) - { - return array_unique($db->loadColumn()); - } - return $db->loadColumn(); - } - } - return false; - } - - public static function jsonToString($value, $sperator = ", ", $table = null, $id = 'id', $name = 'name') - { - // do some table foot work - $external = false; - if (strpos($table, '#__') !== false) - { - $external = true; - $table = str_replace('#__', '', $table); - } - // check if string is JSON - $result = json_decode($value, true); - if (json_last_error() === JSON_ERROR_NONE) - { - // is JSON - if (self::checkArray($result)) - { - if (self::checkString($table)) - { - $names = array(); - foreach ($result as $val) - { - if ($external) - { - if ($_name = self::getVar(null, $val, $id, $name, '=', $table)) - { - $names[] = $_name; - } - } - else - { - if ($_name = self::getVar($table, $val, $id, $name)) - { - $names[] = $_name; - } - } - } - if (self::checkArray($names)) - { - return (string) implode($sperator,$names); - } - } - return (string) implode($sperator,$result); - } - return (string) json_decode($value); - } - return $value; - } - - public static function isPublished($id,$type) - { - if ($type == 'raw') - { - $type = 'item'; - } - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select(array('a.published')); - $query->from('#__sermondistributor_'.$type.' AS a'); - $query->where('a.id = '. (int) $id); - $query->where('a.published = 1'); - $db->setQuery($query); - $db->execute(); - $found = $db->getNumRows(); - if($found) - { - return true; - } - return false; - } - - public static function getGroupName($id) - { - $db = JFactory::getDBO(); - $query = $db->getQuery(true); - $query->select(array('a.title')); - $query->from('#__usergroups AS a'); - $query->where('a.id = '. (int) $id); - $db->setQuery($query); - $db->execute(); - $found = $db->getNumRows(); - if($found) - { - return $db->loadResult(); - } - return $id; - } - - /** - * Get the action permissions - * - * @param string $view The related view name - * @param int $record The item to act upon - * @param string $views The related list view name - * @param mixed $target Only get this permission (like edit, create, delete) - * @param string $component The target component - * @param object $user The user whose permissions we are loading - * - * @return object The JObject of permission/authorised actions - * - */ - public static function getActions($view, &$record = null, $views = null, $target = null, $component = 'sermondistributor', $user = 'null') - { - // load the user if not given - if (!self::checkObject($user)) - { - // get the user object - $user = JFactory::getUser(); - } - // load the JObject - $result = new JObject; - // make view name safe (just incase) - $view = self::safeString($view); - if (self::checkString($views)) - { - $views = self::safeString($views); - } - // get all actions from component - $actions = JAccess::getActionsFromFile( - JPATH_ADMINISTRATOR . '/components/com_' . $component . '/access.xml', - "/access/section[@name='component']/" - ); - // if non found then return empty JObject - if (empty($actions)) - { - return $result; - } - // get created by if not found - if (self::checkObject($record) && !isset($record->created_by) && isset($record->id)) - { - $record->created_by = self::getVar($view, $record->id, 'id', 'created_by', '=', $component); - } - // set actions only set in component settings - $componentActions = array('core.admin', 'core.manage', 'core.options', 'core.export'); - // check if we have a target - $checkTarget = false; - if ($target) - { - // convert to an array - if (self::checkString($target)) - { - $target = array($target); - } - // check if we are good to go - if (self::checkArray($target)) - { - $checkTarget = true; - } - } - // loop the actions and set the permissions - foreach ($actions as $action) - { - // check target action filter - if ($checkTarget && self::filterActions($view, $action->name, $target)) - { - continue; - } - // set to use component default - $fallback = true; - // reset permission per/action - $permission = false; - $catpermission = false; - // set area - $area = 'comp'; - // check if the record has an ID and the action is item related (not a component action) - if (self::checkObject($record) && isset($record->id) && $record->id > 0 && !in_array($action->name, $componentActions) && - (strpos($action->name, 'core.') !== false || strpos($action->name, $view . '.') !== false)) - { - // we are in item - $area = 'item'; - // The record has been set. Check the record permissions. - $permission = $user->authorise($action->name, 'com_' . $component . '.' . $view . '.' . (int) $record->id); - // if no permission found, check edit own - if (!$permission) - { - // With edit, if the created_by matches current user then dig deeper. - if (($action->name === 'core.edit' || $action->name === $view . '.edit') && $record->created_by > 0 && ($record->created_by == $user->id)) - { - // the correct target - $coreCheck = (array) explode('.', $action->name); - // check that we have both local and global access - if ($user->authorise($coreCheck[0] . '.edit.own', 'com_' . $component . '.' . $view . '.' . (int) $record->id) && - $user->authorise($coreCheck[0] . '.edit.own', 'com_' . $component)) - { - // allow edit - $result->set($action->name, true); - // set not to use global default - // because we already validated it - $fallback = false; - } - else - { - // do not allow edit - $result->set($action->name, false); - $fallback = false; - } - } - } - elseif (self::checkString($views) && isset($record->catid) && $record->catid > 0) - { - // we are in item - $area = 'category'; - // set the core check - $coreCheck = explode('.', $action->name); - $core = $coreCheck[0]; - // make sure we use the core. action check for the categories - if (strpos($action->name, $view) !== false && strpos($action->name, 'core.') === false ) - { - $coreCheck[0] = 'core'; - $categoryCheck = implode('.', $coreCheck); - } - else - { - $categoryCheck = $action->name; - } - // The record has a category. Check the category permissions. - $catpermission = $user->authorise($categoryCheck, 'com_' . $component . '.' . $views . '.category.' . (int) $record->catid); - if (!$catpermission && !is_null($catpermission)) - { - // With edit, if the created_by matches current user then dig deeper. - if (($action->name === 'core.edit' || $action->name === $view . '.edit') && $record->created_by > 0 && ($record->created_by == $user->id)) - { - // check that we have both local and global access - if ($user->authorise('core.edit.own', 'com_' . $component . '.' . $views . '.category.' . (int) $record->catid) && - $user->authorise($core . '.edit.own', 'com_' . $component)) - { - // allow edit - $result->set($action->name, true); - // set not to use global default - // because we already validated it - $fallback = false; - } - else - { - // do not allow edit - $result->set($action->name, false); - $fallback = false; - } - } - } - } - } - // if allowed then fallback on component global settings - if ($fallback) - { - // if item/category blocks access then don't fall back on global - if ((($area === 'item') && !$permission) || (($area === 'category') && !$catpermission)) - { - // do not allow - $result->set($action->name, false); - } - // Finally remember the global settings have the final say. (even if item allow) - // The local item permissions can block, but it can't open and override of global permissions. - // Since items are created by users and global permissions is set by system admin. - else - { - $result->set($action->name, $user->authorise($action->name, 'com_' . $component)); - } - } - } - return $result; - } - - /** - * Filter the action permissions - * - * @param string $action The action to check - * @param array $targets The array of target actions - * - * @return boolean true if action should be filtered out - * - */ - protected static function filterActions(&$view, &$action, &$targets) - { - foreach ($targets as $target) - { - if (strpos($action, $view . '.' . $target) !== false || - strpos($action, 'core.' . $target) !== false) - { - return false; - break; - } - } - return true; - } - - /** - * Get any component's model - */ - public static function getModel($name, $path = JPATH_COMPONENT_ADMINISTRATOR, $Component = 'Sermondistributor', $config = array()) - { - // fix the name - $name = self::safeString($name); - // full path to models - $fullPathModels = $path . '/models'; - // load the model file - JModelLegacy::addIncludePath($fullPathModels, $Component . 'Model'); - // make sure the table path is loaded - if (!isset($config['table_path']) || !self::checkString($config['table_path'])) - { - // This is the JCB default path to tables in Joomla 3.x - $config['table_path'] = JPATH_ADMINISTRATOR . '/components/com_' . strtolower($Component) . '/tables'; - } - // get instance - $model = JModelLegacy::getInstance($name, $Component . 'Model', $config); - // if model not found (strange) - if ($model == false) - { - jimport('joomla.filesystem.file'); - // get file path - $filePath = $path . '/' . $name . '.php'; - $fullPathModel = $fullPathModels . '/' . $name . '.php'; - // check if it exists - if (File::exists($filePath)) - { - // get the file - require_once $filePath; - } - elseif (File::exists($fullPathModel)) - { - // get the file - require_once $fullPathModel; - } - // build class names - $modelClass = $Component . 'Model' . $name; - if (class_exists($modelClass)) - { - // initialize the model - return new $modelClass($config); - } - } - return $model; - } - - /** - * Add to asset Table - */ - public static function setAsset($id, $table, $inherit = true) - { - $parent = JTable::getInstance('Asset'); - $parent->loadByName('com_sermondistributor'); - - $parentId = $parent->id; - $name = 'com_sermondistributor.'.$table.'.'.$id; - $title = ''; - - $asset = JTable::getInstance('Asset'); - $asset->loadByName($name); - - // Check for an error. - $error = $asset->getError(); - - if ($error) - { - return false; - } - else - { - // Specify how a new or moved node asset is inserted into the tree. - if ($asset->parent_id != $parentId) - { - $asset->setLocation($parentId, 'last-child'); - } - - // Prepare the asset to be stored. - $asset->parent_id = $parentId; - $asset->name = $name; - $asset->title = $title; - // get the default asset rules - $rules = self::getDefaultAssetRules('com_sermondistributor', $table, $inherit); - if ($rules instanceof JAccessRules) - { - $asset->rules = (string) $rules; - } - - if (!$asset->check() || !$asset->store()) - { - JFactory::getApplication()->enqueueMessage($asset->getError(), 'warning'); - return false; - } - else - { - // Create an asset_id or heal one that is corrupted. - $object = new stdClass(); - - // Must be a valid primary key value. - $object->id = $id; - $object->asset_id = (int) $asset->id; - - // Update their asset_id to link to the asset table. - return JFactory::getDbo()->updateObject('#__sermondistributor_'.$table, $object, 'id'); - } - } - return false; - } - - /** - * Gets the default asset Rules for a component/view. - */ - protected static function getDefaultAssetRules($component, $view, $inherit = true) - { - // if new or inherited - $assetId = 0; - // Only get the actual item rules if not inheriting - if (!$inherit) - { - // Need to find the asset id by the name of the component. - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->quoteName('id')) - ->from($db->quoteName('#__assets')) - ->where($db->quoteName('name') . ' = ' . $db->quote($component)); - $db->setQuery($query); - $db->execute(); - // check that there is a value - if ($db->getNumRows()) - { - // asset already set so use saved rules - $assetId = (int) $db->loadResult(); - } - } - // get asset rules - $result = JAccess::getAssetRules($assetId); - if ($result instanceof JAccessRules) - { - $_result = (string) $result; - $_result = json_decode($_result); - foreach ($_result as $name => &$rule) - { - $v = explode('.', $name); - if ($view !== $v[0]) - { - // remove since it is not part of this view - unset($_result->$name); - } - elseif ($inherit) - { - // clear the value since we inherit - $rule = array(); - } - } - // check if there are any view values remaining - if (count((array) $_result)) - { - $_result = json_encode($_result); - $_result = array($_result); - // Instantiate and return the JAccessRules object for the asset rules. - $rules = new JAccessRules($_result); - // return filtered rules - return $rules; - } - } - return $result; - } - - /** - * xmlAppend - * - * @param SimpleXMLElement $xml The XML element reference in which to inject a comment - * @param mixed $node A SimpleXMLElement node to append to the XML element reference, or a stdClass object containing a comment attribute to be injected before the XML node and a fieldXML attribute containing a SimpleXMLElement - * - * @return null - * - */ - public static function xmlAppend(&$xml, $node) - { - if (!$node) - { - // element was not returned - return; - } - switch (get_class($node)) - { - case 'stdClass': - if (property_exists($node, 'comment')) - { - self::xmlComment($xml, $node->comment); - } - if (property_exists($node, 'fieldXML')) - { - self::xmlAppend($xml, $node->fieldXML); - } - break; - case 'SimpleXMLElement': - $domXML = dom_import_simplexml($xml); - $domNode = dom_import_simplexml($node); - $domXML->appendChild($domXML->ownerDocument->importNode($domNode, true)); - $xml = simplexml_import_dom($domXML); - break; - } - } - - /** - * xmlComment - * - * @param SimpleXMLElement $xml The XML element reference in which to inject a comment - * @param string $comment The comment to inject - * - * @return null - * - */ - public static function xmlComment(&$xml, $comment) - { - $domXML = dom_import_simplexml($xml); - $domComment = new DOMComment($comment); - $nodeTarget = $domXML->ownerDocument->importNode($domComment, true); - $domXML->appendChild($nodeTarget); - $xml = simplexml_import_dom($domXML); - } - - /** - * xmlAddAttributes - * - * @param SimpleXMLElement $xml The XML element reference in which to inject a comment - * @param array $attributes The attributes to apply to the XML element - * - * @return null - * - */ - public static function xmlAddAttributes(&$xml, $attributes = array()) - { - foreach ($attributes as $key => $value) - { - $xml->addAttribute($key, $value); - } - } - - /** - * xmlAddOptions - * - * @param SimpleXMLElement $xml The XML element reference in which to inject a comment - * @param array $options The options to apply to the XML element - * - * @return void - * - */ - public static function xmlAddOptions(&$xml, $options = array()) - { - foreach ($options as $key => $value) - { - $addOption = $xml->addChild('option'); - $addOption->addAttribute('value', $key); - $addOption[] = $value; - } - } - - /** - * get the field object - * - * @param array $attributes The array of attributes - * @param string $default The default of the field - * @param array $options The options to apply to the XML element - * - * @return object - * - */ - public static function getFieldObject(&$attributes, $default = '', $options = null) - { - // make sure we have attributes and a type value - if (self::checkArray($attributes) && isset($attributes['type'])) - { - // make sure the form helper class is loaded - if (!method_exists('JFormHelper', 'loadFieldType')) - { - jimport('joomla.form.form'); - } - // get field type - $field = JFormHelper::loadFieldType($attributes['type'], true); - // get field xml - $XML = self::getFieldXML($attributes, $options); - // setup the field - $field->setup($XML, $default); - // return the field object - return $field; - } - return false; - } - - /** - * get the field xml - * - * @param array $attributes The array of attributes - * @param array $options The options to apply to the XML element - * - * @return object - * - */ - public static function getFieldXML(&$attributes, $options = null) - { - // make sure we have attributes and a type value - if (self::checkArray($attributes)) - { - // start field xml - $XML = new SimpleXMLElement(''); - // load the attributes - self::xmlAddAttributes($XML, $attributes); - // check if we have options - if (self::checkArray($options)) - { - // load the options - self::xmlAddOptions($XML, $options); - } - // return the field xml - return $XML; - } - return false; - } - - /** - * Render Bool Button - * - * @param array $args All the args for the button - * 0) name - * 1) additional (options class) // not used at this time - * 2) default - * 3) yes (name) - * 4) no (name) - * - * @return string The input html of the button - * - */ - public static function renderBoolButton() - { - $args = func_get_args(); - // check if there is additional button class - $additional = isset($args[1]) ? (string) $args[1] : ''; // not used at this time - // button attributes - $buttonAttributes = array( - 'type' => 'radio', - 'name' => isset($args[0]) ? self::htmlEscape($args[0]) : 'bool_button', - 'label' => isset($args[0]) ? self::safeString(self::htmlEscape($args[0]), 'Ww') : 'Bool Button', // not seen anyway - 'class' => 'btn-group', - 'filter' => 'INT', - 'default' => isset($args[2]) ? (int) $args[2] : 0); - // set the button options - $buttonOptions = array( - '1' => isset($args[3]) ? self::htmlEscape($args[3]) : 'JYES', - '0' => isset($args[4]) ? self::htmlEscape($args[4]) : 'JNO'); - // return the input - return self::getFieldObject($buttonAttributes, $buttonAttributes['default'], $buttonOptions)->input; - } - - /** - * Check if have an json string - * - * @input string The json string to check - * - * @returns bool true on success - */ - public static function checkJson($string) - { - if (self::checkString($string)) - { - json_decode($string); - return (json_last_error() === JSON_ERROR_NONE); - } - return false; - } - - /** - * Check if have an object with a length - * - * @input object The object to check - * - * @returns bool true on success - */ - public static function checkObject($object) - { - if (isset($object) && is_object($object)) - { - return count((array)$object) > 0; - } - return false; - } - - /** - * Check if have an array with a length - * - * @input array The array to check - * - * @returns bool/int number of items in array on success - */ - public static function checkArray($array, $removeEmptyString = false) - { - if (isset($array) && is_array($array) && ($nr = count((array)$array)) > 0) - { - // also make sure the empty strings are removed - if ($removeEmptyString) - { - foreach ($array as $key => $string) - { - if (empty($string)) - { - unset($array[$key]); - } - } - return self::checkArray($array, false); - } - return $nr; - } - return false; - } - - /** - * Check if have a string with a length - * - * @input string The string to check - * - * @returns bool true on success - */ - public static function checkString($string) - { - if (isset($string) && is_string($string) && strlen($string) > 0) - { - return true; - } - return false; - } - - /** - * Check if we are connected - * Thanks https://stackoverflow.com/a/4860432/1429677 - * - * @returns bool true on success - */ - public static function isConnected() - { - // If example.com is down, then probably the whole internet is down, since IANA maintains the domain. Right? - $connected = @fsockopen("www.example.com", 80); - // website, port (try 80 or 443) - if ($connected) - { - //action when connected - $is_conn = true; - fclose($connected); - } - else - { - //action in connection failure - $is_conn = false; - } - return $is_conn; - } - - /** - * Merge an array of array's - * - * @input array The arrays you would like to merge - * - * @returns array on success - */ - public static function mergeArrays($arrays) - { - if(self::checkArray($arrays)) - { - $arrayBuket = array(); - foreach ($arrays as $array) - { - if (self::checkArray($array)) - { - $arrayBuket = array_merge($arrayBuket, $array); - } - } - return $arrayBuket; - } - return false; - } - - // typo sorry! - public static function sorten($string, $length = 40, $addTip = true) - { - return self::shorten($string, $length, $addTip); - } - - /** - * Shorten a string - * - * @input string The you would like to shorten - * - * @returns string on success - */ - public static function shorten($string, $length = 40, $addTip = true) - { - if (self::checkString($string)) - { - $initial = strlen($string); - $words = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE); - $words_count = count((array)$words); - - $word_length = 0; - $last_word = 0; - for (; $last_word < $words_count; ++$last_word) - { - $word_length += strlen($words[$last_word]); - if ($word_length > $length) - { - break; - } - } - - $newString = implode(array_slice($words, 0, $last_word)); - $final = strlen($newString); - if ($initial != $final && $addTip) - { - $title = self::shorten($string, 400 , false); - return ''.trim($newString).'...'; - } - elseif ($initial != $final && !$addTip) - { - return trim($newString).'...'; - } - } - return $string; - } - - /** - * Making strings safe (various ways) - * - * @input string The you would like to make safe - * - * @returns string on success - */ - public static function safeString($string, $type = 'L', $spacer = '_', $replaceNumbers = true, $keepOnlyCharacters = true) - { - if ($replaceNumbers === true) - { - // remove all numbers and replace with english text version (works well only up to millions) - $string = self::replaceNumbers($string); - } - // 0nly continue if we have a string - if (self::checkString($string)) - { - // create file name without the extention that is safe - if ($type === 'filename') - { - // make sure VDM is not in the string - $string = str_replace('VDM', 'vDm', $string); - // Remove anything which isn't a word, whitespace, number - // or any of the following caracters -_() - // If you don't need to handle multi-byte characters - // you can use preg_replace rather than mb_ereg_replace - // Thanks @Łukasz Rysiak! - // $string = mb_ereg_replace("([^\w\s\d\-_\(\)])", '', $string); - $string = preg_replace("([^\w\s\d\-_\(\)])", '', $string); - // http://stackoverflow.com/a/2021729/1429677 - return preg_replace('/\s+/', ' ', $string); - } - // remove all other characters - $string = trim($string); - $string = preg_replace('/'.$spacer.'+/', ' ', $string); - $string = preg_replace('/\s+/', ' ', $string); - // Transliterate string - $string = self::transliterate($string); - // remove all and keep only characters - if ($keepOnlyCharacters) - { - $string = preg_replace("/[^A-Za-z ]/", '', $string); - } - // keep both numbers and characters - else - { - $string = preg_replace("/[^A-Za-z0-9 ]/", '', $string); - } - // select final adaptations - if ($type === 'L' || $type === 'strtolower') - { - // replace white space with underscore - $string = preg_replace('/\s+/', $spacer, $string); - // default is to return lower - return strtolower($string); - } - elseif ($type === 'W') - { - // return a string with all first letter of each word uppercase(no undersocre) - return ucwords(strtolower($string)); - } - elseif ($type === 'w' || $type === 'word') - { - // return a string with all lowercase(no undersocre) - return strtolower($string); - } - elseif ($type === 'Ww' || $type === 'Word') - { - // return a string with first letter of the first word uppercase and all the rest lowercase(no undersocre) - return ucfirst(strtolower($string)); - } - elseif ($type === 'WW' || $type === 'WORD') - { - // return a string with all the uppercase(no undersocre) - return strtoupper($string); - } - elseif ($type === 'U' || $type === 'strtoupper') - { - // replace white space with underscore - $string = preg_replace('/\s+/', $spacer, $string); - // return all upper - return strtoupper($string); - } - elseif ($type === 'F' || $type === 'ucfirst') - { - // replace white space with underscore - $string = preg_replace('/\s+/', $spacer, $string); - // return with first caracter to upper - return ucfirst(strtolower($string)); - } - elseif ($type === 'cA' || $type === 'cAmel' || $type === 'camelcase') - { - // convert all words to first letter uppercase - $string = ucwords(strtolower($string)); - // remove white space - $string = preg_replace('/\s+/', '', $string); - // now return first letter lowercase - return lcfirst($string); - } - // return string - return $string; - } - // not a string - return ''; - } - - public static function transliterate($string) - { - // set tag only once - if (!self::checkString(self::$langTag)) - { - // get global value - self::$langTag = JComponentHelper::getParams('com_sermondistributor')->get('language', 'en-GB'); - } - // Transliterate on the language requested - $lang = Language::getInstance(self::$langTag); - return $lang->transliterate($string); - } - - public static function htmlEscape($var, $charset = 'UTF-8', $shorten = false, $length = 40) - { - if (self::checkString($var)) - { - $filter = new JFilterInput(); - $string = $filter->clean(html_entity_decode(htmlentities($var, ENT_COMPAT, $charset)), 'HTML'); - if ($shorten) - { - return self::shorten($string,$length); - } - return $string; - } - else - { - return ''; - } - } - - public static function replaceNumbers($string) - { - // set numbers array - $numbers = array(); - // first get all numbers - preg_match_all('!\d+!', $string, $numbers); - // check if we have any numbers - if (isset($numbers[0]) && self::checkArray($numbers[0])) - { - foreach ($numbers[0] as $number) - { - $searchReplace[$number] = self::numberToString((int)$number); - } - // now replace numbers in string - $string = str_replace(array_keys($searchReplace), array_values($searchReplace),$string); - // check if we missed any, strange if we did. - return self::replaceNumbers($string); - } - // return the string with no numbers remaining. - return $string; - } - - /** - * Convert an integer into an English word string - * Thanks to Tom Nicholson - * - * @input an int - * @returns a string - */ - public static function numberToString($x) - { - $nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven", - "eight", "nine", "ten", "eleven", "twelve", "thirteen", - "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", - "nineteen", "twenty", 30 => "thirty", 40 => "forty", - 50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty", - 90 => "ninety" ); - - if(!is_numeric($x)) - { - $w = $x; - } - elseif(fmod($x, 1) != 0) - { - $w = $x; - } - else - { - if($x < 0) - { - $w = 'minus '; - $x = -$x; - } - else - { - $w = ''; - // ... now $x is a non-negative integer. - } - - if($x < 21) // 0 to 20 - { - $w .= $nwords[$x]; - } - elseif($x < 100) // 21 to 99 - { - $w .= $nwords[10 * floor($x/10)]; - $r = fmod($x, 10); - if($r > 0) - { - $w .= ' '. $nwords[$r]; - } - } - elseif($x < 1000) // 100 to 999 - { - $w .= $nwords[floor($x/100)] .' hundred'; - $r = fmod($x, 100); - if($r > 0) - { - $w .= ' and '. self::numberToString($r); - } - } - elseif($x < 1000000) // 1000 to 999999 - { - $w .= self::numberToString(floor($x/1000)) .' thousand'; - $r = fmod($x, 1000); - if($r > 0) - { - $w .= ' '; - if($r < 100) - { - $w .= 'and '; - } - $w .= self::numberToString($r); - } - } - else // millions - { - $w .= self::numberToString(floor($x/1000000)) .' million'; - $r = fmod($x, 1000000); - if($r > 0) - { - $w .= ' '; - if($r < 100) - { - $w .= 'and '; - } - $w .= self::numberToString($r); - } - } - } - return $w; - } - - /** - * Random Key - * - * @returns a string - */ - public static function randomkey($size) - { - $bag = "abcefghijknopqrstuwxyzABCDDEFGHIJKLLMMNOPQRSTUVVWXYZabcddefghijkllmmnopqrstuvvwxyzABCEFGHIJKNOPQRSTUWXYZ"; - $key = array(); - $bagsize = strlen($bag) - 1; - for ($i = 0; $i < $size; $i++) - { - $get = rand(0, $bagsize); - $key[] = $bag[$get]; - } - return implode($key); - } - - /** - * Get The Encryption Keys - * - * @param string $type The type of key - * @param string/bool $default The return value if no key was found - * - * @return string On success - * - **/ - public static function getCryptKey($type, $default = false) - { - // Get the global params - $params = JComponentHelper::getParams('com_sermondistributor', true); - // Basic Encryption Type - if ('basic' === $type) - { - $basic_key = $params->get('basic_key', $default); - if (self::checkString($basic_key)) - { - return $basic_key; - } - } - - return $default; - } -} - diff --git a/admin/language/en-GB/en-GB.com_sermondistributor.ini b/admin/language/en-GB/en-GB.com_sermondistributor.ini index 85b198d3..d1677521 100644 --- a/admin/language/en-GB/en-GB.com_sermondistributor.ini +++ b/admin/language/en-GB/en-GB.com_sermondistributor.ini @@ -1,16 +1,13 @@ COM_SERMONDISTRIBUTOR="Sermon Distributor" COM_SERMONDISTRIBUTOR_ADD_THE_STRONGAPP_GENERATED_ACCESS_TOKENSTRONG_HERE="Add the App Generated access token here." COM_SERMONDISTRIBUTOR_ADD_TOKEN_HERE="ADD TOKEN HERE!" -COM_SERMONDISTRIBUTOR_ALL_IS_GOOD_PLEASE_CHECK_AGAIN_LATTER="All is good, please check again latter." +COM_SERMONDISTRIBUTOR_ALL_IS_GOOD_PLEASE_CHECK_AGAIN_LATER="All is good, please check again later" COM_SERMONDISTRIBUTOR_ALWAYS_BETTER_TO_ADD_THE_FILES_TO_EXTERNAL_SOURCE_AND_LET_THE_SYSTEM_CREATE_THE_SERMON_FOR_YOU_PLEASE_READ_INSTRUCTIONS_BELOW_CAREFULLY="Always better to add the files to External Source and let the system create the sermon for you. Please read instructions below carefully." COM_SERMONDISTRIBUTOR_ARCHIVED="Archived" COM_SERMONDISTRIBUTOR_ARE_YOU_SURE_YOU_WANT_TO_DELETE_CONFIRMING_WILL_PERMANENTLY_DELETE_THE_SELECTED_ITEMS="Are you sure you want to delete? Confirming will permanently delete the selected item(s)!" COM_SERMONDISTRIBUTOR_AUTHOR="Author" -COM_SERMONDISTRIBUTOR_A_FEW_CLOSED_ISSUES_FROM_GITHUB_IS_LOADING="A few closed issues from Github is loading" -COM_SERMONDISTRIBUTOR_A_FEW_OPEN_ISSUES_FROM_GITHUB_IS_LOADING="A few open issues from Github is loading" COM_SERMONDISTRIBUTOR_BACK="Back" COM_SERMONDISTRIBUTOR_BCOULD_NOT_USE_THE_GIVEN_TOKEN_OR_THE_GIVEN_BUILD_OPTION_DOES_NOT_EXISTB="Could not use the given token, or the given build option does not exist." -COM_SERMONDISTRIBUTOR_BETA_RELEASE="Beta Release" COM_SERMONDISTRIBUTOR_BY_USING_AN_ACCESS_TOKEN_YOU_WILL_BE_ABLE_TO_MAKE_API_CALLS_FOR_YOUR_OWN_ACCOUNT_WITHOUT_GOING_THROUGH_THE_AUTHORIZATION_FLOW_DURING_THIS_MANUAL_UPDATE_OF_THE_LOCAL_LISTINGBR_THE_TOKEN_WILL_NOT_BE_STORED_AND_FOR_SAFETY_THE_TOKEN_WILL_BE_REVOKED_ONCE_THE_UPDATE_IS_COMPLETED_SUCCESSFULLYBR_BTHIS_WILL_MEAN_IT_CAN_ONLY_BE_USED_THIS_ONCEB_YOU_WOULD_NEED_A_NEW_TOKEN_EACH_TIME_YOU_RUN_THIS_UPDATE_MANUALLY_BR_SMALLMAKE_SURE_TO_HAVE_SSL_INPLACE_ON_THIS_PAGE_WHEN_DOING_THIS_UPDATE_AS_AN_EXTRA_SECURITY_MEASURESMALL="By using an access token, you will be able to make API calls for your own account without going through the authorization flow during this manual update of the local listing.
The token will not be stored and for safety the token will be revoked once the update is completed successfully.
This will mean it can only be used this once, you would need a new token each time you run this update manually.
Make sure to have SSL in-place on this page when doing this update, as an extra security measure." COM_SERMONDISTRIBUTOR_CATEGORIES_ACCESS_SITE="Categories (Site) Access" COM_SERMONDISTRIBUTOR_CATEGORIES_ACCESS_SITE_DESC="Allows the users in this group to access site categories." @@ -21,7 +18,6 @@ COM_SERMONDISTRIBUTOR_CLEAR_LOCAL_LISTING="Clear Local Listing" COM_SERMONDISTRIBUTOR_CLOSE_NEW="Close & New" COM_SERMONDISTRIBUTOR_CONFIG_ADD_TO_BUTTON_DESCRIPTION="Allow add to external source button to show, this will expose the external source links." COM_SERMONDISTRIBUTOR_CONFIG_ADD_TO_BUTTON_LABEL="External Source Button" -COM_SERMONDISTRIBUTOR_CONFIG_ALMOST_FLAT_LOAD="Almost Flat" COM_SERMONDISTRIBUTOR_CONFIG_AUTHOR="Author Info" COM_SERMONDISTRIBUTOR_CONFIG_AUTHOR_EMAIL_DESC="The email address of the author of this component." COM_SERMONDISTRIBUTOR_CONFIG_AUTHOR_EMAIL_LABEL="Author Email" @@ -129,15 +125,17 @@ COM_SERMONDISTRIBUTOR_CONFIG_DARK_BLUE="Dark Blue" COM_SERMONDISTRIBUTOR_CONFIG_DONT_LOAD="Not" COM_SERMONDISTRIBUTOR_CONFIG_ENCRYPTION_DESC="The encryption key for the field encryption is set here." COM_SERMONDISTRIBUTOR_CONFIG_ENCRYPTION_LABEL="Encryption Settings" -COM_SERMONDISTRIBUTOR_CONFIG_FLAT_LOAD="Flat" COM_SERMONDISTRIBUTOR_CONFIG_FORCE_LOAD="Force" COM_SERMONDISTRIBUTOR_CONFIG_GLOBAL_DESC="The Global Parameters" COM_SERMONDISTRIBUTOR_CONFIG_GLOBAL_LABEL="Global" -COM_SERMONDISTRIBUTOR_CONFIG_GRADIANT_LOAD="Gradient" COM_SERMONDISTRIBUTOR_CONFIG_GREEN="Green" COM_SERMONDISTRIBUTOR_CONFIG_GRID="Grid" COM_SERMONDISTRIBUTOR_CONFIG_HTML_5_BASIC="HTML 5 (basic)" COM_SERMONDISTRIBUTOR_CONFIG_JPLAYER="jPlayer" +COM_SERMONDISTRIBUTOR_CONFIG_JQUERY_LOAD="Load jQuery" +COM_SERMONDISTRIBUTOR_CONFIG_JQUERY_LOAD_DESC="Would you like to load the Joomla jQuery Framework?" +COM_SERMONDISTRIBUTOR_CONFIG_JQUERY_LOAD_LABEL="Load Joomla jQuery" +COM_SERMONDISTRIBUTOR_CONFIG_JQUERY_REMOVE="Remove jQuery" COM_SERMONDISTRIBUTOR_CONFIG_LEGACY="Legacy" COM_SERMONDISTRIBUTOR_CONFIG_LINES="Lines" COM_SERMONDISTRIBUTOR_CONFIG_LIST="List" @@ -315,18 +313,12 @@ COM_SERMONDISTRIBUTOR_CONFIG_SPACED="Spaced" COM_SERMONDISTRIBUTOR_CONFIG_STRIPED="Striped" COM_SERMONDISTRIBUTOR_CONFIG_TABLE="Table" COM_SERMONDISTRIBUTOR_CONFIG_UIKIT="Uikit" -COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_DESC="The Parameters for the uikit are set here.
Uikit is a lightweight and modular front-end frameworkfor developing fast and powerful web interfaces. For more info visit version 2 or version 3" -COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_LABEL="Uikit2 and Uikit3 Settings" +COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_DESC="The Parameters for the uikit are set here.
Uikit is a lightweight and modular front-end frameworkfor developing fast and powerful web interfaces. For more info visit https://getuikit.com/" +COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_LABEL="Uikit3 Settings" COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_LOAD_DESC="Set the uikit loading option." COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_LOAD_LABEL="Loading Options" COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_MIN_DESC="Should the minified version of uikit files be loaded?" COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_MIN_LABEL="Load Minified" -COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_STYLE_DESC="Set the css style that should be used." -COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_STYLE_LABEL="css Style" -COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_V2="Version 2" -COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_V3="Version 3" -COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_VERSION_DESC="Select what version you would like to use" -COM_SERMONDISTRIBUTOR_CONFIG_UIKIT_VERSION_LABEL="Uikit Versions" COM_SERMONDISTRIBUTOR_CONFIG_YES="Yes" COM_SERMONDISTRIBUTOR_CONTRIBUTOR="Contributor" COM_SERMONDISTRIBUTOR_CONTRIBUTORS="Contributors" @@ -347,7 +339,6 @@ COM_SERMONDISTRIBUTOR_DASHBOARD_SERMONS_CATID="Categories For
Sermons" COM_SERMONDISTRIBUTOR_DASHBOARD_SERMON_ADD="Add Sermon

" COM_SERMONDISTRIBUTOR_DASHBOARD_STATISTICS="Statistics

" COM_SERMONDISTRIBUTOR_DATE="Date" -COM_SERMONDISTRIBUTOR_DOWNLOAD="download" COM_SERMONDISTRIBUTOR_DOWNLOAD_NAME="Download Name" COM_SERMONDISTRIBUTOR_EDIT_CREATED_BY="Edit Created By" COM_SERMONDISTRIBUTOR_EDIT_CREATED_BY_DESC="Allows users in this group to edit created by." @@ -368,7 +359,7 @@ COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_ACCESS_DESC="Allows the users in this gro COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_BATCH_OPTIONS="Batch process the selected External Sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_BATCH_TIP="All changes will be applied to all selected External Sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_BATCH_USE="External Sources Batch Use" -COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch external sources" +COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch external sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_CREATE="External Sources Create" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_CREATE_DESC="Allows the users in this group to create create external sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_DASHBOARD_ADD="External Sources Dashboard Add" @@ -388,7 +379,10 @@ COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_OWN_DESC="Allows the users in this g COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_STATE="External Sources Edit State" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_STATE_DESC="Allows the users in this group to update the state of the external source" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_VERSION="External Sources Edit Version" -COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_VERSION_DESC="Allows users in this group to edit versions of version external sources" +COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version external sources" +COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EMPTYSTATE_BUTTON_ADD="Add your first external source" +COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EMPTYSTATE_CONTENT="External sources of files" +COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EMPTYSTATE_TITLE="No external sources have been created yet." COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EXPORT="External Sources Export" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EXPORT_DESC="Allows the users in this group to export export external sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_IMPORT="External Sources Import" @@ -444,6 +438,7 @@ COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_DROPBOXOPTIONS_LABEL="Options" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_DYNAMIC_AUTOMATIC_BUILD="Dynamic Automatic Build" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_EDIT="Editing the External Source" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_ERROR_UNIQUE_ALIAS="Another External Source has the same alias." +COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_ERROR_UNIQUE_ALIAS_TRASHED="A trashed External Source has the same alias ." COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_EXTERNALSOURCES_DESCRIPTION="Only one option at this time" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_EXTERNALSOURCES_LABEL="External Sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_FILETYPES_DESCRIPTION="Select the file types you would like to use from this external sources." @@ -568,7 +563,6 @@ COM_SERMONDISTRIBUTOR_FILTER_SEARCH_PREACHERS="Search the preacher items. Prefix COM_SERMONDISTRIBUTOR_FILTER_SEARCH_SERIES_LIST="Search the series items. Prefix with ID: to search for an item by ID." COM_SERMONDISTRIBUTOR_FILTER_SEARCH_SERMONS="Search the sermon items. Prefix with ID: to search for an item by ID." COM_SERMONDISTRIBUTOR_FILTER_SEARCH_STATISTICS="Search the statistic items. Prefix with ID: to search for an item by ID." -COM_SERMONDISTRIBUTOR_FILTER_SELECT_ACCESS="Select Access" COM_SERMONDISTRIBUTOR_FILTER_SELECT_ADMIN_VIEWS="Select Admin Views" COM_SERMONDISTRIBUTOR_FILTER_SELECT_BUILD_OPTION="Select Build Option" COM_SERMONDISTRIBUTOR_FILTER_SELECT_DOWNLOAD_LINK_OPTION="Select Download Link Option" @@ -606,7 +600,7 @@ COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_ACCESS_DESC="Allows the users in this group COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_BATCH_OPTIONS="Batch process the selected Help Documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_BATCH_TIP="All changes will be applied to all selected Help Documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_BATCH_USE="Help Documents Batch Use" -COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch help documents" +COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch help documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_CREATE="Help Documents Create" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_CREATE_DESC="Allows the users in this group to create create help documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_DASHBOARD_LIST="Help Documents Dashboard List" @@ -620,7 +614,10 @@ COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_OWN_DESC="Allows the users in this gro COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_STATE="Help Documents Edit State" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_STATE_DESC="Allows the users in this group to update the state of the help document" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_VERSION="Help Documents Edit Version" -COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version help documents" +COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version help documents" +COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EMPTYSTATE_BUTTON_ADD="Add your first help document" +COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EMPTYSTATE_CONTENT="The help documentation of this component" +COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EMPTYSTATE_TITLE="No help documents have been created yet." COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EXPORT="Help Documents Export" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EXPORT_DESC="Allows the users in this group to export export help documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_IMPORT="Help Documents Import" @@ -661,6 +658,7 @@ COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_CREATED_DATE_LABEL="Created Date" COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_DETAILS="Details" COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_EDIT="Editing the Help Document" COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_ERROR_UNIQUE_ALIAS="Another Help Document has the same alias." +COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_ERROR_UNIQUE_ALIAS_TRASHED="A trashed Help Document has the same alias ." COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_GROUPS_DESCRIPTION="Select a group/s" COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_GROUPS_LABEL="Group/s" COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_ID="Id" @@ -743,13 +741,10 @@ COM_SERMONDISTRIBUTOR_IMPORT_UNABLE_TO_FIND_IMPORT_PACKAGE="Package to import no COM_SERMONDISTRIBUTOR_IMPORT_UPDATE_DATA="Import Data" COM_SERMONDISTRIBUTOR_IMPORT_UPLOAD_BOTTON="Upload File" COM_SERMONDISTRIBUTOR_INACTIVE="Inactive" -COM_SERMONDISTRIBUTOR_ISSUE="issue" COM_SERMONDISTRIBUTOR_KEEP_ORIGINAL_ACCESS="- Keep Original Access -" COM_SERMONDISTRIBUTOR_KEEP_ORIGINAL_CATEGORY="- Keep Original Category -" COM_SERMONDISTRIBUTOR_KEEP_ORIGINAL_STATE="- Keep Original State -" -COM_SERMONDISTRIBUTOR_LAST_FEW_RELEASES_FROM_GITHUB_IS_LOADING="Last few releases from Github is loading" COM_SERMONDISTRIBUTOR_LAST_UPDATE="Last Update" -COM_SERMONDISTRIBUTOR_LATEST_RELEASE="Latest Release" COM_SERMONDISTRIBUTOR_LICENSE="License" COM_SERMONDISTRIBUTOR_LISTING_INFO="Listing Info" COM_SERMONDISTRIBUTOR_LOCAL_LISTING="Local Listing" @@ -759,7 +754,7 @@ COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_ACCESS_DESC="Allows the users in this group COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_BATCH_OPTIONS="Batch process the selected Local Listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_BATCH_TIP="All changes will be applied to all selected Local Listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_BATCH_USE="Local Listings Batch Use" -COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch local listings" +COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch local listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_CREATE="Local Listings Create" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_CREATE_DESC="Allows the users in this group to create create local listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_DASHBOARD_LIST="Local Listings Dashboard List" @@ -789,7 +784,10 @@ COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_STATE_DESC="Allows the users in this g COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_URL="Local Listings Edit Url" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_URL_DESC="Allows the users in this group to edit url of local listing" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_VERSION="Local Listings Edit Version" -COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version local listings" +COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version local listings" +COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EMPTYSTATE_BUTTON_ADD="Add your first local listing" +COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EMPTYSTATE_CONTENT="Local Listing of files" +COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EMPTYSTATE_TITLE="No local listings have been created yet." COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EXPORT="Local Listings Export" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EXPORT_DESC="Allows the users in this group to export export local listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_IMPORT="Local Listings Import" @@ -825,6 +823,7 @@ COM_SERMONDISTRIBUTOR_LOCAL_LISTING_DETAILS="Details" COM_SERMONDISTRIBUTOR_LOCAL_LISTING_DYNAMIC_AUTOMATIC_BUILD="Dynamic Automatic Build" COM_SERMONDISTRIBUTOR_LOCAL_LISTING_EDIT="Editing the Local Listing" COM_SERMONDISTRIBUTOR_LOCAL_LISTING_ERROR_UNIQUE_ALIAS="Another Local Listing has the same alias." +COM_SERMONDISTRIBUTOR_LOCAL_LISTING_ERROR_UNIQUE_ALIAS_TRASHED="A trashed Local Listing has the same alias ." COM_SERMONDISTRIBUTOR_LOCAL_LISTING_EXTERNAL_SOURCE_DESCRIPTION="The external source of this listing" COM_SERMONDISTRIBUTOR_LOCAL_LISTING_EXTERNAL_SOURCE_LABEL="External Source" COM_SERMONDISTRIBUTOR_LOCAL_LISTING_ID="Id" @@ -871,7 +870,6 @@ COM_SERMONDISTRIBUTOR_MANUAL_UPDATER_EXTERNAL_SOURCES_BUTTON_ACCESS_DESC="Allows COM_SERMONDISTRIBUTOR_MANUAL_UPDATER_SUBMENU="Manual Updater Submenu" COM_SERMONDISTRIBUTOR_MANUAL_UPDATER_SUBMENU_DESC="Allows the users in this group to submenu of Manual Updater" COM_SERMONDISTRIBUTOR_NEW="New" -COM_SERMONDISTRIBUTOR_NEW_ISSUE="New Issue" COM_SERMONDISTRIBUTOR_NOTICE="Notice!" COM_SERMONDISTRIBUTOR_NOT_FOUND_OR_ACCESS_DENIED="Not found, or access denied." COM_SERMONDISTRIBUTOR_NO_ACCESS_GRANTED="No Access Granted!" @@ -881,13 +879,8 @@ COM_SERMONDISTRIBUTOR_NO_FILES_LINKED_YET="No Files Linked Yet" COM_SERMONDISTRIBUTOR_NO_ID_FOUND_CAN_NOT_RESET_THE_UPDATE_STATUS="No id found, can not reset the update status!" COM_SERMONDISTRIBUTOR_NO_MANUAL_UPDATES_AVAILABLE="No Manual Updates Available" COM_SERMONDISTRIBUTOR_NUMBER_OF_FILES_LISTED="Number of Files Listed" -COM_SERMONDISTRIBUTOR_ON_GITHUB="on Github" -COM_SERMONDISTRIBUTOR_OPEN="Open" -COM_SERMONDISTRIBUTOR_OPENED="opened" -COM_SERMONDISTRIBUTOR_OPENED_THIS="opened this" -COM_SERMONDISTRIBUTOR_OPEN_ON_GITHUB="Open on Github" -COM_SERMONDISTRIBUTOR_OUT_OF_DATE="Out of date" COM_SERMONDISTRIBUTOR_PLEASE_ADD_FILES_TO_S="Please add files to (%s)" +COM_SERMONDISTRIBUTOR_PLEASE_CHECK_AGAIN_LATER="Please check again later" COM_SERMONDISTRIBUTOR_PLEASE_CHECK_AGAIN_LATTER="Please check again latter." COM_SERMONDISTRIBUTOR_PREACHER="Preacher" COM_SERMONDISTRIBUTOR_PREACHERS="Preachers" @@ -898,7 +891,7 @@ COM_SERMONDISTRIBUTOR_PREACHERS_ACCESS_SITE_DESC="Allows the users in this group COM_SERMONDISTRIBUTOR_PREACHERS_BATCH_OPTIONS="Batch process the selected Preachers" COM_SERMONDISTRIBUTOR_PREACHERS_BATCH_TIP="All changes will be applied to all selected Preachers" COM_SERMONDISTRIBUTOR_PREACHERS_BATCH_USE="Preachers Batch Use" -COM_SERMONDISTRIBUTOR_PREACHERS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch preachers" +COM_SERMONDISTRIBUTOR_PREACHERS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch preachers" COM_SERMONDISTRIBUTOR_PREACHERS_CREATE="Preachers Create" COM_SERMONDISTRIBUTOR_PREACHERS_CREATE_DESC="Allows the users in this group to create create preachers" COM_SERMONDISTRIBUTOR_PREACHERS_DASHBOARD_ADD="Preachers Dashboard Add" @@ -918,7 +911,10 @@ COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_OWN_DESC="Allows the users in this group to COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_STATE="Preachers Edit State" COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_STATE_DESC="Allows the users in this group to update the state of the preacher" COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_VERSION="Preachers Edit Version" -COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version preachers" +COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version preachers" +COM_SERMONDISTRIBUTOR_PREACHERS_EMPTYSTATE_BUTTON_ADD="Add your first preacher" +COM_SERMONDISTRIBUTOR_PREACHERS_EMPTYSTATE_CONTENT="The Speakers/Preachers of the audio or video recordings." +COM_SERMONDISTRIBUTOR_PREACHERS_EMPTYSTATE_TITLE="No preachers have been created yet." COM_SERMONDISTRIBUTOR_PREACHERS_EXPORT="Preachers Export" COM_SERMONDISTRIBUTOR_PREACHERS_EXPORT_DESC="Allows the users in this group to export export preachers" COM_SERMONDISTRIBUTOR_PREACHERS_IMPORT="Preachers Import" @@ -961,6 +957,7 @@ COM_SERMONDISTRIBUTOR_PREACHER_EMAIL_HINT="demo@example.com" COM_SERMONDISTRIBUTOR_PREACHER_EMAIL_LABEL="Email
not required" COM_SERMONDISTRIBUTOR_PREACHER_EMAIL_MESSAGE="Error! Please add email address here." COM_SERMONDISTRIBUTOR_PREACHER_ERROR_UNIQUE_ALIAS="Another Preacher has the same alias." +COM_SERMONDISTRIBUTOR_PREACHER_ERROR_UNIQUE_ALIAS_TRASHED="A trashed Preacher has the same alias ." COM_SERMONDISTRIBUTOR_PREACHER_ICON_DESCRIPTION="Must be 358px x 358px" COM_SERMONDISTRIBUTOR_PREACHER_ICON_LABEL="Icon" COM_SERMONDISTRIBUTOR_PREACHER_ID="Id" @@ -986,12 +983,9 @@ COM_SERMONDISTRIBUTOR_PREACHER_WEBSITE_HINT="http://www.example.com" COM_SERMONDISTRIBUTOR_PREACHER_WEBSITE_LABEL="Website" COM_SERMONDISTRIBUTOR_PREACHER_WEBSITE_MESSAGE="Error! Please add website here." COM_SERMONDISTRIBUTOR_PUBLISHED="Published" -COM_SERMONDISTRIBUTOR_RELEASED_THIS="released this" COM_SERMONDISTRIBUTOR_RESETTING_THE_UPDATE_STATUS_WAS_SUCCESSFUL="Resetting the update status was successful!" COM_SERMONDISTRIBUTOR_RESET_UPDATE_STATUS="Reset Update Status" COM_SERMONDISTRIBUTOR_RESET_UPDATE_STATUS_CAN_NOT_BE_DONE="Reset update status can not be done." -COM_SERMONDISTRIBUTOR_RESPOND_TO_THIS_ISSUE_ON_GITHUB="Respond to this issue on Github" -COM_SERMONDISTRIBUTOR_REVIEW_THIS_ISSUE_ON_GITHUB="Review this issue on Github" COM_SERMONDISTRIBUTOR_SAVE_SUCCESS="Great! Item successfully saved." COM_SERMONDISTRIBUTOR_SAVE_WARNING="The value already existed so please select another." COM_SERMONDISTRIBUTOR_SELECT_AN_ADMIN_VIEW="Select an admin view" @@ -1011,6 +1005,7 @@ COM_SERMONDISTRIBUTOR_SERIES_DESCRIPTION_LABEL="Description" COM_SERMONDISTRIBUTOR_SERIES_DETAILS="Details" COM_SERMONDISTRIBUTOR_SERIES_EDIT="Editing the Series" COM_SERMONDISTRIBUTOR_SERIES_ERROR_UNIQUE_ALIAS="Another Series has the same alias." +COM_SERMONDISTRIBUTOR_SERIES_ERROR_UNIQUE_ALIAS_TRASHED="A trashed Series has the same alias ." COM_SERMONDISTRIBUTOR_SERIES_ICON_DESCRIPTION="Must be 358px x 358px" COM_SERMONDISTRIBUTOR_SERIES_ICON_LABEL="Icon" COM_SERMONDISTRIBUTOR_SERIES_ID="Id" @@ -1022,7 +1017,7 @@ COM_SERMONDISTRIBUTOR_SERIES_LIST_ACCESS_SITE_DESC="Allows the users in this gro COM_SERMONDISTRIBUTOR_SERIES_LIST_BATCH_OPTIONS="Batch process the selected Series List" COM_SERMONDISTRIBUTOR_SERIES_LIST_BATCH_TIP="All changes will be applied to all selected Series List" COM_SERMONDISTRIBUTOR_SERIES_LIST_BATCH_USE="Series List Batch Use" -COM_SERMONDISTRIBUTOR_SERIES_LIST_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch series list" +COM_SERMONDISTRIBUTOR_SERIES_LIST_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch series list" COM_SERMONDISTRIBUTOR_SERIES_LIST_CREATE="Series List Create" COM_SERMONDISTRIBUTOR_SERIES_LIST_CREATE_DESC="Allows the users in this group to create create series list" COM_SERMONDISTRIBUTOR_SERIES_LIST_DASHBOARD_ADD="Series List Dashboard Add" @@ -1042,7 +1037,10 @@ COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_OWN_DESC="Allows the users in this group COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_STATE="Series List Edit State" COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_STATE_DESC="Allows the users in this group to update the state of the series" COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_VERSION="Series List Edit Version" -COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_VERSION_DESC="Allows users in this group to edit versions of version series list" +COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version series list" +COM_SERMONDISTRIBUTOR_SERIES_LIST_EMPTYSTATE_BUTTON_ADD="Add your first series" +COM_SERMONDISTRIBUTOR_SERIES_LIST_EMPTYSTATE_CONTENT="Bundle a number of things of a similar kind or related nature coming one after another." +COM_SERMONDISTRIBUTOR_SERIES_LIST_EMPTYSTATE_TITLE="No series list have been created yet." COM_SERMONDISTRIBUTOR_SERIES_LIST_EXPORT="Series List Export" COM_SERMONDISTRIBUTOR_SERIES_LIST_EXPORT_DESC="Allows the users in this group to export export series list" COM_SERMONDISTRIBUTOR_SERIES_LIST_IMPORT="Series List Import" @@ -1096,7 +1094,7 @@ COM_SERMONDISTRIBUTOR_SERMONS_ACCESS_DESC="Allows the users in this group to acc COM_SERMONDISTRIBUTOR_SERMONS_BATCH_OPTIONS="Batch process the selected Sermons" COM_SERMONDISTRIBUTOR_SERMONS_BATCH_TIP="All changes will be applied to all selected Sermons" COM_SERMONDISTRIBUTOR_SERMONS_BATCH_USE="Sermons Batch Use" -COM_SERMONDISTRIBUTOR_SERMONS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch sermons" +COM_SERMONDISTRIBUTOR_SERMONS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch sermons" COM_SERMONDISTRIBUTOR_SERMONS_CREATE="Sermons Create" COM_SERMONDISTRIBUTOR_SERMONS_CREATE_DESC="Allows the users in this group to create create sermons" COM_SERMONDISTRIBUTOR_SERMONS_DASHBOARD_ADD="Sermons Dashboard Add" @@ -1116,7 +1114,10 @@ COM_SERMONDISTRIBUTOR_SERMONS_EDIT_OWN_DESC="Allows the users in this group to e COM_SERMONDISTRIBUTOR_SERMONS_EDIT_STATE="Sermons Edit State" COM_SERMONDISTRIBUTOR_SERMONS_EDIT_STATE_DESC="Allows the users in this group to update the state of the sermon" COM_SERMONDISTRIBUTOR_SERMONS_EDIT_VERSION="Sermons Edit Version" -COM_SERMONDISTRIBUTOR_SERMONS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version sermons" +COM_SERMONDISTRIBUTOR_SERMONS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version sermons" +COM_SERMONDISTRIBUTOR_SERMONS_EMPTYSTATE_BUTTON_ADD="Add your first sermon" +COM_SERMONDISTRIBUTOR_SERMONS_EMPTYSTATE_CONTENT="The Sermon details of the audio or video recordings." +COM_SERMONDISTRIBUTOR_SERMONS_EMPTYSTATE_TITLE="No sermons have been created yet." COM_SERMONDISTRIBUTOR_SERMONS_EXPORT="Sermons Export" COM_SERMONDISTRIBUTOR_SERMONS_EXPORT_DESC="Allows the users in this group to export export sermons" COM_SERMONDISTRIBUTOR_SERMONS_IMPORT="Sermons Import" @@ -1162,6 +1163,7 @@ COM_SERMONDISTRIBUTOR_SERMON_DYNAMIC_AUTOMATIC_BUILD="Dynamic Automatic Build" COM_SERMONDISTRIBUTOR_SERMON_EDIT="Editing the Sermon" COM_SERMONDISTRIBUTOR_SERMON_ENCRYPTED="Encrypted" COM_SERMONDISTRIBUTOR_SERMON_ERROR_UNIQUE_ALIAS="Another Sermon has the same alias." +COM_SERMONDISTRIBUTOR_SERMON_ERROR_UNIQUE_ALIAS_TRASHED="A trashed Sermon has the same alias ." COM_SERMONDISTRIBUTOR_SERMON_EXTERNAL_SOURCE="External Source" COM_SERMONDISTRIBUTOR_SERMON_FILES="Files" COM_SERMONDISTRIBUTOR_SERMON_ICON_DESCRIPTION="Must be 358px x 358px" @@ -1234,7 +1236,7 @@ COM_SERMONDISTRIBUTOR_STATISTICS_ACCESS_DESC="Allows the users in this group to COM_SERMONDISTRIBUTOR_STATISTICS_BATCH_OPTIONS="Batch process the selected Statistics" COM_SERMONDISTRIBUTOR_STATISTICS_BATCH_TIP="All changes will be applied to all selected Statistics" COM_SERMONDISTRIBUTOR_STATISTICS_BATCH_USE="Statistics Batch Use" -COM_SERMONDISTRIBUTOR_STATISTICS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch statistics" +COM_SERMONDISTRIBUTOR_STATISTICS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch statistics" COM_SERMONDISTRIBUTOR_STATISTICS_CREATE="Statistics Create" COM_SERMONDISTRIBUTOR_STATISTICS_CREATE_DESC="Allows the users in this group to create create statistics" COM_SERMONDISTRIBUTOR_STATISTICS_DASHBOARD_LIST="Statistics Dashboard List" @@ -1252,7 +1254,10 @@ COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_OWN_DESC="Allows the users in this group t COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_STATE="Statistics Edit State" COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_STATE_DESC="Allows the users in this group to update the state of the statistic" COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_VERSION="Statistics Edit Version" -COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version statistics" +COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version statistics" +COM_SERMONDISTRIBUTOR_STATISTICS_EMPTYSTATE_BUTTON_ADD="Add your first statistic" +COM_SERMONDISTRIBUTOR_STATISTICS_EMPTYSTATE_CONTENT="The data on each file's statistics" +COM_SERMONDISTRIBUTOR_STATISTICS_EMPTYSTATE_TITLE="No statistics have been created yet." COM_SERMONDISTRIBUTOR_STATISTICS_EXPORT="Statistics Export" COM_SERMONDISTRIBUTOR_STATISTICS_EXPORT_DESC="Allows the users in this group to export export statistics" COM_SERMONDISTRIBUTOR_STATISTICS_IMPORT="Statistics Import" @@ -1289,6 +1294,7 @@ COM_SERMONDISTRIBUTOR_STATISTIC_CREATED_DATE_LABEL="Created Date" COM_SERMONDISTRIBUTOR_STATISTIC_DETAILS="Details" COM_SERMONDISTRIBUTOR_STATISTIC_EDIT="Editing the Statistic" COM_SERMONDISTRIBUTOR_STATISTIC_ERROR_UNIQUE_ALIAS="Another Statistic has the same alias." +COM_SERMONDISTRIBUTOR_STATISTIC_ERROR_UNIQUE_ALIAS_TRASHED="A trashed Statistic has the same alias ." COM_SERMONDISTRIBUTOR_STATISTIC_FILENAME_DESCRIPTION="Enter the file name." COM_SERMONDISTRIBUTOR_STATISTIC_FILENAME_HINT="the_file_name.mp3" COM_SERMONDISTRIBUTOR_STATISTIC_FILENAME_LABEL="File Name" @@ -1334,7 +1340,6 @@ COM_SERMONDISTRIBUTOR_THE_README_IS_LOADING="The readme is loading" COM_SERMONDISTRIBUTOR_THE_UPDATE_IS_RUNNING="The update is running." COM_SERMONDISTRIBUTOR_THE_WIKI_IS_LOADING="The wiki is loading" COM_SERMONDISTRIBUTOR_THIS_SOURCE_HAS_NO_LOCAL_LISTING_SET="This source has no local listing set." -COM_SERMONDISTRIBUTOR_TOTAL_DOWNLOADS="total downloads" COM_SERMONDISTRIBUTOR_TRASHED="Trashed" COM_SERMONDISTRIBUTOR_TRASHED_ITEMS="Trashed items" COM_SERMONDISTRIBUTOR_TRASH_AREA="Trash Area" @@ -1347,13 +1352,10 @@ COM_SERMONDISTRIBUTOR_TYPE_SERMON="Sermon" COM_SERMONDISTRIBUTOR_TYPE_STATISTIC="Statistic" COM_SERMONDISTRIBUTOR_UNKNOWN_ERROR_HAS_OCCURRED="Unknown error has occurred." COM_SERMONDISTRIBUTOR_UPDATE_LOCAL_LINKS_OF_TARGET_S_EXTERNAL_SOURCE="Update Local Links of (target %s) External Source" -COM_SERMONDISTRIBUTOR_UP_TO_DATE="Up to date" COM_SERMONDISTRIBUTOR_USE_BATCH="Use Batch" COM_SERMONDISTRIBUTOR_USE_BATCH_DESC="Allows users in this group to use batch copy/update method." COM_SERMONDISTRIBUTOR_VERSION="Version" COM_SERMONDISTRIBUTOR_VIEW_ERROR="View Error!" -COM_SERMONDISTRIBUTOR_VIEW_MORE_ISSUES_ON_GITHUB="View more issues on Github" -COM_SERMONDISTRIBUTOR_VIEW_MORE_RELEASES_ON_GITHUB="View more releases on Github" COM_SERMONDISTRIBUTOR_VIEW_UPDATE_STATUS="View Update Status" COM_SERMONDISTRIBUTOR_WEBSITE="Website" COM_SERMONDISTRIBUTOR_YOU_ARE_CURRENTLY_VIEWING_THE_TRASHED_ITEMS="You are currently viewing the trashed items." diff --git a/admin/language/en-GB/en-GB.com_sermondistributor.sys.ini b/admin/language/en-GB/en-GB.com_sermondistributor.sys.ini index 5410fe93..5ad0ec79 100644 --- a/admin/language/en-GB/en-GB.com_sermondistributor.sys.ini +++ b/admin/language/en-GB/en-GB.com_sermondistributor.sys.ini @@ -15,7 +15,7 @@ COM_SERMONDISTRIBUTOR_EXPORT_DATA_DESC="Allows users in this group to export dat COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_ACCESS="External Sources Access" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_ACCESS_DESC="Allows the users in this group to access access external sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_BATCH_USE="External Sources Batch Use" -COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch external sources" +COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch external sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_CREATE="External Sources Create" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_CREATE_DESC="Allows the users in this group to create create external sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_DASHBOARD_ADD="External Sources Dashboard Add" @@ -35,7 +35,7 @@ COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_OWN_DESC="Allows the users in this g COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_STATE="External Sources Edit State" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_STATE_DESC="Allows the users in this group to update the state of the external source" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_VERSION="External Sources Edit Version" -COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_VERSION_DESC="Allows users in this group to edit versions of version external sources" +COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version external sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EXPORT="External Sources Export" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_EXPORT_DESC="Allows the users in this group to export export external sources" COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES_IMPORT="External Sources Import" @@ -49,7 +49,7 @@ COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_RESET_UPDATE_STATUS_BUTTON_ACCESS_DESC="Al COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_ACCESS="Help Documents Access" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_ACCESS_DESC="Allows the users in this group to access access help documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_BATCH_USE="Help Documents Batch Use" -COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch help documents" +COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch help documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_CREATE="Help Documents Create" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_CREATE_DESC="Allows the users in this group to create create help documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_DASHBOARD_LIST="Help Documents Dashboard List" @@ -63,7 +63,7 @@ COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_OWN_DESC="Allows the users in this gro COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_STATE="Help Documents Edit State" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_STATE_DESC="Allows the users in this group to update the state of the help document" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_VERSION="Help Documents Edit Version" -COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version help documents" +COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version help documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EXPORT="Help Documents Export" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_EXPORT_DESC="Allows the users in this group to export export help documents" COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS_IMPORT="Help Documents Import" @@ -75,7 +75,7 @@ COM_SERMONDISTRIBUTOR_IMPORT_DATA_DESC="Allows users in this group to import dat COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_ACCESS="Local Listings Access" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_ACCESS_DESC="Allows the users in this group to access access local listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_BATCH_USE="Local Listings Batch Use" -COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch local listings" +COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch local listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_CREATE="Local Listings Create" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_CREATE_DESC="Allows the users in this group to create create local listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_DASHBOARD_LIST="Local Listings Dashboard List" @@ -105,7 +105,7 @@ COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_STATE_DESC="Allows the users in this g COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_URL="Local Listings Edit Url" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_URL_DESC="Allows the users in this group to edit url of local listing" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_VERSION="Local Listings Edit Version" -COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version local listings" +COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version local listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EXPORT="Local Listings Export" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_EXPORT_DESC="Allows the users in this group to export export local listings" COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS_IMPORT="Local Listings Import" @@ -120,13 +120,15 @@ COM_SERMONDISTRIBUTOR_MANUAL_UPDATER_EXTERNAL_SOURCES_BUTTON_ACCESS="Manual Upda COM_SERMONDISTRIBUTOR_MANUAL_UPDATER_EXTERNAL_SOURCES_BUTTON_ACCESS_DESC="Allows the users in this group to access the external sources button." COM_SERMONDISTRIBUTOR_MANUAL_UPDATER_SUBMENU="Manual Updater Submenu" COM_SERMONDISTRIBUTOR_MANUAL_UPDATER_SUBMENU_DESC="Allows the users in this group to submenu of Manual Updater" -COM_SERMONDISTRIBUTOR_MENU="» Sermon Distributor" +COM_SERMONDISTRIBUTOR_MENU="Sermon Distributor" COM_SERMONDISTRIBUTOR_MENU_CATEGORIES_DESC="All categories that are published" COM_SERMONDISTRIBUTOR_MENU_CATEGORIES_OPTION="Categories" COM_SERMONDISTRIBUTOR_MENU_CATEGORIES_TITLE="Categories" COM_SERMONDISTRIBUTOR_MENU_CATEGORY_DESC="A category that is published" COM_SERMONDISTRIBUTOR_MENU_CATEGORY_OPTION="Category" COM_SERMONDISTRIBUTOR_MENU_CATEGORY_TITLE="Category" +COM_SERMONDISTRIBUTOR_MENU_DASHBOARD="Dashboard" +COM_SERMONDISTRIBUTOR_MENU_MANUAL_UPDATER="Manual Updater" COM_SERMONDISTRIBUTOR_MENU_PREACHERS="Preachers" COM_SERMONDISTRIBUTOR_MENU_PREACHERS_DESC="All preachers that are published" COM_SERMONDISTRIBUTOR_MENU_PREACHERS_OPTION="Preachers" @@ -147,7 +149,7 @@ COM_SERMONDISTRIBUTOR_PREACHERS_ACCESS_DESC="Allows the users in this group to a COM_SERMONDISTRIBUTOR_PREACHERS_ACCESS_SITE="Preachers (Site) Access" COM_SERMONDISTRIBUTOR_PREACHERS_ACCESS_SITE_DESC="Allows the users in this group to access site preachers." COM_SERMONDISTRIBUTOR_PREACHERS_BATCH_USE="Preachers Batch Use" -COM_SERMONDISTRIBUTOR_PREACHERS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch preachers" +COM_SERMONDISTRIBUTOR_PREACHERS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch preachers" COM_SERMONDISTRIBUTOR_PREACHERS_CREATE="Preachers Create" COM_SERMONDISTRIBUTOR_PREACHERS_CREATE_DESC="Allows the users in this group to create create preachers" COM_SERMONDISTRIBUTOR_PREACHERS_DASHBOARD_ADD="Preachers Dashboard Add" @@ -167,7 +169,7 @@ COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_OWN_DESC="Allows the users in this group to COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_STATE="Preachers Edit State" COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_STATE_DESC="Allows the users in this group to update the state of the preacher" COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_VERSION="Preachers Edit Version" -COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version preachers" +COM_SERMONDISTRIBUTOR_PREACHERS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version preachers" COM_SERMONDISTRIBUTOR_PREACHERS_EXPORT="Preachers Export" COM_SERMONDISTRIBUTOR_PREACHERS_EXPORT_DESC="Allows the users in this group to export export preachers" COM_SERMONDISTRIBUTOR_PREACHERS_IMPORT="Preachers Import" @@ -183,7 +185,7 @@ COM_SERMONDISTRIBUTOR_SERIES_LIST_ACCESS_DESC="Allows the users in this group to COM_SERMONDISTRIBUTOR_SERIES_LIST_ACCESS_SITE="Series List (Site) Access" COM_SERMONDISTRIBUTOR_SERIES_LIST_ACCESS_SITE_DESC="Allows the users in this group to access site series list." COM_SERMONDISTRIBUTOR_SERIES_LIST_BATCH_USE="Series List Batch Use" -COM_SERMONDISTRIBUTOR_SERIES_LIST_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch series list" +COM_SERMONDISTRIBUTOR_SERIES_LIST_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch series list" COM_SERMONDISTRIBUTOR_SERIES_LIST_CREATE="Series List Create" COM_SERMONDISTRIBUTOR_SERIES_LIST_CREATE_DESC="Allows the users in this group to create create series list" COM_SERMONDISTRIBUTOR_SERIES_LIST_DASHBOARD_ADD="Series List Dashboard Add" @@ -203,7 +205,7 @@ COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_OWN_DESC="Allows the users in this group COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_STATE="Series List Edit State" COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_STATE_DESC="Allows the users in this group to update the state of the series" COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_VERSION="Series List Edit Version" -COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_VERSION_DESC="Allows users in this group to edit versions of version series list" +COM_SERMONDISTRIBUTOR_SERIES_LIST_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version series list" COM_SERMONDISTRIBUTOR_SERIES_LIST_EXPORT="Series List Export" COM_SERMONDISTRIBUTOR_SERIES_LIST_EXPORT_DESC="Allows the users in this group to export export series list" COM_SERMONDISTRIBUTOR_SERIES_LIST_IMPORT="Series List Import" @@ -213,7 +215,7 @@ COM_SERMONDISTRIBUTOR_SERIES_LIST_SUBMENU_DESC="Allows the users in this group t COM_SERMONDISTRIBUTOR_SERMONS_ACCESS="Sermons Access" COM_SERMONDISTRIBUTOR_SERMONS_ACCESS_DESC="Allows the users in this group to access access sermons" COM_SERMONDISTRIBUTOR_SERMONS_BATCH_USE="Sermons Batch Use" -COM_SERMONDISTRIBUTOR_SERMONS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch sermons" +COM_SERMONDISTRIBUTOR_SERMONS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch sermons" COM_SERMONDISTRIBUTOR_SERMONS_CREATE="Sermons Create" COM_SERMONDISTRIBUTOR_SERMONS_CREATE_DESC="Allows the users in this group to create create sermons" COM_SERMONDISTRIBUTOR_SERMONS_DASHBOARD_ADD="Sermons Dashboard Add" @@ -233,7 +235,7 @@ COM_SERMONDISTRIBUTOR_SERMONS_EDIT_OWN_DESC="Allows the users in this group to e COM_SERMONDISTRIBUTOR_SERMONS_EDIT_STATE="Sermons Edit State" COM_SERMONDISTRIBUTOR_SERMONS_EDIT_STATE_DESC="Allows the users in this group to update the state of the sermon" COM_SERMONDISTRIBUTOR_SERMONS_EDIT_VERSION="Sermons Edit Version" -COM_SERMONDISTRIBUTOR_SERMONS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version sermons" +COM_SERMONDISTRIBUTOR_SERMONS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version sermons" COM_SERMONDISTRIBUTOR_SERMONS_EXPORT="Sermons Export" COM_SERMONDISTRIBUTOR_SERMONS_EXPORT_DESC="Allows the users in this group to export export sermons" COM_SERMONDISTRIBUTOR_SERMONS_IMPORT="Sermons Import" @@ -245,7 +247,7 @@ COM_SERMONDISTRIBUTOR_SERMON_ACCESS_SITE_DESC="Allows the users in this group to COM_SERMONDISTRIBUTOR_STATISTICS_ACCESS="Statistics Access" COM_SERMONDISTRIBUTOR_STATISTICS_ACCESS_DESC="Allows the users in this group to access access statistics" COM_SERMONDISTRIBUTOR_STATISTICS_BATCH_USE="Statistics Batch Use" -COM_SERMONDISTRIBUTOR_STATISTICS_BATCH_USE_DESC="Allows users in this group to use batch copy/update method of batch statistics" +COM_SERMONDISTRIBUTOR_STATISTICS_BATCH_USE_DESC="Allows the users in this group to use batch copy/update method of batch statistics" COM_SERMONDISTRIBUTOR_STATISTICS_CREATE="Statistics Create" COM_SERMONDISTRIBUTOR_STATISTICS_CREATE_DESC="Allows the users in this group to create create statistics" COM_SERMONDISTRIBUTOR_STATISTICS_DASHBOARD_LIST="Statistics Dashboard List" @@ -263,7 +265,7 @@ COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_OWN_DESC="Allows the users in this group t COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_STATE="Statistics Edit State" COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_STATE_DESC="Allows the users in this group to update the state of the statistic" COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_VERSION="Statistics Edit Version" -COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_VERSION_DESC="Allows users in this group to edit versions of version statistics" +COM_SERMONDISTRIBUTOR_STATISTICS_EDIT_VERSION_DESC="Allows the users in this group to edit versions of version statistics" COM_SERMONDISTRIBUTOR_STATISTICS_EXPORT="Statistics Export" COM_SERMONDISTRIBUTOR_STATISTICS_EXPORT_DESC="Allows the users in this group to export export statistics" COM_SERMONDISTRIBUTOR_STATISTICS_IMPORT="Statistics Import" diff --git a/admin/layouts/batchselection.php b/admin/layouts/batchselection.php deleted file mode 100644 index 3492b47b..00000000 --- a/admin/layouts/batchselection.php +++ /dev/null @@ -1,61 +0,0 @@ - - @copyright Copyright (C) 2015. All Rights Reserved - @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html - - A sermon distributor that links to Dropbox. - -/----------------------------------------------------------------------------------------------------------------------------------*/ - -// No direct access to this file -defined('JPATH_BASE') or die; - -JHtmlBehavior::core(); -$divWrapper = range(1,120,2); -$counter = 0; -?> -ListSelection) : ?> -
- ListSelection as $ListSelection) : ?> -
-
- - -
-
- -
-
- - - -
-
-
- - -
-
- \ No newline at end of file diff --git a/admin/layouts/external_source/build_option_fullwidth.php b/admin/layouts/external_source/build_option_fullwidth.php index 85847056..9ea23b26 100644 --- a/admin/layouts/external_source/build_option_fullwidth.php +++ b/admin/layouts/external_source/build_option_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage build_option_fullwidth.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -44,7 +44,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'note_auto_externalsource' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/external_source/details_above.php b/admin/layouts/external_source/details_above.php index 324e42c9..4a5f0090 100644 --- a/admin/layouts/external_source/details_above.php +++ b/admin/layouts/external_source/details_above.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_above.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,21 +38,29 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'description', 'externalsources' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/external_source/details_fullwidth.php b/admin/layouts/external_source/details_fullwidth.php index 21c767bc..b5e3c8ff 100644 --- a/admin/layouts/external_source/details_fullwidth.php +++ b/admin/layouts/external_source/details_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_fullwidth.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -44,7 +44,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'apicronjob_note' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/external_source/details_left.php b/admin/layouts/external_source/details_left.php index f64196ba..5dca0563 100644 --- a/admin/layouts/external_source/details_left.php +++ b/admin/layouts/external_source/details_left.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_left.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -46,7 +46,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'dropboxoptions' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/external_source/details_right.php b/admin/layouts/external_source/details_right.php index dd57d52f..fe4270f8 100644 --- a/admin/layouts/external_source/details_right.php +++ b/admin/layouts/external_source/details_right.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_right.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -44,7 +44,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'filetypes' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/external_source/details_under.php b/admin/layouts/external_source/details_under.php index aaadd756..7edfc74c 100644 --- a/admin/layouts/external_source/details_under.php +++ b/admin/layouts/external_source/details_under.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_under.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,20 +38,28 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'not_required' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/external_source/publishing.php b/admin/layouts/external_source/publishing.php index 1c3304ab..1f0a760b 100644 --- a/admin/layouts/external_source/publishing.php +++ b/admin/layouts/external_source/publishing.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage publishing.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -46,7 +46,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'modified_by' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/external_source/publlshing.php b/admin/layouts/external_source/publlshing.php index 57b2f712..dc91145a 100644 --- a/admin/layouts/external_source/publlshing.php +++ b/admin/layouts/external_source/publlshing.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage publlshing.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -46,7 +46,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'id' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/help_document/details_above.php b/admin/layouts/help_document/details_above.php index 275a4093..50cf6add 100644 --- a/admin/layouts/help_document/details_above.php +++ b/admin/layouts/help_document/details_above.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_above.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,21 +38,29 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'title', 'alias' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/help_document/details_fullwidth.php b/admin/layouts/help_document/details_fullwidth.php index 030bf924..4fea7c09 100644 --- a/admin/layouts/help_document/details_fullwidth.php +++ b/admin/layouts/help_document/details_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_fullwidth.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'content' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/help_document/details_left.php b/admin/layouts/help_document/details_left.php index 95657c04..c583e690 100644 --- a/admin/layouts/help_document/details_left.php +++ b/admin/layouts/help_document/details_left.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_left.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -46,7 +46,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'site_view' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/help_document/details_right.php b/admin/layouts/help_document/details_right.php index 05a0d500..9f3b01e5 100644 --- a/admin/layouts/help_document/details_right.php +++ b/admin/layouts/help_document/details_right.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_right.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -44,7 +44,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'article' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/help_document/details_under.php b/admin/layouts/help_document/details_under.php index aaadd756..7edfc74c 100644 --- a/admin/layouts/help_document/details_under.php +++ b/admin/layouts/help_document/details_under.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_under.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,20 +38,28 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'not_required' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/help_document/metadata.php b/admin/layouts/help_document/metadata.php index cf54d36d..f16b6988 100644 --- a/admin/layouts/help_document/metadata.php +++ b/admin/layouts/help_document/metadata.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage metadata.php @@ -22,8 +22,10 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ +use Joomla\CMS\Language\Text; + // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; $form = $displayData->getForm(); @@ -33,7 +35,7 @@ $fieldSets = $form->getFieldsets('metadata'); $fieldSet) : ?> description) && trim($fieldSet->description)) : ?> -

escape(JText::_($fieldSet->description)); ?>

+

escape(Text::_($fieldSet->description)); ?>

getForm(); @@ -51,7 +51,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'id' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/local_listing/details_above.php b/admin/layouts/local_listing/details_above.php index 01c7bdc9..253bfe4a 100644 --- a/admin/layouts/local_listing/details_above.php +++ b/admin/layouts/local_listing/details_above.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_above.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,21 +38,29 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'name', 'size' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/local_listing/details_fullwidth.php b/admin/layouts/local_listing/details_fullwidth.php index ca312c37..61599614 100644 --- a/admin/layouts/local_listing/details_fullwidth.php +++ b/admin/layouts/local_listing/details_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_fullwidth.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -43,7 +43,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'url' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/local_listing/details_left.php b/admin/layouts/local_listing/details_left.php index 58b6da11..21da8d1d 100644 --- a/admin/layouts/local_listing/details_left.php +++ b/admin/layouts/local_listing/details_left.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_left.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'external_source' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/local_listing/details_right.php b/admin/layouts/local_listing/details_right.php index 33c7251b..8d00517c 100644 --- a/admin/layouts/local_listing/details_right.php +++ b/admin/layouts/local_listing/details_right.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_right.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'build' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/local_listing/publishing.php b/admin/layouts/local_listing/publishing.php index 1c3304ab..1f0a760b 100644 --- a/admin/layouts/local_listing/publishing.php +++ b/admin/layouts/local_listing/publishing.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage publishing.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -46,7 +46,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'modified_by' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/local_listing/publlshing.php b/admin/layouts/local_listing/publlshing.php index 57b2f712..dc91145a 100644 --- a/admin/layouts/local_listing/publlshing.php +++ b/admin/layouts/local_listing/publlshing.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage publlshing.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -46,7 +46,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'id' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/preacher/details_above.php b/admin/layouts/preacher/details_above.php index 5f52f0f5..269aa9ea 100644 --- a/admin/layouts/preacher/details_above.php +++ b/admin/layouts/preacher/details_above.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_above.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,21 +38,29 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'name', 'alias' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/preacher/details_fullwidth.php b/admin/layouts/preacher/details_fullwidth.php index 89384fca..e1db485e 100644 --- a/admin/layouts/preacher/details_fullwidth.php +++ b/admin/layouts/preacher/details_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_fullwidth.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'description' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/preacher/details_left.php b/admin/layouts/preacher/details_left.php index 8b81eb10..e19c99d9 100644 --- a/admin/layouts/preacher/details_left.php +++ b/admin/layouts/preacher/details_left.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_left.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'icon' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/preacher/details_right.php b/admin/layouts/preacher/details_right.php index ab2524e5..28fa87ba 100644 --- a/admin/layouts/preacher/details_right.php +++ b/admin/layouts/preacher/details_right.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_right.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -43,7 +43,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'website' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/preacher/metadata.php b/admin/layouts/preacher/metadata.php index cf54d36d..f16b6988 100644 --- a/admin/layouts/preacher/metadata.php +++ b/admin/layouts/preacher/metadata.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage metadata.php @@ -22,8 +22,10 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ +use Joomla\CMS\Language\Text; + // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; $form = $displayData->getForm(); @@ -33,7 +35,7 @@ $fieldSets = $form->getFieldsets('metadata'); $fieldSet) : ?> description) && trim($fieldSet->description)) : ?> -

escape(JText::_($fieldSet->description)); ?>

+

escape(Text::_($fieldSet->description)); ?>

getForm(); @@ -52,7 +52,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'id' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/preacher/sermons_fullwidth.php b/admin/layouts/preacher/sermons_fullwidth.php index 63a85b6f..331ea9f3 100644 --- a/admin/layouts/preacher/sermons_fullwidth.php +++ b/admin/layouts/preacher/sermons_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage sermons_fullwidth.php @@ -22,25 +22,32 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; +use VDM\Joomla\Utilities\ArrayHelper; + // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // set the defaults $items = $displayData->vvvsermons; -$user = JFactory::getUser(); +$user = Factory::getApplication()->getIdentity(); $id = $displayData->item->id; // set the edit URL $edit = "index.php?option=com_sermondistributor&view=sermons&task=sermon.edit"; // set a return value $return = ($id) ? "index.php?option=com_sermondistributor&view=preacher&layout=edit&id=" . $id : ""; // check for a return value -$jinput = JFactory::getApplication()->input; +$jinput = Factory::getApplication()->input; if ($_return = $jinput->get('return', null, 'base64')) { $return .= "&return=" . $_return; } // check if return value was set -if (SermondistributorHelper::checkString($return)) +if (StringHelper::check($return)) { // set the referral values $ref = ($id) ? "&ref=preacher&refid=" . $id . "&return=" . urlencode(base64_encode($return)) : "&return=" . urlencode(base64_encode($return)); @@ -60,40 +67,40 @@ $can = SermondistributorHelper::getActions('sermon');
get('sermon.create')): ?>
- - + +


- - + +
- - - - - - - - - @@ -101,7 +108,9 @@ $can = SermondistributorHelper::getActions('sermon'); $item): ?> authorise('core.manage', 'com_checkin') || $item->checked_out == $user->id || $item->checked_out == 0; - $userChkOut = JFactory::getUser($item->checked_out); + $userChkOut = Factory::getContainer()-> + get(\Joomla\CMS\User\UserFactoryInterface::class)-> + loadUserById($item->checked_out); $canDo = SermondistributorHelper::getActions('sermon',$item,'sermons'); ?> @@ -109,7 +118,7 @@ $can = SermondistributorHelper::getActions('sermon'); get('sermon.edit')): ?> escape($item->name); ?>checked_out): ?> - name, $item->checked_out_time, 'sermons.', $canCheckin); ?> + name, $item->checked_out_time, 'sermons.', $canCheckin); ?> escape($item->name); ?> @@ -136,33 +145,33 @@ $can = SermondistributorHelper::getActions('sermon'); published == 1): ?> - published == 0): ?> - published == 2): ?> - published == -2): ?> - @@ -172,17 +181,10 @@ $can = SermondistributorHelper::getActions('sermon'); - - - - -
- + + - + + - + + - + + - + + - + + - + + - + + - + +
- link_type); ?> + link_type); ?> - source); ?> + source); ?> - - + + + - - + + + - - + + + - - + + +
- -
- +
diff --git a/admin/layouts/series/details_above.php b/admin/layouts/series/details_above.php index 5f52f0f5..269aa9ea 100644 --- a/admin/layouts/series/details_above.php +++ b/admin/layouts/series/details_above.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_above.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,21 +38,29 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'name', 'alias' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/series/details_fullwidth.php b/admin/layouts/series/details_fullwidth.php index 89384fca..e1db485e 100644 --- a/admin/layouts/series/details_fullwidth.php +++ b/admin/layouts/series/details_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_fullwidth.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'description' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/series/details_left.php b/admin/layouts/series/details_left.php index 8b81eb10..e19c99d9 100644 --- a/admin/layouts/series/details_left.php +++ b/admin/layouts/series/details_left.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_left.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'icon' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/series/details_right.php b/admin/layouts/series/details_right.php index 549ad60b..fb29b096 100644 --- a/admin/layouts/series/details_right.php +++ b/admin/layouts/series/details_right.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_right.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'scripture' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/series/metadata.php b/admin/layouts/series/metadata.php index cf54d36d..f16b6988 100644 --- a/admin/layouts/series/metadata.php +++ b/admin/layouts/series/metadata.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage metadata.php @@ -22,8 +22,10 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ +use Joomla\CMS\Language\Text; + // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; $form = $displayData->getForm(); @@ -33,7 +35,7 @@ $fieldSets = $form->getFieldsets('metadata'); $fieldSet) : ?> description) && trim($fieldSet->description)) : ?> -

escape(JText::_($fieldSet->description)); ?>

+

escape(Text::_($fieldSet->description)); ?>

getForm(); @@ -52,7 +52,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'id' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/series/sermons_fullwidth.php b/admin/layouts/series/sermons_fullwidth.php index 93aa618c..52d61db9 100644 --- a/admin/layouts/series/sermons_fullwidth.php +++ b/admin/layouts/series/sermons_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage sermons_fullwidth.php @@ -22,25 +22,32 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; +use VDM\Joomla\Utilities\ArrayHelper; + // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // set the defaults $items = $displayData->vwcsermons; -$user = JFactory::getUser(); +$user = Factory::getApplication()->getIdentity(); $id = $displayData->item->id; // set the edit URL $edit = "index.php?option=com_sermondistributor&view=sermons&task=sermon.edit"; // set a return value $return = ($id) ? "index.php?option=com_sermondistributor&view=series&layout=edit&id=" . $id : ""; // check for a return value -$jinput = JFactory::getApplication()->input; +$jinput = Factory::getApplication()->input; if ($_return = $jinput->get('return', null, 'base64')) { $return .= "&return=" . $_return; } // check if return value was set -if (SermondistributorHelper::checkString($return)) +if (StringHelper::check($return)) { // set the referral values $ref = ($id) ? "&ref=series&refid=" . $id . "&return=" . urlencode(base64_encode($return)) : "&return=" . urlencode(base64_encode($return)); @@ -57,38 +64,38 @@ $can = SermondistributorHelper::getActions('sermon'); ?>
get('sermon.create')): ?> -

+

- - + +
- - - - - - - - - @@ -96,7 +103,9 @@ $can = SermondistributorHelper::getActions('sermon'); $item): ?> authorise('core.manage', 'com_checkin') || $item->checked_out == $user->id || $item->checked_out == 0; - $userChkOut = JFactory::getUser($item->checked_out); + $userChkOut = Factory::getContainer()-> + get(\Joomla\CMS\User\UserFactoryInterface::class)-> + loadUserById($item->checked_out); $canDo = SermondistributorHelper::getActions('sermon',$item,'sermons'); ?> @@ -104,7 +113,7 @@ $can = SermondistributorHelper::getActions('sermon'); get('sermon.edit')): ?> escape($item->name); ?>checked_out): ?> - name, $item->checked_out_time, 'sermons.', $canCheckin); ?> + name, $item->checked_out_time, 'sermons.', $canCheckin); ?> escape($item->name); ?> @@ -131,33 +140,33 @@ $can = SermondistributorHelper::getActions('sermon'); published == 1): ?> - published == 0): ?> - published == 2): ?> - published == -2): ?> - @@ -167,17 +176,10 @@ $can = SermondistributorHelper::getActions('sermon'); - - - - -
- + + - + + - + + - + + - + + - + + - + + - + + - + +
- link_type); ?> + link_type); ?> - source); ?> + source); ?> - - + + + - - + + + - - + + + - - + + +
- -
- +
diff --git a/admin/layouts/sermon/details_above.php b/admin/layouts/sermon/details_above.php index 6218a9d6..0be04615 100644 --- a/admin/layouts/sermon/details_above.php +++ b/admin/layouts/sermon/details_above.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_above.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,22 +38,30 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'name', 'alias', 'preacher' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/sermon/details_fullwidth.php b/admin/layouts/sermon/details_fullwidth.php index 89384fca..e1db485e 100644 --- a/admin/layouts/sermon/details_fullwidth.php +++ b/admin/layouts/sermon/details_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_fullwidth.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'description' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/sermon/details_left.php b/admin/layouts/sermon/details_left.php index 725eb983..651b470d 100644 --- a/admin/layouts/sermon/details_left.php +++ b/admin/layouts/sermon/details_left.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_left.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -44,7 +44,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'icon' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/sermon/details_right.php b/admin/layouts/sermon/details_right.php index 7968829d..5b13c0a1 100644 --- a/admin/layouts/sermon/details_right.php +++ b/admin/layouts/sermon/details_right.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_right.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -44,7 +44,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'tags' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/sermon/details_under.php b/admin/layouts/sermon/details_under.php index c365dc40..251b0ed6 100644 --- a/admin/layouts/sermon/details_under.php +++ b/admin/layouts/sermon/details_under.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_under.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,21 +38,29 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'not_required', 'auto_sermons' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/sermon/files_fullwidth.php b/admin/layouts/sermon/files_fullwidth.php index 11e49adb..ca40b006 100644 --- a/admin/layouts/sermon/files_fullwidth.php +++ b/admin/layouts/sermon/files_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage files_fullwidth.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -51,7 +51,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'url' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/sermon/metadata.php b/admin/layouts/sermon/metadata.php index cf54d36d..f16b6988 100644 --- a/admin/layouts/sermon/metadata.php +++ b/admin/layouts/sermon/metadata.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage metadata.php @@ -22,8 +22,10 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ +use Joomla\CMS\Language\Text; + // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; $form = $displayData->getForm(); @@ -33,7 +35,7 @@ $fieldSets = $form->getFieldsets('metadata'); $fieldSet) : ?> description) && trim($fieldSet->description)) : ?> -

escape(JText::_($fieldSet->description)); ?>

+

escape(Text::_($fieldSet->description)); ?>

getForm(); @@ -52,7 +52,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'id' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/sermon/stastics_fullwidth.php b/admin/layouts/sermon/stastics_fullwidth.php index db88f257..892ab210 100644 --- a/admin/layouts/sermon/stastics_fullwidth.php +++ b/admin/layouts/sermon/stastics_fullwidth.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage stastics_fullwidth.php @@ -22,25 +22,32 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; +use VDM\Joomla\Utilities\ArrayHelper; + // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // set the defaults $items = $displayData->vwbstastics; -$user = JFactory::getUser(); +$user = Factory::getApplication()->getIdentity(); $id = $displayData->item->id; // set the edit URL $edit = "index.php?option=com_sermondistributor&view=statistics&task=statistic.edit"; // set a return value $return = ($id) ? "index.php?option=com_sermondistributor&view=sermon&layout=edit&id=" . $id : ""; // check for a return value -$jinput = JFactory::getApplication()->input; +$jinput = Factory::getApplication()->input; if ($_return = $jinput->get('return', null, 'base64')) { $return .= "&return=" . $_return; } // check if return value was set -if (SermondistributorHelper::checkString($return)) +if (StringHelper::check($return)) { // set the referral values $ref = ($id) ? "&ref=sermon&refid=" . $id . "&return=" . urlencode(base64_encode($return)) : "&return=" . urlencode(base64_encode($return)); @@ -52,30 +59,30 @@ else ?>
- - + +
- - - - - - - @@ -83,7 +90,9 @@ else $item): ?> authorise('core.manage', 'com_checkin') || $item->checked_out == $user->id || $item->checked_out == 0; - $userChkOut = JFactory::getUser($item->checked_out); + $userChkOut = Factory::getContainer()-> + get(\Joomla\CMS\User\UserFactoryInterface::class)-> + loadUserById($item->checked_out); $canDo = SermondistributorHelper::getActions('statistic',$item,'statistics'); ?> @@ -91,7 +100,7 @@ else get('statistic.edit')): ?> filename; ?>checked_out): ?> - name, $item->checked_out_time, 'statistics.', $canCheckin); ?> + name, $item->checked_out_time, 'statistics.', $canCheckin); ?> filename; ?> @@ -118,27 +127,27 @@ else escape($item->counter); ?> published == 1): ?> - published == 0): ?> - published == 2): ?> - published == -2): ?> - @@ -148,17 +157,10 @@ else - - - - -
- + + - + + - + + - + + - + + - + + - + +
- - + + + - - + + + - - + + + - - + + +
- -
- +
diff --git a/admin/layouts/statistic/details_above.php b/admin/layouts/statistic/details_above.php index 942766bd..68a60bfe 100644 --- a/admin/layouts/statistic/details_above.php +++ b/admin/layouts/statistic/details_above.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_above.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -38,21 +38,29 @@ $layout_path_array = explode('.', $this->getLayoutId()); $fields_tab_layout = 'fields_' . $layout_path_array[1]; // get the fields -$fields = $displayData->get($fields_tab_layout) ?: array( +$fields = $displayData->get($fields_tab_layout) ?: [ 'filename', 'sermon' -); +]; -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +// Ensure $fields is treated as an array and count its size. +$size = count((array) $fields); + +// Use a ternary operator to determine the class. +// If there are 1 to 4 fields, set the class to divide the 12-grid column equally among the fields. +// For more than 4 fields, default to four columns (3-grid each) for medium and larger screens. +$css_class = ($size > 0 && $size <= 4) ? 'col-12 col-md-' . round(12 / $size) : 'col-12 col-md-3'; + +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> -
+
setFieldAttribute($field, 'type', 'hidden'); ?> - renderField($field, null, null, array('class' => 'control-wrapper-' . $field)); ?> + renderField($field, null, null, ['class' => $css_class . ' control-wrapper-' . $field]); ?>
diff --git a/admin/layouts/statistic/details_left.php b/admin/layouts/statistic/details_left.php index e81d61de..2974fa1e 100644 --- a/admin/layouts/statistic/details_left.php +++ b/admin/layouts/statistic/details_left.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_left.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -43,7 +43,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'series' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/statistic/details_right.php b/admin/layouts/statistic/details_right.php index 777c011a..260f5b0a 100644 --- a/admin/layouts/statistic/details_right.php +++ b/admin/layouts/statistic/details_right.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage details_right.php @@ -23,7 +23,7 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; // get the form $form = $displayData->getForm(); @@ -42,7 +42,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'counter' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/statistic/metadata.php b/admin/layouts/statistic/metadata.php index cf54d36d..f16b6988 100644 --- a/admin/layouts/statistic/metadata.php +++ b/admin/layouts/statistic/metadata.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage metadata.php @@ -22,8 +22,10 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ +use Joomla\CMS\Language\Text; + // No direct access to this file -defined('_JEXEC') or die('Restricted access'); +defined('_JEXEC') or die; $form = $displayData->getForm(); @@ -33,7 +35,7 @@ $fieldSets = $form->getFieldsets('metadata'); $fieldSet) : ?> description) && trim($fieldSet->description)) : ?> -

escape(JText::_($fieldSet->description)); ?>

+

escape(Text::_($fieldSet->description)); ?>

getForm(); @@ -52,7 +52,7 @@ $fields = $displayData->get($fields_tab_layout) ?: array( 'id' ); -$hiddenFields = $displayData->get('hidden_fields') ?: array(); +$hiddenFields = $displayData->get('hidden_fields') ?: []; ?> diff --git a/admin/layouts/trashhelper.php b/admin/layouts/trashhelper.php index 0f24f745..60bd91b5 100644 --- a/admin/layouts/trashhelper.php +++ b/admin/layouts/trashhelper.php @@ -10,7 +10,7 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage trashhelper.php @@ -22,8 +22,16 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ + + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\LayoutHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + // No direct access to this file -defined('JPATH_BASE') or die('Restricted access'); +defined('JPATH_BASE') or die; @@ -39,7 +47,7 @@ defined('JPATH_BASE') or die('Restricted access'); document.adminForm.elements['checkall-toggle'].checked=1; Joomla.checkAll(document.adminForm.elements['checkall-toggle']); // check to confirm the deletion - if(confirm('')) { + if(confirm('')) { Joomla.submitbutton('get("name") ?>.delete'); } else { document.adminForm.elements['checkall-toggle'].checked=0; @@ -47,7 +55,7 @@ defined('JPATH_BASE') or die('Restricted access'); } } else { // confirm deletion of those selected - if (confirm('')) { + if (confirm('')) { Joomla.submitbutton('get("name") ?>.delete'); }; } @@ -64,23 +72,23 @@ defined('JPATH_BASE') or die('Restricted access'); items)): ?>

- +

-

+

- +

-

+

diff --git a/admin/models/manual_updater.php b/admin/models/manual_updater.php deleted file mode 100644 index 7a184def..00000000 --- a/admin/models/manual_updater.php +++ /dev/null @@ -1,158 +0,0 @@ - - @copyright Copyright (C) 2015. All Rights Reserved - @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html - - A sermon distributor that links to Dropbox. - -/----------------------------------------------------------------------------------------------------------------------------------*/ - -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; - -/** - * Sermondistributor List Model for Manual_updater - */ -class SermondistributorModelManual_updater extends ListModel -{ - /** - * Model user data. - * - * @var strings - */ - protected $user; - protected $userId; - protected $guest; - protected $groups; - protected $levels; - protected $app; - protected $input; - protected $uikitComp; - - /** - * Method to build an SQL query to load the list data. - * - * @return string An SQL query - */ - protected function getListQuery() - { - // Get the current user for authorisation checks - $this->user = JFactory::getUser(); - $this->userId = $this->user->get('id'); - $this->guest = $this->user->get('guest'); - $this->groups = $this->user->get('groups'); - $this->authorisedGroups = $this->user->getAuthorisedGroups(); - $this->levels = $this->user->getAuthorisedViewLevels(); - $this->app = JFactory::getApplication(); - $this->input = $this->app->input; - $this->initSet = true; - // Make sure all records load, since no pagination allowed. - $this->setState('list.limit', 0); - // Get a db connection. - $db = JFactory::getDbo(); - - // Create a new query object. - $query = $db->getQuery(true); - - // Get from #__sermondistributor_external_source as a - $query->select($db->quoteName( - array('a.id','a.description','a.externalsources','a.build','a.update_method','a.update_timer','a.filetypes','a.oauthtoken','a.permissiontype','a.dropboxoptions','a.sharedurl','a.folder'), - array('id','description','externalsources','build','update_method','update_timer','filetypes','oauthtoken','permissiontype','dropboxoptions','sharedurl','folder'))); - $query->from($db->quoteName('#__sermondistributor_external_source', 'a')); - // Get where a.update_method is 1 - $query->where('a.update_method = 1'); - // Get where a.published is 1 - $query->where('a.published = 1'); - $query->order('a.description ASC'); - - // return the query object - return $query; - } - - /** - * Method to get an array of data items. - * - * @return mixed An array of data items on success, false on failure. - */ - public function getItems() - { - $user = JFactory::getUser(); - // check if this user has permission to access items - if (!$user->authorise('manual_updater.access', 'com_sermondistributor')) - { - $app = JFactory::getApplication(); - $app->enqueueMessage(JText::_('Not authorised!'), 'error'); - // redirect away if not a correct (TODO for now we go to default view) - $app->redirect('index.php?option=com_sermondistributor'); - return false; - } - // load parent items - $items = parent::getItems(); - - // Get the global params - $globalParams = JComponentHelper::getParams('com_sermondistributor', true); - - // Get the basic encryption. - $basickey = SermondistributorHelper::getCryptKey('basic'); - // Get the encryption object. - $basic = new FOFEncryptAes($basickey); - - // Insure all item fields are adapted where needed. - if (SermondistributorHelper::checkArray($items)) - { - foreach ($items as $nr => &$item) - { - // Always create a slug for sef URL's - $item->slug = (isset($item->alias) && isset($item->id)) ? $item->id.':'.$item->alias : $item->id; - // Check if we can decode filetypes - if (SermondistributorHelper::checkJson($item->filetypes)) - { - // Decode filetypes - $item->filetypes = json_decode($item->filetypes, true); - } - // Check if we can decode oauthtoken - if (!empty($item->oauthtoken) && $basickey && !is_numeric($item->oauthtoken) && $item->oauthtoken === base64_encode(base64_decode($item->oauthtoken, true))) - { - // Decode oauthtoken - $item->oauthtoken = rtrim($basic->decryptString($item->oauthtoken), "\0"); - } - } - } - - // return items - return $items; - } - - /** - * Get the uikit needed components - * - * @return mixed An array of objects on success. - * - */ - public function getUikitComp() - { - if (isset($this->uikitComp) && SermondistributorHelper::checkArray($this->uikitComp)) - { - return $this->uikitComp; - } - return false; - } -} diff --git a/admin/models/sermondistributor.php b/admin/models/sermondistributor.php deleted file mode 100644 index 6e1d10fb..00000000 --- a/admin/models/sermondistributor.php +++ /dev/null @@ -1,481 +0,0 @@ - - @copyright Copyright (C) 2015. All Rights Reserved - @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html - - A sermon distributor that links to Dropbox. - -/----------------------------------------------------------------------------------------------------------------------------------*/ - -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; - -/** - * Sermondistributor List Model - */ -class SermondistributorModelSermondistributor extends ListModel -{ - public function getIcons() - { - // load user for access menus - $user = JFactory::getUser(); - // reset icon array - $icons = array(); - // view groups array - $viewGroups = array( - 'main' => array('png.preacher.add', 'png.preachers', 'png.sermon.add', 'png.sermons', 'png.sermons.catid_qpo0O0oqp_com_sermondistributor_po0O0oq_sermon', 'png.series.add', 'png.series_list', 'png.statistics', 'png.external_source.add', 'png.external_sources', 'png.manual_updater', 'png.local_listings', 'png.help_documents') - ); - // view access array - $viewAccess = array( - 'manual_updater.access' => 'manual_updater.access', - 'manual_updater.submenu' => 'manual_updater.submenu', - 'manual_updater.dashboard_list' => 'manual_updater.dashboard_list', - 'preacher.create' => 'preacher.create', - 'preachers.access' => 'preacher.access', - 'preacher.access' => 'preacher.access', - 'preachers.submenu' => 'preacher.submenu', - 'preachers.dashboard_list' => 'preacher.dashboard_list', - 'preacher.dashboard_add' => 'preacher.dashboard_add', - 'sermon.create' => 'sermon.create', - 'sermons.access' => 'sermon.access', - 'sermon.access' => 'sermon.access', - 'sermons.submenu' => 'sermon.submenu', - 'sermons.dashboard_list' => 'sermon.dashboard_list', - 'sermon.dashboard_add' => 'sermon.dashboard_add', - 'series.create' => 'series.create', - 'series_list.access' => 'series.access', - 'series.access' => 'series.access', - 'series_list.submenu' => 'series.submenu', - 'series_list.dashboard_list' => 'series.dashboard_list', - 'series.dashboard_add' => 'series.dashboard_add', - 'statistic.create' => 'statistic.create', - 'statistics.access' => 'statistic.access', - 'statistic.access' => 'statistic.access', - 'statistics.submenu' => 'statistic.submenu', - 'statistics.dashboard_list' => 'statistic.dashboard_list', - 'external_source.create' => 'external_source.create', - 'external_sources.access' => 'external_source.access', - 'external_source.access' => 'external_source.access', - 'external_sources.submenu' => 'external_source.submenu', - 'external_sources.dashboard_list' => 'external_source.dashboard_list', - 'external_source.dashboard_add' => 'external_source.dashboard_add', - 'local_listing.create' => 'local_listing.create', - 'local_listings.access' => 'local_listing.access', - 'local_listing.access' => 'local_listing.access', - 'local_listings.submenu' => 'local_listing.submenu', - 'local_listings.dashboard_list' => 'local_listing.dashboard_list', - 'help_document.create' => 'help_document.create', - 'help_documents.access' => 'help_document.access', - 'help_document.access' => 'help_document.access', - 'help_documents.submenu' => 'help_document.submenu', - 'help_documents.dashboard_list' => 'help_document.dashboard_list'); - // loop over the $views - foreach($viewGroups as $group => $views) - { - $i = 0; - if (SermondistributorHelper::checkArray($views)) - { - foreach($views as $view) - { - $add = false; - // external views (links) - if (strpos($view,'||') !== false) - { - $dwd = explode('||', $view); - if (count($dwd) == 3) - { - list($type, $name, $url) = $dwd; - $viewName = $name; - $alt = $name; - $url = $url; - $image = $name . '.' . $type; - $name = 'COM_SERMONDISTRIBUTOR_DASHBOARD_' . SermondistributorHelper::safeString($name,'U'); - } - } - // internal views - elseif (strpos($view,'.') !== false) - { - $dwd = explode('.', $view); - if (count($dwd) == 3) - { - list($type, $name, $action) = $dwd; - } - elseif (count($dwd) == 2) - { - list($type, $name) = $dwd; - $action = false; - } - if ($action) - { - $viewName = $name; - switch($action) - { - case 'add': - $url = 'index.php?option=com_sermondistributor&view=' . $name . '&layout=edit'; - $image = $name . '_' . $action. '.' . $type; - $alt = $name . ' ' . $action; - $name = 'COM_SERMONDISTRIBUTOR_DASHBOARD_'.SermondistributorHelper::safeString($name,'U').'_ADD'; - $add = true; - break; - default: - // check for new convention (more stable) - if (strpos($action, '_qpo0O0oqp_') !== false) - { - list($action, $extension) = (array) explode('_qpo0O0oqp_', $action); - $extension = str_replace('_po0O0oq_', '.', $extension); - } - else - { - $extension = 'com_sermondistributor.' . $name; - } - $url = 'index.php?option=com_categories&view=categories&extension=' . $extension; - $image = $name . '_' . $action . '.' . $type; - $alt = $viewName . ' ' . $action; - $name = 'COM_SERMONDISTRIBUTOR_DASHBOARD_' . SermondistributorHelper::safeString($name,'U') . '_' . SermondistributorHelper::safeString($action,'U'); - break; - } - } - else - { - $viewName = $name; - $alt = $name; - $url = 'index.php?option=com_sermondistributor&view=' . $name; - $image = $name . '.' . $type; - $name = 'COM_SERMONDISTRIBUTOR_DASHBOARD_' . SermondistributorHelper::safeString($name,'U'); - $hover = false; - } - } - else - { - $viewName = $view; - $alt = $view; - $url = 'index.php?option=com_sermondistributor&view=' . $view; - $image = $view . '.png'; - $name = ucwords($view).'

'; - $hover = false; - } - // first make sure the view access is set - if (SermondistributorHelper::checkArray($viewAccess)) - { - // setup some defaults - $dashboard_add = false; - $dashboard_list = false; - $accessTo = ''; - $accessAdd = ''; - // access checking start - $accessCreate = (isset($viewAccess[$viewName.'.create'])) ? SermondistributorHelper::checkString($viewAccess[$viewName.'.create']):false; - $accessAccess = (isset($viewAccess[$viewName.'.access'])) ? SermondistributorHelper::checkString($viewAccess[$viewName.'.access']):false; - // set main controllers - $accessDashboard_add = (isset($viewAccess[$viewName.'.dashboard_add'])) ? SermondistributorHelper::checkString($viewAccess[$viewName.'.dashboard_add']):false; - $accessDashboard_list = (isset($viewAccess[$viewName.'.dashboard_list'])) ? SermondistributorHelper::checkString($viewAccess[$viewName.'.dashboard_list']):false; - // check for adding access - if ($add && $accessCreate) - { - $accessAdd = $viewAccess[$viewName.'.create']; - } - elseif ($add) - { - $accessAdd = 'core.create'; - } - // check if access to view is set - if ($accessAccess) - { - $accessTo = $viewAccess[$viewName.'.access']; - } - // set main access controllers - if ($accessDashboard_add) - { - $dashboard_add = $user->authorise($viewAccess[$viewName.'.dashboard_add'], 'com_sermondistributor'); - } - if ($accessDashboard_list) - { - $dashboard_list = $user->authorise($viewAccess[$viewName.'.dashboard_list'], 'com_sermondistributor'); - } - if (SermondistributorHelper::checkString($accessAdd) && SermondistributorHelper::checkString($accessTo)) - { - // check access - if($user->authorise($accessAdd, 'com_sermondistributor') && $user->authorise($accessTo, 'com_sermondistributor') && $dashboard_add) - { - $icons[$group][$i] = new StdClass; - $icons[$group][$i]->url = $url; - $icons[$group][$i]->name = $name; - $icons[$group][$i]->image = $image; - $icons[$group][$i]->alt = $alt; - } - } - elseif (SermondistributorHelper::checkString($accessTo)) - { - // check access - if($user->authorise($accessTo, 'com_sermondistributor') && $dashboard_list) - { - $icons[$group][$i] = new StdClass; - $icons[$group][$i]->url = $url; - $icons[$group][$i]->name = $name; - $icons[$group][$i]->image = $image; - $icons[$group][$i]->alt = $alt; - } - } - elseif (SermondistributorHelper::checkString($accessAdd)) - { - // check access - if($user->authorise($accessAdd, 'com_sermondistributor') && $dashboard_add) - { - $icons[$group][$i] = new StdClass; - $icons[$group][$i]->url = $url; - $icons[$group][$i]->name = $name; - $icons[$group][$i]->image = $image; - $icons[$group][$i]->alt = $alt; - } - } - else - { - $icons[$group][$i] = new StdClass; - $icons[$group][$i]->url = $url; - $icons[$group][$i]->name = $name; - $icons[$group][$i]->image = $image; - $icons[$group][$i]->alt = $alt; - } - } - else - { - $icons[$group][$i] = new StdClass; - $icons[$group][$i]->url = $url; - $icons[$group][$i]->name = $name; - $icons[$group][$i]->image = $image; - $icons[$group][$i]->alt = $alt; - } - $i++; - } - } - else - { - $icons[$group][$i] = false; - } - } - return $icons; - } - - - public function getGithub() - { - // load jquery (not sure why... but else the timeago breaks) - JHtml::_('jquery.framework'); - // get the document to load the scripts - $document = JFactory::getDocument(); - $document->addScript(JURI::root() . "media/com_sermondistributor/js/timeago.js"); - $document->addScriptDeclaration(' - var urlToGetAllOpenIssues = "https://api.github.com/repos/Llewellynvdm/Joomla-Sermon-Distributor/issues?state=open&page=1&per_page=5"; - var urlToGetAllClosedIssues = "https://api.github.com/repos/Llewellynvdm/Joomla-Sermon-Distributor/issues?state=closed&page=1&per_page=5"; - var urlToGetAllReleases = "https://api.github.com/repos/Llewellynvdm/Joomla-Sermon-Distributor/releases?page=1&per_page=5"; - jQuery(document).ready(function () { - jQuery.getJSON(urlToGetAllOpenIssues, function (openissues) { - jQuery("#openissues").html(""); - jQuery.each(openissues, function (i, issue) { - // set time ago - var timeago = jQuery.timeago(new Date(issue.created_at)); - jQuery("#openissues") - .append("

" + issue.title + "

") - .append("\"@" ") - .append("" + issue.user.login + " '.JText::_('COM_SERMONDISTRIBUTOR_OPENED_THIS').' '.JText::_('COM_SERMONDISTRIBUTOR_ISSUE').'-" + issue.number + " (" + timeago + ") ") - .append(marked.parse(issue.body)) - .append("'.JText::_('COM_SERMONDISTRIBUTOR_RESPOND_TO_THIS_ISSUE_ON_GITHUB').'...
"); - }); - }); - jQuery.getJSON(urlToGetAllClosedIssues, function (closedissues) { - jQuery("#closedissues").html(""); - jQuery.each(closedissues, function (i, issue) { - // set time ago - var timeago = jQuery.timeago(new Date(issue.created_at)); - jQuery("#closedissues") - .append("

" + issue.title + "

") - .append("\"@" ") - .append("" + issue.user.login + " '.JText::_('COM_SERMONDISTRIBUTOR_OPENED').' '.JText::_('COM_SERMONDISTRIBUTOR_ISSUE').'-" + issue.number + " (" + timeago + ")") - .append(marked.parse(issue.body)) - .append("'.JText::_('COM_SERMONDISTRIBUTOR_REVIEW_THIS_ISSUE_ON_GITHUB').'...
"); - }); - }); - jQuery.getJSON(urlToGetAllReleases, function (tagreleases) { - // set the update notice while we are at it - var activeVersion = tagreleases[0].tag_name.substring(1); - if (activeVersion === manifest.version) { - // local version is in sync with latest release - jQuery(".update-notice").html("'.JText::_('COM_SERMONDISTRIBUTOR_UP_TO_DATE').'"); - } else { - // split versions in to array - var activeVersionArray = activeVersion.split("."); - var localVersionArray = manifest.version.split("."); - if ((+localVersionArray[0] > +activeVersionArray[0]) || - (+localVersionArray[0] == +activeVersionArray[0] && +localVersionArray[1] > +activeVersionArray[1]) || - (+localVersionArray[0] == +activeVersionArray[0] && +localVersionArray[1] == +activeVersionArray[1] && +localVersionArray[2] > +activeVersionArray[2])) { - // local version head latest release - jQuery(".update-notice").html("'.JText::_('COM_SERMONDISTRIBUTOR_BETA_RELEASE').'"); - } else { - // local version behind latest release - jQuery(".update-notice").html("'.JText::_('COM_SERMONDISTRIBUTOR_OUT_OF_DATE').'"); - } - } - // set the taged releases - jQuery("#tagreleases").html(""); - jQuery.each(tagreleases, function (i, tagrelease) { - // set active release - var activeNotice = ""; - if (i === 0) { - var activeNotice = " '.JText::_('COM_SERMONDISTRIBUTOR_LATEST_RELEASE').'

"; - } - // set time ago - var timeago = jQuery.timeago(new Date(tagrelease.published_at)); - jQuery("#tagreleases") - .append("

" + tagrelease.name + "

") - .append(activeNotice) - .append("\"@" ") - .append("" + tagrelease.author.login + " '.JText::_('COM_SERMONDISTRIBUTOR_RELEASED_THIS').' " + tagrelease.tag_name+ " (" + timeago + ")") - .append(marked.parse(tagrelease.body)) - .append(" " + tagrelease.assets[0].name + " (" + tagrelease.assets[0].download_count + ") ") - .append("| '.JText::_('COM_SERMONDISTRIBUTOR_OPEN_ON_GITHUB').'...
"); - }); - }); - });'); - $create = '
'; - $moreopen = ''.JText::_('COM_SERMONDISTRIBUTOR_VIEW_MORE_ISSUES_ON_GITHUB').'... '; - $moreclosed = ''.JText::_('COM_SERMONDISTRIBUTOR_VIEW_MORE_ISSUES_ON_GITHUB').'... '; - $viewissues = ''.JText::_('COM_SERMONDISTRIBUTOR_VIEW_MORE_RELEASES_ON_GITHUB').'... '; - - return (object) array( - 'openissues' => $create.'
'.JText::_('COM_SERMONDISTRIBUTOR_A_FEW_OPEN_ISSUES_FROM_GITHUB_IS_LOADING').'..
'.$moreopen, - 'closedissues' => $create.'
'.JText::_('COM_SERMONDISTRIBUTOR_A_FEW_CLOSED_ISSUES_FROM_GITHUB_IS_LOADING').'..
'.$moreclosed, - 'tagreleases' => '
'.JText::_('COM_SERMONDISTRIBUTOR_LAST_FEW_RELEASES_FROM_GITHUB_IS_LOADING').'..
'.$viewissues - ); - } - - public function getWiki() - { - $document = JFactory::getDocument(); - $document->addScriptDeclaration(' - var gewiki = "https://raw.githubusercontent.com/wiki/Llewellynvdm/Joomla-Sermon-Distributor/Home.md"; - jQuery(document).ready(function () { - jQuery.get(gewiki) - .success(function(wiki) { - jQuery("#wiki-md").html(marked.parse(wiki)); - }) - .error(function(jqXHR, textStatus, errorThrown) { - jQuery("#wiki-md").html("'.JText::_('COM_SERMONDISTRIBUTOR_PLEASE_CHECK_AGAIN_LATTER').'"); - }); - });'); - - return '
'.JText::_('COM_SERMONDISTRIBUTOR_THE_WIKI_IS_LOADING').'..
'; - } - - - - public function getNoticeboard() - { - // get the document to load the scripts - $document = JFactory::getDocument(); - $document->addScript(JURI::root() . "media/com_sermondistributor/js/marked.js"); - $document->addScriptDeclaration(' - var token = "'.JSession::getFormToken().'"; - var noticeboard = "https://vdm.bz/sermondistributor-noticeboard-md"; - jQuery(document).ready(function () { - jQuery.get(noticeboard) - .success(function(board) { - if (board.length > 5) { - jQuery("#noticeboard-md").html(marked.parse(board)); - getIS(1,board).done(function(result) { - if (result){ - jQuery("#cpanel_tabTabs a").each(function() { - if (this.href.indexOf("#vast_development_method") >= 0 || this.href.indexOf("#notice_board") >= 0) { - var textVDM = jQuery(this).text(); - jQuery(this).html("1 "+textVDM); - jQuery(this).attr("id","vdm-new-notice"); - jQuery("#vdm-new-notice").click(function() { - getIS(2,board).done(function(result) { - if (result) { - jQuery(".vdm-new-notice").fadeOut(500); - } - }); - }); - } - }); - } - }); - } else { - jQuery("#noticeboard-md").html("'.JText::_('COM_SERMONDISTRIBUTOR_ALL_IS_GOOD_PLEASE_CHECK_AGAIN_LATTER').'"); - } - }) - .error(function(jqXHR, textStatus, errorThrown) { - jQuery("#noticeboard-md").html("'.JText::_('COM_SERMONDISTRIBUTOR_ALL_IS_GOOD_PLEASE_CHECK_AGAIN_LATTER').'"); - }); - }); - // to check is READ/NEW - function getIS(type,notice){ - if(type == 1){ - var getUrl = "index.php?option=com_sermondistributor&task=ajax.isNew&format=json&raw=true"; - } else if (type == 2) { - var getUrl = "index.php?option=com_sermondistributor&task=ajax.isRead&format=json&raw=true"; - } - if(token.length > 0 && notice.length){ - var request = token+"=1¬ice="+notice; - } - return jQuery.ajax({ - type: "POST", - url: getUrl, - dataType: "json", - data: request, - jsonp: false - }); - } - -// nice little dot trick :) -jQuery(document).ready( function($) { - var x=0; - setInterval(function() { - var dots = ""; - x++; - for (var y=0; y < x%8; y++) { - dots+="."; - } - $(".loading-dots").text(dots); - } , 500); -});'); - - return '
'.JText::_('COM_SERMONDISTRIBUTOR_THE_NOTICE_BOARD_IS_LOADING').'..
'; - } - - public function getReadme() - { - $document = JFactory::getDocument(); - $document->addScriptDeclaration(' - var getreadme = "'. JURI::root() . 'administrator/components/com_sermondistributor/README.txt"; - jQuery(document).ready(function () { - jQuery.get(getreadme) - .success(function(readme) { - jQuery("#readme-md").html(marked.parse(readme)); - }) - .error(function(jqXHR, textStatus, errorThrown) { - jQuery("#readme-md").html("'.JText::_('COM_SERMONDISTRIBUTOR_PLEASE_CHECK_AGAIN_LATTER').'"); - }); - });'); - - return '
'.JText::_('COM_SERMONDISTRIBUTOR_THE_README_IS_LOADING').'..
'; - } -} diff --git a/admin/helpers/html/index.html b/admin/presets/index.html similarity index 100% rename from admin/helpers/html/index.html rename to admin/presets/index.html diff --git a/admin/sermondistributor.php b/admin/sermondistributor.php deleted file mode 100644 index f6824c5c..00000000 --- a/admin/sermondistributor.php +++ /dev/null @@ -1,52 +0,0 @@ - - @copyright Copyright (C) 2015. All Rights Reserved - @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html - - A sermon distributor that links to Dropbox. - -/----------------------------------------------------------------------------------------------------------------------------------*/ - -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - - - -// Access check. -if (!JFactory::getUser()->authorise('core.manage', 'com_sermondistributor')) -{ - throw new JAccessExceptionNotallowed(JText::_('JERROR_ALERTNOAUTHOR'), 403); -}; - -// Add CSS file for all pages -$document = JFactory::getDocument(); -$document->addStyleSheet('components/com_sermondistributor/assets/css/admin.css'); -$document->addScript('components/com_sermondistributor/assets/js/admin.js'); - -// require helper files -JLoader::register('SermondistributorHelper', __DIR__ . '/helpers/sermondistributor.php'); -JLoader::register('JHtmlBatch_', __DIR__ . '/helpers/html/batch_.php'); - -// Get an instance of the controller prefixed by Sermondistributor -$controller = JControllerLegacy::getInstance('Sermondistributor'); - -// Perform the Request task -$controller->execute(JFactory::getApplication()->input->get('task')); - -// Redirect if set by the controller -$controller->redirect(); diff --git a/admin/helpers/index.html b/admin/services/index.html similarity index 100% rename from admin/helpers/index.html rename to admin/services/index.html diff --git a/admin/services/provider.php b/admin/services/provider.php new file mode 100644 index 00000000..eb26cdbe --- /dev/null +++ b/admin/services/provider.php @@ -0,0 +1,130 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ + + + +// register additional namespace +\spl_autoload_register(function ($class) { + // project-specific base directories and namespace prefix + $search = [ + 'libraries/jcb_powers/VDM.Joomla.FOF' => 'VDM\\Joomla\\FOF', + 'libraries/jcb_powers/VDM.Joomla' => 'VDM\\Joomla' + ]; + // Start the search and load if found + $found = false; + $found_base_dir = ""; + $found_len = 0; + foreach ($search as $base_dir => $prefix) + { + // does the class use the namespace prefix? + $len = strlen($prefix); + if (strncmp($prefix, $class, $len) === 0) + { + // we have a match so load the values + $found = true; + $found_base_dir = $base_dir; + $found_len = $len; + // done here + break; + } + } + // check if we found a match + if (!$found) + { + // not found so move to the next registered autoloader + return; + } + // get the relative class name + $relative_class = substr($class, $found_len); + // replace the namespace prefix with the base directory, replace namespace + // separators with directory separators in the relative class name, append + // with .php + $file = JPATH_ROOT . '/' . $found_base_dir . '/src' . str_replace('\\', '/', $relative_class) . '.php'; + // if the file exists, require it + if (file_exists($file)) + { + require $file; + } +}); + +// (soon) use Joomla\CMS\Association\AssociationExtensionInterface; +use Joomla\CMS\Categories\CategoryFactoryInterface; +use Joomla\CMS\Component\Router\RouterFactoryInterface; +use Joomla\CMS\Dispatcher\ComponentDispatcherFactoryInterface; +use Joomla\CMS\Extension\ComponentInterface; +use Joomla\CMS\Extension\Service\Provider\CategoryFactory; +use Joomla\CMS\Extension\Service\Provider\ComponentDispatcherFactory; +use Joomla\CMS\Extension\Service\Provider\MVCFactory; +use Joomla\CMS\Extension\Service\Provider\RouterFactory; +use Joomla\CMS\HTML\Registry; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Extension\SermondistributorComponent; +// (soon) use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\AssociationsHelper; +use Joomla\DI\Container; +use Joomla\DI\ServiceProviderInterface; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * The TrueChristianChurch Sermondistributor service provider. + * + * @since 4.0.0 + */ +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) + { + // (soon) $container->set(AssociationExtensionInterface::class, new AssociationsHelper()); + + $container->registerServiceProvider(new CategoryFactory('\\TrueChristianChurch\\Component\\Sermondistributor')); + $container->registerServiceProvider(new MVCFactory('\\TrueChristianChurch\\Component\\Sermondistributor')); + $container->registerServiceProvider(new ComponentDispatcherFactory('\\TrueChristianChurch\\Component\\Sermondistributor')); + $container->registerServiceProvider(new RouterFactory('\\TrueChristianChurch\\Component\\Sermondistributor')); + + $container->set( + ComponentInterface::class, + function (Container $container) { + $component = new SermondistributorComponent($container->get(ComponentDispatcherFactoryInterface::class)); + + $component->setRegistry($container->get(Registry::class)); + $component->setMVCFactory($container->get(MVCFactoryInterface::class)); + $component->setCategoryFactory($container->get(CategoryFactoryInterface::class)); + // (soon) $component->setAssociationExtension($container->get(AssociationExtensionInterface::class)); + $component->setRouterFactory($container->get(RouterFactoryInterface::class)); + + return $component; + } + ); + } +}; diff --git a/admin/sql/install.mysql.utf8.sql b/admin/sql/install.mysql.utf8.sql index f4067122..f1dd79f7 100644 --- a/admin/sql/install.mysql.utf8.sql +++ b/admin/sql/install.mysql.utf8.sql @@ -1,3 +1,6 @@ +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +SET time_zone = "+00:00"; + CREATE TABLE IF NOT EXISTS `#__sermondistributor_preacher` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `asset_id` INT(10) unsigned NOT NULL DEFAULT 0 COMMENT 'FK to the #__assets table.', @@ -11,15 +14,15 @@ CREATE TABLE IF NOT EXISTS `#__sermondistributor_preacher` ( `published` TINYINT(3) NOT NULL DEFAULT 1, `created_by` INT(10) unsigned NOT NULL DEFAULT 0, `modified_by` INT(10) unsigned NOT NULL DEFAULT 0, - `created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `created` DATETIME DEFAULT CURRENT_TIMESTAMP, + `modified` DATETIME DEFAULT NULL, `checked_out` int(11) unsigned NOT NULL DEFAULT 0, - `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `checked_out_time` DATETIME DEFAULT NULL, `version` INT(10) unsigned NOT NULL DEFAULT 1, `hits` INT(10) unsigned NOT NULL DEFAULT 0, `access` INT(10) unsigned NOT NULL DEFAULT 0, `ordering` INT(11) NOT NULL DEFAULT 0, - `metakey` TEXT NOT NULL, + `metakey` TEXT, `metadesc` TEXT NOT NULL, `metadata` TEXT NOT NULL, PRIMARY KEY (`id`), @@ -50,21 +53,21 @@ CREATE TABLE IF NOT EXISTS `#__sermondistributor_sermon` ( `series` INT(11) NOT NULL DEFAULT 0, `short_description` VARCHAR(255) NOT NULL DEFAULT '', `source` TINYINT(1) NOT NULL DEFAULT 0, - `tags` TEXT NOT NULL, + `tags` CHAR(11) NOT NULL DEFAULT 0, `url` VARCHAR(255) NOT NULL DEFAULT '', `params` text NULL, `published` TINYINT(3) NOT NULL DEFAULT 1, `created_by` INT(10) unsigned NOT NULL DEFAULT 0, `modified_by` INT(10) unsigned NOT NULL DEFAULT 0, - `created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `created` DATETIME DEFAULT CURRENT_TIMESTAMP, + `modified` DATETIME DEFAULT NULL, `checked_out` int(11) unsigned NOT NULL DEFAULT 0, - `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `checked_out_time` DATETIME DEFAULT NULL, `version` INT(10) unsigned NOT NULL DEFAULT 1, `hits` INT(10) unsigned NOT NULL DEFAULT 0, `access` INT(10) unsigned NOT NULL DEFAULT 0, `ordering` INT(11) NOT NULL DEFAULT 0, - `metakey` TEXT NOT NULL, + `metakey` TEXT, `metadesc` TEXT NOT NULL, `metadata` TEXT NOT NULL, PRIMARY KEY (`id`), @@ -94,15 +97,15 @@ CREATE TABLE IF NOT EXISTS `#__sermondistributor_series` ( `published` TINYINT(3) NOT NULL DEFAULT 1, `created_by` INT(10) unsigned NOT NULL DEFAULT 0, `modified_by` INT(10) unsigned NOT NULL DEFAULT 0, - `created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `created` DATETIME DEFAULT CURRENT_TIMESTAMP, + `modified` DATETIME DEFAULT NULL, `checked_out` int(11) unsigned NOT NULL DEFAULT 0, - `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `checked_out_time` DATETIME DEFAULT NULL, `version` INT(10) unsigned NOT NULL DEFAULT 1, `hits` INT(10) unsigned NOT NULL DEFAULT 0, `access` INT(10) unsigned NOT NULL DEFAULT 0, `ordering` INT(11) NOT NULL DEFAULT 0, - `metakey` TEXT NOT NULL, + `metakey` TEXT, `metadesc` TEXT NOT NULL, `metadata` TEXT NOT NULL, PRIMARY KEY (`id`), @@ -127,15 +130,15 @@ CREATE TABLE IF NOT EXISTS `#__sermondistributor_statistic` ( `published` TINYINT(3) NOT NULL DEFAULT 1, `created_by` INT(10) unsigned NOT NULL DEFAULT 0, `modified_by` INT(10) unsigned NOT NULL DEFAULT 0, - `created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `created` DATETIME DEFAULT CURRENT_TIMESTAMP, + `modified` DATETIME DEFAULT NULL, `checked_out` int(11) unsigned NOT NULL DEFAULT 0, - `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `checked_out_time` DATETIME DEFAULT NULL, `version` INT(10) unsigned NOT NULL DEFAULT 1, `hits` INT(10) unsigned NOT NULL DEFAULT 0, `access` INT(10) unsigned NOT NULL DEFAULT 0, `ordering` INT(11) NOT NULL DEFAULT 0, - `metakey` TEXT NOT NULL, + `metakey` TEXT, `metadesc` TEXT NOT NULL, `metadata` TEXT NOT NULL, PRIMARY KEY (`id`), @@ -169,10 +172,10 @@ CREATE TABLE IF NOT EXISTS `#__sermondistributor_external_source` ( `published` TINYINT(3) NOT NULL DEFAULT 1, `created_by` INT(10) unsigned NOT NULL DEFAULT 0, `modified_by` INT(10) unsigned NOT NULL DEFAULT 0, - `created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `created` DATETIME DEFAULT CURRENT_TIMESTAMP, + `modified` DATETIME DEFAULT NULL, `checked_out` int(11) unsigned NOT NULL DEFAULT 0, - `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `checked_out_time` DATETIME DEFAULT NULL, `version` INT(10) unsigned NOT NULL DEFAULT 1, `hits` INT(10) unsigned NOT NULL DEFAULT 0, `ordering` INT(11) NOT NULL DEFAULT 0, @@ -202,10 +205,10 @@ CREATE TABLE IF NOT EXISTS `#__sermondistributor_local_listing` ( `published` TINYINT(3) NOT NULL DEFAULT 1, `created_by` INT(10) unsigned NOT NULL DEFAULT 0, `modified_by` INT(10) unsigned NOT NULL DEFAULT 0, - `created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `created` DATETIME DEFAULT CURRENT_TIMESTAMP, + `modified` DATETIME DEFAULT NULL, `checked_out` int(11) unsigned NOT NULL DEFAULT 0, - `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `checked_out_time` DATETIME DEFAULT NULL, `version` INT(10) unsigned NOT NULL DEFAULT 1, `hits` INT(10) unsigned NOT NULL DEFAULT 0, `ordering` INT(11) NOT NULL DEFAULT 0, @@ -237,15 +240,15 @@ CREATE TABLE IF NOT EXISTS `#__sermondistributor_help_document` ( `published` TINYINT(3) NOT NULL DEFAULT 1, `created_by` INT(10) unsigned NOT NULL DEFAULT 0, `modified_by` INT(10) unsigned NOT NULL DEFAULT 0, - `created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `created` DATETIME DEFAULT CURRENT_TIMESTAMP, + `modified` DATETIME DEFAULT NULL, `checked_out` int(11) unsigned NOT NULL DEFAULT 0, - `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `checked_out_time` DATETIME DEFAULT NULL, `version` INT(10) unsigned NOT NULL DEFAULT 1, `hits` INT(10) unsigned NOT NULL DEFAULT 0, `access` INT(10) unsigned NOT NULL DEFAULT 0, `ordering` INT(11) NOT NULL DEFAULT 0, - `metakey` TEXT NOT NULL, + `metakey` TEXT, `metadesc` TEXT NOT NULL, `metadata` TEXT NOT NULL, PRIMARY KEY (`id`), diff --git a/admin/sql/updates/mysql/1.3.8.sql b/admin/sql/updates/mysql/1.3.8.sql deleted file mode 100644 index 25659445..00000000 --- a/admin/sql/updates/mysql/1.3.8.sql +++ /dev/null @@ -1,68 +0,0 @@ -CREATE TABLE IF NOT EXISTS `#__sermondistributor_external_source` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `asset_id` INT(255) UNSIGNED NOT NULL DEFAULT '0', - `build` TINYINT(1) NOT NULL DEFAULT '0', - `description` VARCHAR(255) NOT NULL DEFAULT '', - `dropboxoptions` TINYINT(1) NOT NULL DEFAULT '1', - `externalsources` INT(11) NOT NULL DEFAULT '0', - `filetypes` TEXT NOT NULL, - `folder` TEXT NOT NULL, - `not_required` INT(1) NOT NULL DEFAULT '0', - `oauthtoken` TEXT NOT NULL, - `permissiontype` VARCHAR(64) NOT NULL DEFAULT '', - `sharedurl` TEXT NOT NULL, - `update_method` TINYINT NOT NULL DEFAULT '0', - `update_timer` INT(1) NOT NULL DEFAULT '0', - `params` TEXT NOT NULL, - `published` tinyint(1) NOT NULL DEFAULT '1', - `created_by` int(11) NOT NULL DEFAULT '0', - `modified_by` int(11) NOT NULL DEFAULT '0', - `created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `checked_out` int(11) NOT NULL, - `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `version` int(11) NOT NULL DEFAULT '1', - `hits` int(11) NOT NULL DEFAULT '0', - `ordering` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `idx_checkout` (`checked_out`), - KEY `idx_createdby` (`created_by`), - KEY `idx_modifiedby` (`modified_by`), - KEY `idx_state` (`published`), - KEY `idx_description` (`description`), - KEY `idx_externalsources` (`externalsources`), - KEY `idx_update_method` (`update_method`), - KEY `idx_build` (`build`), - KEY `idx_dropboxoptions` (`dropboxoptions`), - KEY `idx_permissiontype` (`permissiontype`) -) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; - -CREATE TABLE IF NOT EXISTS `#__sermondistributor_local_listing` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `asset_id` INT(255) UNSIGNED NOT NULL DEFAULT '0', - `build` TINYINT(1) NOT NULL DEFAULT '0', - `external_source` int(11) NOT NULL DEFAULT '0', - `key` VARCHAR(255) NOT NULL DEFAULT '', - `name` VARCHAR(255) NOT NULL DEFAULT '', - `size` INT(50) NOT NULL DEFAULT '0', - `url` TEXT NOT NULL, - `params` TEXT NOT NULL, - `published` tinyint(1) NOT NULL DEFAULT '1', - `created_by` int(11) NOT NULL DEFAULT '0', - `modified_by` int(11) NOT NULL DEFAULT '0', - `created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `checked_out` int(11) NOT NULL, - `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `version` int(11) NOT NULL DEFAULT '1', - `hits` int(11) NOT NULL DEFAULT '0', - `ordering` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `idx_checkout` (`checked_out`), - KEY `idx_createdby` (`created_by`), - KEY `idx_modifiedby` (`modified_by`), - KEY `idx_state` (`published`), - KEY `idx_name` (`name`), - KEY `idx_build` (`build`), - KEY `idx_key` (`key`) -) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; diff --git a/admin/sql/updates/mysql/2.0.3.sql b/admin/sql/updates/mysql/2.0.3.sql deleted file mode 100644 index 939ba272..00000000 --- a/admin/sql/updates/mysql/2.0.3.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE `#__sermondistributor_sermon` ENGINE = InnoDB; - -ALTER TABLE `#__sermondistributor_sermon` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; diff --git a/admin/sql/updates/mysql/2.1.0.sql b/admin/sql/updates/mysql/2.1.0.sql deleted file mode 100644 index 9470d3da..00000000 --- a/admin/sql/updates/mysql/2.1.0.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE `#__sermondistributor_external_source` ENGINE = InnoDB; - -ALTER TABLE `#__sermondistributor_external_source` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; diff --git a/admin/sql/updates/mysql/1.0.0.sql b/admin/sql/updates/mysql/3.0.2.sql similarity index 100% rename from admin/sql/updates/mysql/1.0.0.sql rename to admin/sql/updates/mysql/3.0.2.sql diff --git a/admin/sql/updates/mysql/3.0.3.sql b/admin/sql/updates/mysql/3.0.3.sql new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/admin/sql/updates/mysql/3.0.3.sql @@ -0,0 +1 @@ + diff --git a/admin/sql/updates/mysql/5.0.01.sql b/admin/sql/updates/mysql/5.0.01.sql new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/admin/sql/updates/mysql/5.0.01.sql @@ -0,0 +1 @@ + diff --git a/admin/layouts/index.html b/admin/sql/xml/index.html similarity index 100% rename from admin/layouts/index.html rename to admin/sql/xml/index.html diff --git a/admin/controllers/ajax.json.php b/admin/src/Controller/AjaxController.php similarity index 62% rename from admin/controllers/ajax.json.php rename to admin/src/Controller/AjaxController.php index 4e2ec5a3..9cb00af1 100644 --- a/admin/controllers/ajax.json.php +++ b/admin/src/Controller/AjaxController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage ajax.json.php + @subpackage AjaxController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,28 +21,47 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\Application\CMSApplication; +use Joomla\CMS\MVC\Controller\BaseController; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Session\Session; +use Joomla\Input\Input; +use Joomla\Utilities\ArrayHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\BaseController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Sermondistributor Ajax Base Controller + * + * @since 1.6 */ -class SermondistributorControllerAjax extends BaseController +class AjaxController extends BaseController { - public function __construct($config) + /** + * Constructor. + * + * @param array $config An optional associative array of configuration settings. + * Recognized key values include 'name', 'default_task', 'model_path', and + * 'view_path' (this list is not meant to be comprehensive). + * @param ?MVCFactoryInterface $factory The factory. + * @param ?CMSApplication $app The Application for the dispatcher + * @param ?Input $input Input + * + * @since 3.0 + */ + public function __construct($config = [], ?MVCFactoryInterface $factory = null, ?CMSApplication $app = null, ?Input $input = null) { - parent::__construct($config); + parent::__construct($config, $factory, $app, $input); + // make sure all json stuff are set - JFactory::getDocument()->setMimeEncoding( 'application/json' ); - // get the application - $app = JFactory::getApplication(); - $app->setHeader('Content-Disposition','attachment;filename="getajax.json"'); - $app->setHeader('Access-Control-Allow-Origin', '*'); - // load the tasks + $this->app->getDocument()->setMimeEncoding( 'application/json' ); + $this->app->setHeader('Content-Disposition','attachment;filename="getajax.json"'); + $this->app->setHeader('Access-Control-Allow-Origin', '*'); + // load the tasks $this->registerTask('isNew', 'ajax'); $this->registerTask('isRead', 'ajax'); $this->registerTask('getBuildTable', 'ajax'); @@ -51,19 +70,24 @@ class SermondistributorControllerAjax extends BaseController $this->registerTask('updateLocalListingExternal', 'ajax'); } + /** + * The ajax function + * + * @since 3.10 + */ public function ajax() { // get the user for later use - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // get the input values - $jinput = JFactory::getApplication()->input; - // check if we should return raw - $returnRaw = $jinput->get('raw', false, 'BOOLEAN'); + $jinput = $this->input ?? $this->app->input; + // check if we should return raw (DEFAULT TRUE SINCE J4) + $returnRaw = $jinput->get('raw', true, 'BOOLEAN'); // return to a callback function - $callback = $jinput->get('callback', null, 'CMD'); + $callback = $jinput->get('callback', null, 'CMD'); // Check Token! - $token = JSession::getFormToken(); - $call_token = $jinput->get('token', 0, 'ALNUM'); + $token = Session::getFormToken(); + $call_token = $jinput->get('token', 0, 'ALNUM'); if($jinput->get($token, 0, 'ALNUM') || $token === $call_token) { // get the task @@ -76,11 +100,19 @@ class SermondistributorControllerAjax extends BaseController $noticeValue = $jinput->get('notice', NULL, 'STRING'); if($noticeValue && $user->id != 0) { - $result = $this->getModel('ajax')->isNew($noticeValue); + $ajaxModule = $this->getModel('ajax', 'Administrator'); + if ($ajaxModule) + { + $result = $ajaxModule->isNew($noticeValue); + } + else + { + $result = ['error' => 'There was an error! [149]']; + } } else { - $result = false; + $result = ['error' => 'There was an error! [149]']; } if($callback) { @@ -95,7 +127,7 @@ class SermondistributorControllerAjax extends BaseController echo "(".json_encode($result).");"; } } - catch(Exception $e) + catch(\Exception $e) { if($callback) { @@ -117,11 +149,19 @@ class SermondistributorControllerAjax extends BaseController $noticeValue = $jinput->get('notice', NULL, 'STRING'); if($noticeValue && $user->id != 0) { - $result = $this->getModel('ajax')->isRead($noticeValue); + $ajaxModule = $this->getModel('ajax', 'Administrator'); + if ($ajaxModule) + { + $result = $ajaxModule->isRead($noticeValue); + } + else + { + $result = ['error' => 'There was an error! [149]']; + } } else { - $result = false; + $result = ['error' => 'There was an error! [149]']; } if($callback) { @@ -136,7 +176,7 @@ class SermondistributorControllerAjax extends BaseController echo "(".json_encode($result).");"; } } - catch(Exception $e) + catch(\Exception $e) { if($callback) { @@ -159,11 +199,19 @@ class SermondistributorControllerAjax extends BaseController $ojectValue = $jinput->get('oject', NULL, 'STRING'); if($idNameValue && $user->id != 0 && $ojectValue) { - $result = $this->getModel('ajax')->getBuildTable($idNameValue, $ojectValue); + $ajaxModule = $this->getModel('ajax', 'Administrator'); + if ($ajaxModule) + { + $result = $ajaxModule->getBuildTable($idNameValue, $ojectValue); + } + else + { + $result = ['error' => 'There was an error! [149]']; + } } else { - $result = false; + $result = ['error' => 'There was an error! [149]']; } if($callback) { @@ -178,7 +226,7 @@ class SermondistributorControllerAjax extends BaseController echo "(".json_encode($result).");"; } } - catch(Exception $e) + catch(\Exception $e) { if($callback) { @@ -200,11 +248,19 @@ class SermondistributorControllerAjax extends BaseController $idValue = $jinput->get('id', NULL, 'INT'); if($idValue && $user->id != 0) { - $result = $this->getModel('ajax')->getSourceStatus($idValue); + $ajaxModule = $this->getModel('ajax', 'Administrator'); + if ($ajaxModule) + { + $result = $ajaxModule->getSourceStatus($idValue); + } + else + { + $result = ['error' => 'There was an error! [149]']; + } } else { - $result = false; + $result = ['error' => 'There was an error! [149]']; } if($callback) { @@ -219,7 +275,7 @@ class SermondistributorControllerAjax extends BaseController echo "(".json_encode($result).");"; } } - catch(Exception $e) + catch(\Exception $e) { if($callback) { @@ -241,11 +297,19 @@ class SermondistributorControllerAjax extends BaseController $getTypeValue = $jinput->get('getType', NULL, 'WORD'); if($getTypeValue && $user->id != 0) { - $result = $this->getModel('ajax')->getCronPath($getTypeValue); + $ajaxModule = $this->getModel('ajax', 'Administrator'); + if ($ajaxModule) + { + $result = $ajaxModule->getCronPath($getTypeValue); + } + else + { + $result = ['error' => 'There was an error! [149]']; + } } else { - $result = false; + $result = ['error' => 'There was an error! [149]']; } if($callback) { @@ -260,7 +324,7 @@ class SermondistributorControllerAjax extends BaseController echo "(".json_encode($result).");"; } } - catch(Exception $e) + catch(\Exception $e) { if($callback) { @@ -285,11 +349,19 @@ class SermondistributorControllerAjax extends BaseController $sleutelValue = $jinput->get('sleutel', NULL, 'CMD'); if($idValue && $user->id != 0 && $targetValue && $typeValue && $sleutelValue) { - $result = $this->getModel('ajax')->updateLocalListingExternal($idValue, $targetValue, $typeValue, $sleutelValue); + $ajaxModule = $this->getModel('ajax', 'Administrator'); + if ($ajaxModule) + { + $result = $ajaxModule->updateLocalListingExternal($idValue, $targetValue, $typeValue, $sleutelValue); + } + else + { + $result = ['error' => 'There was an error! [149]']; + } } else { - $result = false; + $result = ['error' => 'There was an error! [149]']; } if($callback) { @@ -304,7 +376,7 @@ class SermondistributorControllerAjax extends BaseController echo "(".json_encode($result).");"; } } - catch(Exception $e) + catch(\Exception $e) { if($callback) { @@ -327,15 +399,15 @@ class SermondistributorControllerAjax extends BaseController // return to a callback function if($callback) { - echo $callback."(".json_encode(false).");"; + echo $callback."(".json_encode(['error' => 'There was an error! [129]']).");"; } elseif($returnRaw) { - echo json_encode(false); + echo json_encode(['error' => 'There was an error! [129]']); } else { - echo "(".json_encode(false).");"; + echo "(".json_encode(['error' => 'There was an error! [129]']).");"; } } } diff --git a/admin/src/Controller/DisplayController.php b/admin/src/Controller/DisplayController.php new file mode 100644 index 00000000..86372935 --- /dev/null +++ b/admin/src/Controller/DisplayController.php @@ -0,0 +1,58 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\MVC\Controller\BaseController; +use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Router\Route; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor master admin display controller. + * + * @since 4.0 + */ +class DisplayController extends BaseController +{ + /** + * The default view. + * + * @var string + * @since 1.0.0 + */ + protected $default_view = 'sermondistributor'; + + /** + * display task + * + * @return void + */ + function display($cachable = false, $urlparams = false) + { + return parent::display($cachable, $urlparams); + } +} diff --git a/admin/controllers/external_source.php b/admin/src/Controller/External_sourceController.php similarity index 75% rename from admin/controllers/external_source.php rename to admin/src/Controller/External_sourceController.php index f06e4479..98a26068 100644 --- a/admin/controllers/external_source.php +++ b/admin/src/Controller/External_sourceController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage external_source.php + @subpackage External_sourceController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,18 +21,43 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Form\FormFactoryInterface; +use Joomla\CMS\Application\CMSApplication; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\Input\Input; +use Joomla\CMS\Versioning\VersionableControllerTrait; +use Joomla\CMS\MVC\Controller\FormController; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\FormController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * External_source Form Controller + * + * @since 1.6 */ -class SermondistributorControllerExternal_source extends FormController +class External_sourceController extends FormController { + use VersionableControllerTrait; + + /** + * The prefix to use with controller messages. + * + * @var string + * @since 1.6 + */ + protected $text_prefix = 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE'; + /** * Current or most recently performed task. * @@ -43,41 +68,36 @@ class SermondistributorControllerExternal_source extends FormController protected $task; /** - * Class constructor. + * The URL view list variable. * - * @param array $config A named array of configuration variables. - * - * @since 1.6 + * @var string + * @since 1.6 */ - public function __construct($config = array()) - { - $this->view_list = 'External_sources'; // safeguard for setting the return view listing to the main view. - parent::__construct($config); - } + protected $view_list = 'external_sources'; public function clearLocalListing() { // Check for request forgeries. - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); // get the data $originalData = $this->input->post->get('jform', array(), 'array'); if (isset($originalData['id']) && $originalData['id'] > 0) { // get the needed - $app = JFactory::getApplication(); - $lang = JFactory::getLanguage(); + $app = Factory::getApplication(); + $lang = Factory::getLanguage(); $model = $this->getModel(); - $user = JFactory::getUser(); + $user = Factory::getUser(); $context = "$this->option.edit.$this->context"; if (!$user->authorise('external_source.clear_local_listing', 'com_sermondistributor')) { // force production is not permitted - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_YOU_DO_NOT_HAVE_PERMISSION_TO_CLEAR_LOCAL_LISTING'), 'error'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_YOU_DO_NOT_HAVE_PERMISSION_TO_CLEAR_LOCAL_LISTING'), 'error'); // Save the data in the session. $app->setUserState($context . '.data', $originalData); // Redirect back to the edit screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($originalData['id'], 'id'), false ) @@ -89,12 +109,12 @@ class SermondistributorControllerExternal_source extends FormController if (!$cleared) { // force production is not permitted - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_WAS_NOT_CLEARED'), 'error'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_WAS_NOT_CLEARED'), 'error'); // Save the data in the session. $app->setUserState($context . '.data', $originalData); // Redirect back to the edit screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($originalData['id'], 'id'), false ) @@ -102,23 +122,23 @@ class SermondistributorControllerExternal_source extends FormController return false; } // force production is not permitted - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_WAS_CLEARED_SUCCESSFULLY'), 'success'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_WAS_CLEARED_SUCCESSFULLY'), 'success'); // Save the data in the session. $app->setUserState($context . '.data', $originalData); // Redirect back to the edit screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($originalData['id'], 'id'), false ) ); return true; } - $this->setError(JText::_('COM_SERMONDISTRIBUTOR_CLEARING_LOCAL_LISTING_CAN_NOT_BE_DONE')); + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_CLEARING_LOCAL_LISTING_CAN_NOT_BE_DONE')); $this->setMessage($this->getError(), 'error'); // Redirect back to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . '&view=' . $this->view_list . $this->getRedirectToListAppend(), false ) @@ -129,26 +149,26 @@ class SermondistributorControllerExternal_source extends FormController public function resetUpdateStatus() { // Check for request forgeries. - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); // get the data $originalData = $this->input->post->get('jform', array(), 'array'); if (isset($originalData['id']) && $originalData['id'] > 0) { // get the needed - $app = JFactory::getApplication(); - $lang = JFactory::getLanguage(); + $app = Factory::getApplication(); + $lang = Factory::getLanguage(); $model = $this->getModel(); - $user = JFactory::getUser(); + $user = Factory::getUser(); $context = "$this->option.edit.$this->context"; if (!$user->authorise('external_source.reset_update_status', 'com_sermondistributor')) { // force production is not permitted - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_YOU_DO_NOT_HAVE_PERMISSION_TO_RESET_UPDATE_STATUS'), 'error'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_YOU_DO_NOT_HAVE_PERMISSION_TO_RESET_UPDATE_STATUS'), 'error'); // Save the data in the session. $app->setUserState($context . '.data', $originalData); // Redirect back to the edit screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($originalData['id'], 'id'), false ) @@ -165,7 +185,7 @@ class SermondistributorControllerExternal_source extends FormController $app->setUserState($context . '.data', $originalData); // Redirect back to the edit screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($originalData['id'], 'id'), false ) @@ -173,23 +193,23 @@ class SermondistributorControllerExternal_source extends FormController return false; } // reset update status success - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_RESETTING_THE_UPDATE_STATUS_WAS_SUCCESSFUL'), 'success'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_RESETTING_THE_UPDATE_STATUS_WAS_SUCCESSFUL'), 'success'); // Save the data in the session. $app->setUserState($context . '.data', $originalData); // Redirect back to the edit screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($originalData['id'], 'id'), false ) ); return true; } - $this->setError(JText::_('COM_SERMONDISTRIBUTOR_RESET_UPDATE_STATUS_CAN_NOT_BE_DONE')); + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_RESET_UPDATE_STATUS_CAN_NOT_BE_DONE')); $this->setMessage($this->getError(), 'error'); // Redirect back to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . '&view=' . $this->view_list . $this->getRedirectToListAppend(), false ) @@ -197,7 +217,7 @@ class SermondistributorControllerExternal_source extends FormController return false; } - /** + /** * Method override to check if you can add a new record. * * @param array $data An array of input data. @@ -206,10 +226,10 @@ class SermondistributorControllerExternal_source extends FormController * * @since 1.6 */ - protected function allowAdd($data = array()) + protected function allowAdd($data = []) { // Get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // Access check. $access = $user->authorise('external_source.access', 'com_sermondistributor'); if (!$access) @@ -217,7 +237,7 @@ class SermondistributorControllerExternal_source extends FormController return false; } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('external_source.create', $this->option); } @@ -231,16 +251,16 @@ class SermondistributorControllerExternal_source extends FormController * * @since 1.6 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // get record id. $recordId = (int) isset($data[$key]) ? $data[$key] : 0; // Access check. - $access = ($user->authorise('external_source.access', 'com_sermondistributor.external_source.' . (int) $recordId) && $user->authorise('external_source.access', 'com_sermondistributor')); + $access = ($user->authorise('external_source.access', 'com_sermondistributor.external_source.' . (int) $recordId) && $user->authorise('external_source.access', 'com_sermondistributor')); if (!$access) { return false; @@ -305,12 +325,12 @@ class SermondistributorControllerExternal_source extends FormController // set the referral options if ($refid && $ref) - { - $append = '&ref=' . (string)$ref . '&refid='. (int)$refid . $append; + { + $append = '&ref=' . (string) $ref . '&refid='. (int) $refid . $append; } elseif ($ref) { - $append = '&ref='. (string)$ref . $append; + $append = '&ref='. (string) $ref . $append; } return $append; @@ -327,13 +347,13 @@ class SermondistributorControllerExternal_source extends FormController */ public function batch($model = null) { - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); // Set the model - $model = $this->getModel('External_source', '', array()); + $model = $this->getModel('External_source', '', []); // Preset the redirect - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=external_sources' . $this->getRedirectToListAppend(), false)); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=external_sources' . $this->getRedirectToListAppend(), false)); return parent::batch($model); } @@ -358,13 +378,13 @@ class SermondistributorControllerExternal_source extends FormController $cancel = parent::cancel($key); - if (!is_null($return) && JUri::isInternal(base64_decode($return))) + if (!is_null($return) && Uri::isInternal(base64_decode($return))) { $redirect = base64_decode($return); // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); @@ -375,7 +395,7 @@ class SermondistributorControllerExternal_source extends FormController // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -386,7 +406,7 @@ class SermondistributorControllerExternal_source extends FormController // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -412,7 +432,7 @@ class SermondistributorControllerExternal_source extends FormController // Check if there is a return value $return = $this->input->get('return', null, 'base64'); - $canReturn = (!is_null($return) && JUri::isInternal(base64_decode($return))); + $canReturn = (!is_null($return) && Uri::isInternal(base64_decode($return))); if ($this->ref || $this->refid || $canReturn) { @@ -430,29 +450,29 @@ class SermondistributorControllerExternal_source extends FormController // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); } elseif ($this->refid && $this->ref) { - $redirect = '&view=' . (string)$this->ref . '&layout=edit&id=' . (int)$this->refid; + $redirect = '&view=' . (string) $this->ref . '&layout=edit&id=' . (int) $this->refid; // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); } elseif ($this->ref) { - $redirect = '&view=' . (string)$this->ref; + $redirect = '&view=' . (string) $this->ref; // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -464,16 +484,15 @@ class SermondistributorControllerExternal_source extends FormController * Function that allows child controller access to model data * after the data has been saved. * - * @param JModel &$model The data model object. - * @param array $validData The validated data. + * @param BaseDatabaseModel &$model The data model object. + * @param array $validData The validated data. * * @return void * * @since 11.1 */ - protected function postSaveHook(JModelLegacy $model, $validData = array()) + protected function postSaveHook(BaseDatabaseModel $model, $validData = []) { return; } - } diff --git a/admin/controllers/external_sources.php b/admin/src/Controller/External_sourcesController.php similarity index 69% rename from admin/controllers/external_sources.php rename to admin/src/Controller/External_sourcesController.php index d3bd3db0..af2655ce 100644 --- a/admin/controllers/external_sources.php +++ b/admin/src/Controller/External_sourcesController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage external_sources.php + @subpackage External_sourcesController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,27 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Controller\AdminController; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * External_sources Admin Controller + * + * @since 1.6 */ -class SermondistributorControllerExternal_sources extends AdminController +class External_sourcesController extends AdminController { /** * The prefix to use with controller messages. @@ -42,17 +52,17 @@ class SermondistributorControllerExternal_sources extends AdminController protected $text_prefix = 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES'; /** - * Method to get a model object, loading it if required. + * Proxy for getModel. * * @param string $name The model name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * - * @return JModelLegacy The model. + * @return \Joomla\CMS\MVC\Model\BaseDatabaseModel * * @since 1.6 */ - public function getModel($name = 'External_source', $prefix = 'SermondistributorModel', $config = array('ignore_request' => true)) + public function getModel($name = 'External_source', $prefix = 'Administrator', $config = ['ignore_request' => true]) { return parent::getModel($name, $prefix, $config); } @@ -60,13 +70,13 @@ class SermondistributorControllerExternal_sources extends AdminController public function exportData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if export is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('external_source.export', 'com_sermondistributor') && $user->authorise('core.export', 'com_sermondistributor')) { // Get the input - $input = JFactory::getApplication()->input; + $input = Factory::getApplication()->input; $pks = $input->post->get('cid', array(), 'array'); // Sanitize the input $pks = ArrayHelper::toInteger($pks); @@ -74,16 +84,16 @@ class SermondistributorControllerExternal_sources extends AdminController $model = $this->getModel('External_sources'); // get the data to export $data = $model->getExportData($pks); - if (SermondistributorHelper::checkArray($data)) + if (UtilitiesArrayHelper::check($data)) { // now set the data to the spreadsheet - $date = JFactory::getDate(); + $date = Factory::getDate(); SermondistributorHelper::xls($data,'External_sources_'.$date->format('jS_F_Y'),'External sources exported ('.$date->format('jS F, Y').')','external sources'); } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=external_sources', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=external_sources', false), $message, 'error'); return; } @@ -91,32 +101,32 @@ class SermondistributorControllerExternal_sources extends AdminController public function importData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if import is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('external_source.import', 'com_sermondistributor') && $user->authorise('core.import', 'com_sermondistributor')) { // Get the import model $model = $this->getModel('External_sources'); // get the headers to import $headers = $model->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { // Load headers to session. - $session = JFactory::getSession(); + $session = Factory::getSession(); $headers = json_encode($headers); $session->set('external_source_VDM_IMPORTHEADERS', $headers); $session->set('backto_VDM_IMPORT', 'external_sources'); $session->set('dataType_VDM_IMPORTINTO', 'external_source'); // Redirect to import view. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_EXTERNAL_SOURCES'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=import', false), $message); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_EXTERNAL_SOURCES'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=import', false), $message); return; } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=external_sources', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=external_sources', false), $message, 'error'); return; } -} +} \ No newline at end of file diff --git a/admin/controllers/help.php b/admin/src/Controller/HelpController.php similarity index 73% rename from admin/controllers/help.php rename to admin/src/Controller/HelpController.php index 91892d00..53ab6139 100644 --- a/admin/controllers/help.php +++ b/admin/src/Controller/HelpController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage help.php + @subpackage HelpController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,24 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\MVC\Controller\BaseController; +use Joomla\Database\DatabaseInterface; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Session\Session; +use Joomla\Utilities\ArrayHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\BaseController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Sermondistributor Help Base Controller + * + * @since 1.6 */ -class SermondistributorControllerHelp extends BaseController +class HelpController extends BaseController { public function __construct($config) { @@ -42,12 +49,12 @@ class SermondistributorControllerHelp extends BaseController public function help() { - $user = JFactory::getUser(); - $jinput = JFactory::getApplication()->input; + $user = Factory::getApplication()->getIdentity(); + $jinput = Factory::getApplication()->input; // Check Token! - $token = JSession::getFormToken(); - $call_token = $jinput->get('token', 0, 'ALNUM'); - if($user->id != 0 && $token == $call_token) + $token = Session::getFormToken(); + $call_token = $jinput->get('token', 0, 'ALNUM'); + if($user->id != 0 && ($jinput->get($token, 0, 'ALNUM') || $token === $call_token)) { $task = $this->getTask(); switch($task){ @@ -75,7 +82,7 @@ class SermondistributorControllerHelp extends BaseController break; } } - else + else { // stop execution gracefully jexit(); @@ -84,8 +91,8 @@ class SermondistributorControllerHelp extends BaseController protected function getHelpDocumentText($id) { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); + $db = Factory::getContainer()->get(DatabaseInterface::class); + $query = $db->getQuery(true); $query->select(array('a.title','a.content')); $query->from('#__sermondistributor_help_document AS a'); $query->where('a.id = '.(int) $id); @@ -94,21 +101,21 @@ class SermondistributorControllerHelp extends BaseController $db->execute(); if($db->getNumRows()) { - $text = array(); + $text = []; $document = $db->loadObject(); // fix image issue - $images['src="images'] = 'src="'.JURI::root().'images'; - $images["src='images"] = "src='".JURI::root()."images"; - $images['src="/images'] = 'src="'.JURI::root().'images'; - $images["src='/images"] = "src='".JURI::root()."images"; + $images['src="images'] = 'src="'.Uri::root().'images'; + $images["src='images"] = "src='".Uri::root()."images"; + $images['src="/images'] = 'src="'.Uri::root().'images'; + $images["src='/images"] = "src='".Uri::root()."images"; // set document template $text[] = ""; $text[] = ''; $text[] = ""; $text[] = ''; $text[] = "".$document->title.""; - $text[] = ''; - $text[] = ''; + $text[] = ''; + $text[] = ''; $text[] = ""; $text[] = '
'; $text[] = '
'; diff --git a/admin/controllers/help_document.php b/admin/src/Controller/Help_documentController.php similarity index 76% rename from admin/controllers/help_document.php rename to admin/src/Controller/Help_documentController.php index ec8b60e4..5f3639b3 100644 --- a/admin/controllers/help_document.php +++ b/admin/src/Controller/Help_documentController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage help_document.php + @subpackage Help_documentController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,18 +21,43 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Form\FormFactoryInterface; +use Joomla\CMS\Application\CMSApplication; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\Input\Input; +use Joomla\CMS\Versioning\VersionableControllerTrait; +use Joomla\CMS\MVC\Controller\FormController; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\FormController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Help_document Form Controller + * + * @since 1.6 */ -class SermondistributorControllerHelp_document extends FormController +class Help_documentController extends FormController { + use VersionableControllerTrait; + + /** + * The prefix to use with controller messages. + * + * @var string + * @since 1.6 + */ + protected $text_prefix = 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT'; + /** * Current or most recently performed task. * @@ -43,19 +68,14 @@ class SermondistributorControllerHelp_document extends FormController protected $task; /** - * Class constructor. + * The URL view list variable. * - * @param array $config A named array of configuration variables. - * - * @since 1.6 + * @var string + * @since 1.6 */ - public function __construct($config = array()) - { - $this->view_list = 'Help_documents'; // safeguard for setting the return view listing to the main view. - parent::__construct($config); - } + protected $view_list = 'help_documents'; - /** + /** * Method override to check if you can add a new record. * * @param array $data An array of input data. @@ -64,10 +84,10 @@ class SermondistributorControllerHelp_document extends FormController * * @since 1.6 */ - protected function allowAdd($data = array()) + protected function allowAdd($data = []) { // Get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // Access check. $access = $user->authorise('help_document.access', 'com_sermondistributor'); if (!$access) @@ -75,7 +95,7 @@ class SermondistributorControllerHelp_document extends FormController return false; } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('help_document.create', $this->option); } @@ -89,16 +109,16 @@ class SermondistributorControllerHelp_document extends FormController * * @since 1.6 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // get record id. $recordId = (int) isset($data[$key]) ? $data[$key] : 0; // Access check. - $access = ($user->authorise('help_document.access', 'com_sermondistributor.help_document.' . (int) $recordId) && $user->authorise('help_document.access', 'com_sermondistributor')); + $access = ($user->authorise('help_document.access', 'com_sermondistributor.help_document.' . (int) $recordId) && $user->authorise('help_document.access', 'com_sermondistributor')); if (!$access) { return false; @@ -163,12 +183,12 @@ class SermondistributorControllerHelp_document extends FormController // set the referral options if ($refid && $ref) - { - $append = '&ref=' . (string)$ref . '&refid='. (int)$refid . $append; + { + $append = '&ref=' . (string) $ref . '&refid='. (int) $refid . $append; } elseif ($ref) { - $append = '&ref='. (string)$ref . $append; + $append = '&ref='. (string) $ref . $append; } return $append; @@ -185,13 +205,13 @@ class SermondistributorControllerHelp_document extends FormController */ public function batch($model = null) { - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); // Set the model - $model = $this->getModel('Help_document', '', array()); + $model = $this->getModel('Help_document', '', []); // Preset the redirect - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=help_documents' . $this->getRedirectToListAppend(), false)); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=help_documents' . $this->getRedirectToListAppend(), false)); return parent::batch($model); } @@ -216,13 +236,13 @@ class SermondistributorControllerHelp_document extends FormController $cancel = parent::cancel($key); - if (!is_null($return) && JUri::isInternal(base64_decode($return))) + if (!is_null($return) && Uri::isInternal(base64_decode($return))) { $redirect = base64_decode($return); // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); @@ -233,7 +253,7 @@ class SermondistributorControllerHelp_document extends FormController // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -244,7 +264,7 @@ class SermondistributorControllerHelp_document extends FormController // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -270,7 +290,7 @@ class SermondistributorControllerHelp_document extends FormController // Check if there is a return value $return = $this->input->get('return', null, 'base64'); - $canReturn = (!is_null($return) && JUri::isInternal(base64_decode($return))); + $canReturn = (!is_null($return) && Uri::isInternal(base64_decode($return))); if ($this->ref || $this->refid || $canReturn) { @@ -288,29 +308,29 @@ class SermondistributorControllerHelp_document extends FormController // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); } elseif ($this->refid && $this->ref) { - $redirect = '&view=' . (string)$this->ref . '&layout=edit&id=' . (int)$this->refid; + $redirect = '&view=' . (string) $this->ref . '&layout=edit&id=' . (int) $this->refid; // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); } elseif ($this->ref) { - $redirect = '&view=' . (string)$this->ref; + $redirect = '&view=' . (string) $this->ref; // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -322,16 +342,15 @@ class SermondistributorControllerHelp_document extends FormController * Function that allows child controller access to model data * after the data has been saved. * - * @param JModel &$model The data model object. - * @param array $validData The validated data. + * @param BaseDatabaseModel &$model The data model object. + * @param array $validData The validated data. * * @return void * * @since 11.1 */ - protected function postSaveHook(JModelLegacy $model, $validData = array()) + protected function postSaveHook(BaseDatabaseModel $model, $validData = []) { return; } - } diff --git a/admin/controllers/help_documents.php b/admin/src/Controller/Help_documentsController.php similarity index 68% rename from admin/controllers/help_documents.php rename to admin/src/Controller/Help_documentsController.php index d41cc2e3..ea63d422 100644 --- a/admin/controllers/help_documents.php +++ b/admin/src/Controller/Help_documentsController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage help_documents.php + @subpackage Help_documentsController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,27 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Controller\AdminController; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Help_documents Admin Controller + * + * @since 1.6 */ -class SermondistributorControllerHelp_documents extends AdminController +class Help_documentsController extends AdminController { /** * The prefix to use with controller messages. @@ -42,17 +52,17 @@ class SermondistributorControllerHelp_documents extends AdminController protected $text_prefix = 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS'; /** - * Method to get a model object, loading it if required. + * Proxy for getModel. * * @param string $name The model name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * - * @return JModelLegacy The model. + * @return \Joomla\CMS\MVC\Model\BaseDatabaseModel * * @since 1.6 */ - public function getModel($name = 'Help_document', $prefix = 'SermondistributorModel', $config = array('ignore_request' => true)) + public function getModel($name = 'Help_document', $prefix = 'Administrator', $config = ['ignore_request' => true]) { return parent::getModel($name, $prefix, $config); } @@ -60,13 +70,13 @@ class SermondistributorControllerHelp_documents extends AdminController public function exportData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if export is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('help_document.export', 'com_sermondistributor') && $user->authorise('core.export', 'com_sermondistributor')) { // Get the input - $input = JFactory::getApplication()->input; + $input = Factory::getApplication()->input; $pks = $input->post->get('cid', array(), 'array'); // Sanitize the input $pks = ArrayHelper::toInteger($pks); @@ -74,16 +84,16 @@ class SermondistributorControllerHelp_documents extends AdminController $model = $this->getModel('Help_documents'); // get the data to export $data = $model->getExportData($pks); - if (SermondistributorHelper::checkArray($data)) + if (UtilitiesArrayHelper::check($data)) { // now set the data to the spreadsheet - $date = JFactory::getDate(); + $date = Factory::getDate(); SermondistributorHelper::xls($data,'Help_documents_'.$date->format('jS_F_Y'),'Help documents exported ('.$date->format('jS F, Y').')','help documents'); } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=help_documents', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=help_documents', false), $message, 'error'); return; } @@ -91,32 +101,32 @@ class SermondistributorControllerHelp_documents extends AdminController public function importData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if import is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('help_document.import', 'com_sermondistributor') && $user->authorise('core.import', 'com_sermondistributor')) { // Get the import model $model = $this->getModel('Help_documents'); // get the headers to import $headers = $model->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { // Load headers to session. - $session = JFactory::getSession(); + $session = Factory::getSession(); $headers = json_encode($headers); $session->set('help_document_VDM_IMPORTHEADERS', $headers); $session->set('backto_VDM_IMPORT', 'help_documents'); $session->set('dataType_VDM_IMPORTINTO', 'help_document'); // Redirect to import view. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_HELP_DOCUMENTS'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=import', false), $message); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_HELP_DOCUMENTS'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=import', false), $message); return; } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=help_documents', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=help_documents', false), $message, 'error'); return; } -} +} \ No newline at end of file diff --git a/admin/controllers/import.php b/admin/src/Controller/ImportController.php similarity index 78% rename from admin/controllers/import.php rename to admin/src/Controller/ImportController.php index b26652bc..fae2f9cc 100644 --- a/admin/controllers/import.php +++ b/admin/src/Controller/ImportController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage import.php + @subpackage ImportController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,25 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\MVC\Controller\BaseController; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use Joomla\Utilities\ArrayHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\BaseController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Sermondistributor Import Base Controller + * + * @since 1.6 */ -class SermondistributorControllerImport extends BaseController +class ImportController extends BaseController { /** * Import an spreadsheet. @@ -41,21 +49,21 @@ class SermondistributorControllerImport extends BaseController public function import() { // Check for request forgeries - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); $model = $this->getModel('import'); if ($model->import()) { - $cache = JFactory::getCache('mod_menu'); + $cache = Factory::getCache('mod_menu'); $cache->clean(); // TODO: Reset the users acl here as well to kill off any missing bits } - $app = JFactory::getApplication(); + $app = Factory::getApplication(); $redirect_url = $app->getUserState('com_sermondistributor.redirect_url'); if (empty($redirect_url)) { - $redirect_url = JRoute::_('index.php?option=com_sermondistributor&view=import', false); + $redirect_url = Route::_('index.php?option=com_sermondistributor&view=import', false); } else { diff --git a/admin/controllers/local_listing.php b/admin/src/Controller/Local_listingController.php similarity index 76% rename from admin/controllers/local_listing.php rename to admin/src/Controller/Local_listingController.php index 7c01f87a..26c98ec8 100644 --- a/admin/controllers/local_listing.php +++ b/admin/src/Controller/Local_listingController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage local_listing.php + @subpackage Local_listingController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,18 +21,43 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Form\FormFactoryInterface; +use Joomla\CMS\Application\CMSApplication; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\Input\Input; +use Joomla\CMS\Versioning\VersionableControllerTrait; +use Joomla\CMS\MVC\Controller\FormController; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\FormController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Local_listing Form Controller + * + * @since 1.6 */ -class SermondistributorControllerLocal_listing extends FormController +class Local_listingController extends FormController { + use VersionableControllerTrait; + + /** + * The prefix to use with controller messages. + * + * @var string + * @since 1.6 + */ + protected $text_prefix = 'COM_SERMONDISTRIBUTOR_LOCAL_LISTING'; + /** * Current or most recently performed task. * @@ -43,19 +68,14 @@ class SermondistributorControllerLocal_listing extends FormController protected $task; /** - * Class constructor. + * The URL view list variable. * - * @param array $config A named array of configuration variables. - * - * @since 1.6 + * @var string + * @since 1.6 */ - public function __construct($config = array()) - { - $this->view_list = 'Local_listings'; // safeguard for setting the return view listing to the main view. - parent::__construct($config); - } + protected $view_list = 'local_listings'; - /** + /** * Method override to check if you can add a new record. * * @param array $data An array of input data. @@ -64,10 +84,10 @@ class SermondistributorControllerLocal_listing extends FormController * * @since 1.6 */ - protected function allowAdd($data = array()) + protected function allowAdd($data = []) { // Get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // Access check. $access = $user->authorise('local_listing.access', 'com_sermondistributor'); if (!$access) @@ -75,7 +95,7 @@ class SermondistributorControllerLocal_listing extends FormController return false; } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('local_listing.create', $this->option); } @@ -89,16 +109,16 @@ class SermondistributorControllerLocal_listing extends FormController * * @since 1.6 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // get record id. $recordId = (int) isset($data[$key]) ? $data[$key] : 0; // Access check. - $access = ($user->authorise('local_listing.access', 'com_sermondistributor.local_listing.' . (int) $recordId) && $user->authorise('local_listing.access', 'com_sermondistributor')); + $access = ($user->authorise('local_listing.access', 'com_sermondistributor.local_listing.' . (int) $recordId) && $user->authorise('local_listing.access', 'com_sermondistributor')); if (!$access) { return false; @@ -163,12 +183,12 @@ class SermondistributorControllerLocal_listing extends FormController // set the referral options if ($refid && $ref) - { - $append = '&ref=' . (string)$ref . '&refid='. (int)$refid . $append; + { + $append = '&ref=' . (string) $ref . '&refid='. (int) $refid . $append; } elseif ($ref) { - $append = '&ref='. (string)$ref . $append; + $append = '&ref='. (string) $ref . $append; } return $append; @@ -185,13 +205,13 @@ class SermondistributorControllerLocal_listing extends FormController */ public function batch($model = null) { - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); // Set the model - $model = $this->getModel('Local_listing', '', array()); + $model = $this->getModel('Local_listing', '', []); // Preset the redirect - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=local_listings' . $this->getRedirectToListAppend(), false)); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=local_listings' . $this->getRedirectToListAppend(), false)); return parent::batch($model); } @@ -216,13 +236,13 @@ class SermondistributorControllerLocal_listing extends FormController $cancel = parent::cancel($key); - if (!is_null($return) && JUri::isInternal(base64_decode($return))) + if (!is_null($return) && Uri::isInternal(base64_decode($return))) { $redirect = base64_decode($return); // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); @@ -233,7 +253,7 @@ class SermondistributorControllerLocal_listing extends FormController // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -244,7 +264,7 @@ class SermondistributorControllerLocal_listing extends FormController // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -270,7 +290,7 @@ class SermondistributorControllerLocal_listing extends FormController // Check if there is a return value $return = $this->input->get('return', null, 'base64'); - $canReturn = (!is_null($return) && JUri::isInternal(base64_decode($return))); + $canReturn = (!is_null($return) && Uri::isInternal(base64_decode($return))); if ($this->ref || $this->refid || $canReturn) { @@ -288,29 +308,29 @@ class SermondistributorControllerLocal_listing extends FormController // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); } elseif ($this->refid && $this->ref) { - $redirect = '&view=' . (string)$this->ref . '&layout=edit&id=' . (int)$this->refid; + $redirect = '&view=' . (string) $this->ref . '&layout=edit&id=' . (int) $this->refid; // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); } elseif ($this->ref) { - $redirect = '&view=' . (string)$this->ref; + $redirect = '&view=' . (string) $this->ref; // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -322,16 +342,15 @@ class SermondistributorControllerLocal_listing extends FormController * Function that allows child controller access to model data * after the data has been saved. * - * @param JModel &$model The data model object. - * @param array $validData The validated data. + * @param BaseDatabaseModel &$model The data model object. + * @param array $validData The validated data. * * @return void * * @since 11.1 */ - protected function postSaveHook(JModelLegacy $model, $validData = array()) + protected function postSaveHook(BaseDatabaseModel $model, $validData = []) { return; } - } diff --git a/admin/controllers/local_listings.php b/admin/src/Controller/Local_listingsController.php similarity index 68% rename from admin/controllers/local_listings.php rename to admin/src/Controller/Local_listingsController.php index d5f3e1ec..5fc4b054 100644 --- a/admin/controllers/local_listings.php +++ b/admin/src/Controller/Local_listingsController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage local_listings.php + @subpackage Local_listingsController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,27 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Controller\AdminController; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Local_listings Admin Controller + * + * @since 1.6 */ -class SermondistributorControllerLocal_listings extends AdminController +class Local_listingsController extends AdminController { /** * The prefix to use with controller messages. @@ -42,17 +52,17 @@ class SermondistributorControllerLocal_listings extends AdminController protected $text_prefix = 'COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS'; /** - * Method to get a model object, loading it if required. + * Proxy for getModel. * * @param string $name The model name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * - * @return JModelLegacy The model. + * @return \Joomla\CMS\MVC\Model\BaseDatabaseModel * * @since 1.6 */ - public function getModel($name = 'Local_listing', $prefix = 'SermondistributorModel', $config = array('ignore_request' => true)) + public function getModel($name = 'Local_listing', $prefix = 'Administrator', $config = ['ignore_request' => true]) { return parent::getModel($name, $prefix, $config); } @@ -60,13 +70,13 @@ class SermondistributorControllerLocal_listings extends AdminController public function exportData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if export is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('local_listing.export', 'com_sermondistributor') && $user->authorise('core.export', 'com_sermondistributor')) { // Get the input - $input = JFactory::getApplication()->input; + $input = Factory::getApplication()->input; $pks = $input->post->get('cid', array(), 'array'); // Sanitize the input $pks = ArrayHelper::toInteger($pks); @@ -74,16 +84,16 @@ class SermondistributorControllerLocal_listings extends AdminController $model = $this->getModel('Local_listings'); // get the data to export $data = $model->getExportData($pks); - if (SermondistributorHelper::checkArray($data)) + if (UtilitiesArrayHelper::check($data)) { // now set the data to the spreadsheet - $date = JFactory::getDate(); + $date = Factory::getDate(); SermondistributorHelper::xls($data,'Local_listings_'.$date->format('jS_F_Y'),'Local listings exported ('.$date->format('jS F, Y').')','local listings'); } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=local_listings', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=local_listings', false), $message, 'error'); return; } @@ -91,32 +101,32 @@ class SermondistributorControllerLocal_listings extends AdminController public function importData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if import is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('local_listing.import', 'com_sermondistributor') && $user->authorise('core.import', 'com_sermondistributor')) { // Get the import model $model = $this->getModel('Local_listings'); // get the headers to import $headers = $model->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { // Load headers to session. - $session = JFactory::getSession(); + $session = Factory::getSession(); $headers = json_encode($headers); $session->set('local_listing_VDM_IMPORTHEADERS', $headers); $session->set('backto_VDM_IMPORT', 'local_listings'); $session->set('dataType_VDM_IMPORTINTO', 'local_listing'); // Redirect to import view. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_LOCAL_LISTINGS'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=import', false), $message); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_LOCAL_LISTINGS'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=import', false), $message); return; } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=local_listings', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=local_listings', false), $message, 'error'); return; } -} +} \ No newline at end of file diff --git a/admin/controllers/manual_updater.php b/admin/src/Controller/Manual_updaterController.php similarity index 60% rename from admin/controllers/manual_updater.php rename to admin/src/Controller/Manual_updaterController.php index 48b34601..fd5bac3f 100644 --- a/admin/controllers/manual_updater.php +++ b/admin/src/Controller/Manual_updaterController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage manual_updater.php + @subpackage Manual_updaterController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,25 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Controller\AdminController; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Manual_updater Admin Controller + * + * @since 1.6 */ -class SermondistributorControllerManual_updater extends AdminController +class Manual_updaterController extends AdminController { /** * The prefix to use with controller messages. @@ -43,25 +51,36 @@ class SermondistributorControllerManual_updater extends AdminController /** * Proxy for getModel. - * @since 2.5 + * + * @param string $name The model name. Optional. + * @param string $prefix The class prefix. Optional. + * @param array $config Configuration array for model. Optional. + * + * @return \Joomla\CMS\MVC\Model\BaseDatabaseModel + * + * @since 1.6 */ - public function getModel($name = 'Manual_updater', $prefix = 'SermondistributorModel', $config = array()) + public function getModel($name = '###View###', $prefix = 'Administrator', $config = ['ignore_request' => true]) { - $model = parent::getModel($name, $prefix, array('ignore_request' => true)); - - return $model; + return parent::getModel($name, $prefix, $config); } - public function dashboard() + /** + * Adds option to redirect back to the dashboard. + * + * @return void + * + * @since 3.0 + */ + public function dashboard(): void { - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor', false)); - return; + $this->setRedirect(Route::_('index.php?option=com_sermondistributor', false)); } - public function gotoExternalSources() + public function gotoExternalSources() { - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=external_sources', false)); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=external_sources', false)); return; } } diff --git a/admin/controllers/preacher.php b/admin/src/Controller/PreacherController.php similarity index 77% rename from admin/controllers/preacher.php rename to admin/src/Controller/PreacherController.php index af2ef781..8fa30917 100644 --- a/admin/controllers/preacher.php +++ b/admin/src/Controller/PreacherController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage preacher.php + @subpackage PreacherController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,18 +21,43 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Form\FormFactoryInterface; +use Joomla\CMS\Application\CMSApplication; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\Input\Input; +use Joomla\CMS\Versioning\VersionableControllerTrait; +use Joomla\CMS\MVC\Controller\FormController; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\FormController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Preacher Form Controller + * + * @since 1.6 */ -class SermondistributorControllerPreacher extends FormController +class PreacherController extends FormController { + use VersionableControllerTrait; + + /** + * The prefix to use with controller messages. + * + * @var string + * @since 1.6 + */ + protected $text_prefix = 'COM_SERMONDISTRIBUTOR_PREACHER'; + /** * Current or most recently performed task. * @@ -43,19 +68,14 @@ class SermondistributorControllerPreacher extends FormController protected $task; /** - * Class constructor. + * The URL view list variable. * - * @param array $config A named array of configuration variables. - * - * @since 1.6 + * @var string + * @since 1.6 */ - public function __construct($config = array()) - { - $this->view_list = 'Preachers'; // safeguard for setting the return view listing to the main view. - parent::__construct($config); - } + protected $view_list = 'preachers'; - /** + /** * Method override to check if you can add a new record. * * @param array $data An array of input data. @@ -64,10 +84,10 @@ class SermondistributorControllerPreacher extends FormController * * @since 1.6 */ - protected function allowAdd($data = array()) + protected function allowAdd($data = []) { // Get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // Access check. $access = $user->authorise('preacher.access', 'com_sermondistributor'); if (!$access) @@ -75,7 +95,7 @@ class SermondistributorControllerPreacher extends FormController return false; } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('preacher.create', $this->option); } @@ -89,16 +109,16 @@ class SermondistributorControllerPreacher extends FormController * * @since 1.6 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // get record id. $recordId = (int) isset($data[$key]) ? $data[$key] : 0; // Access check. - $access = ($user->authorise('preacher.access', 'com_sermondistributor.preacher.' . (int) $recordId) && $user->authorise('preacher.access', 'com_sermondistributor')); + $access = ($user->authorise('preacher.access', 'com_sermondistributor.preacher.' . (int) $recordId) && $user->authorise('preacher.access', 'com_sermondistributor')); if (!$access) { return false; @@ -163,12 +183,12 @@ class SermondistributorControllerPreacher extends FormController // set the referral options if ($refid && $ref) - { - $append = '&ref=' . (string)$ref . '&refid='. (int)$refid . $append; + { + $append = '&ref=' . (string) $ref . '&refid='. (int) $refid . $append; } elseif ($ref) { - $append = '&ref='. (string)$ref . $append; + $append = '&ref='. (string) $ref . $append; } return $append; @@ -185,13 +205,13 @@ class SermondistributorControllerPreacher extends FormController */ public function batch($model = null) { - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); // Set the model - $model = $this->getModel('Preacher', '', array()); + $model = $this->getModel('Preacher', '', []); // Preset the redirect - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=preachers' . $this->getRedirectToListAppend(), false)); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=preachers' . $this->getRedirectToListAppend(), false)); return parent::batch($model); } @@ -216,13 +236,13 @@ class SermondistributorControllerPreacher extends FormController $cancel = parent::cancel($key); - if (!is_null($return) && JUri::isInternal(base64_decode($return))) + if (!is_null($return) && Uri::isInternal(base64_decode($return))) { $redirect = base64_decode($return); // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); @@ -233,7 +253,7 @@ class SermondistributorControllerPreacher extends FormController // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -244,7 +264,7 @@ class SermondistributorControllerPreacher extends FormController // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -270,7 +290,7 @@ class SermondistributorControllerPreacher extends FormController // Check if there is a return value $return = $this->input->get('return', null, 'base64'); - $canReturn = (!is_null($return) && JUri::isInternal(base64_decode($return))); + $canReturn = (!is_null($return) && Uri::isInternal(base64_decode($return))); if ($this->ref || $this->refid || $canReturn) { @@ -288,29 +308,29 @@ class SermondistributorControllerPreacher extends FormController // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); } elseif ($this->refid && $this->ref) { - $redirect = '&view=' . (string)$this->ref . '&layout=edit&id=' . (int)$this->refid; + $redirect = '&view=' . (string) $this->ref . '&layout=edit&id=' . (int) $this->refid; // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); } elseif ($this->ref) { - $redirect = '&view=' . (string)$this->ref; + $redirect = '&view=' . (string) $this->ref; // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -322,16 +342,15 @@ class SermondistributorControllerPreacher extends FormController * Function that allows child controller access to model data * after the data has been saved. * - * @param JModel &$model The data model object. - * @param array $validData The validated data. + * @param BaseDatabaseModel &$model The data model object. + * @param array $validData The validated data. * * @return void * * @since 11.1 */ - protected function postSaveHook(JModelLegacy $model, $validData = array()) + protected function postSaveHook(BaseDatabaseModel $model, $validData = []) { return; } - } diff --git a/admin/controllers/preachers.php b/admin/src/Controller/PreachersController.php similarity index 68% rename from admin/controllers/preachers.php rename to admin/src/Controller/PreachersController.php index 95168672..6c91b382 100644 --- a/admin/controllers/preachers.php +++ b/admin/src/Controller/PreachersController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage preachers.php + @subpackage PreachersController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,27 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Controller\AdminController; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Preachers Admin Controller + * + * @since 1.6 */ -class SermondistributorControllerPreachers extends AdminController +class PreachersController extends AdminController { /** * The prefix to use with controller messages. @@ -42,17 +52,17 @@ class SermondistributorControllerPreachers extends AdminController protected $text_prefix = 'COM_SERMONDISTRIBUTOR_PREACHERS'; /** - * Method to get a model object, loading it if required. + * Proxy for getModel. * * @param string $name The model name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * - * @return JModelLegacy The model. + * @return \Joomla\CMS\MVC\Model\BaseDatabaseModel * * @since 1.6 */ - public function getModel($name = 'Preacher', $prefix = 'SermondistributorModel', $config = array('ignore_request' => true)) + public function getModel($name = 'Preacher', $prefix = 'Administrator', $config = ['ignore_request' => true]) { return parent::getModel($name, $prefix, $config); } @@ -60,13 +70,13 @@ class SermondistributorControllerPreachers extends AdminController public function exportData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if export is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('preacher.export', 'com_sermondistributor') && $user->authorise('core.export', 'com_sermondistributor')) { // Get the input - $input = JFactory::getApplication()->input; + $input = Factory::getApplication()->input; $pks = $input->post->get('cid', array(), 'array'); // Sanitize the input $pks = ArrayHelper::toInteger($pks); @@ -74,16 +84,16 @@ class SermondistributorControllerPreachers extends AdminController $model = $this->getModel('Preachers'); // get the data to export $data = $model->getExportData($pks); - if (SermondistributorHelper::checkArray($data)) + if (UtilitiesArrayHelper::check($data)) { // now set the data to the spreadsheet - $date = JFactory::getDate(); + $date = Factory::getDate(); SermondistributorHelper::xls($data,'Preachers_'.$date->format('jS_F_Y'),'Preachers exported ('.$date->format('jS F, Y').')','preachers'); } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=preachers', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=preachers', false), $message, 'error'); return; } @@ -91,32 +101,32 @@ class SermondistributorControllerPreachers extends AdminController public function importData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if import is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('preacher.import', 'com_sermondistributor') && $user->authorise('core.import', 'com_sermondistributor')) { // Get the import model $model = $this->getModel('Preachers'); // get the headers to import $headers = $model->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { // Load headers to session. - $session = JFactory::getSession(); + $session = Factory::getSession(); $headers = json_encode($headers); $session->set('preacher_VDM_IMPORTHEADERS', $headers); $session->set('backto_VDM_IMPORT', 'preachers'); $session->set('dataType_VDM_IMPORTINTO', 'preacher'); // Redirect to import view. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_PREACHERS'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=import', false), $message); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_PREACHERS'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=import', false), $message); return; } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=preachers', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=preachers', false), $message, 'error'); return; } -} +} \ No newline at end of file diff --git a/admin/controllers/series.php b/admin/src/Controller/SeriesController.php similarity index 77% rename from admin/controllers/series.php rename to admin/src/Controller/SeriesController.php index c39f8846..1dcabf05 100644 --- a/admin/controllers/series.php +++ b/admin/src/Controller/SeriesController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage series.php + @subpackage SeriesController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,18 +21,43 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Form\FormFactoryInterface; +use Joomla\CMS\Application\CMSApplication; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\Input\Input; +use Joomla\CMS\Versioning\VersionableControllerTrait; +use Joomla\CMS\MVC\Controller\FormController; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\FormController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Series Form Controller + * + * @since 1.6 */ -class SermondistributorControllerSeries extends FormController +class SeriesController extends FormController { + use VersionableControllerTrait; + + /** + * The prefix to use with controller messages. + * + * @var string + * @since 1.6 + */ + protected $text_prefix = 'COM_SERMONDISTRIBUTOR_SERIES'; + /** * Current or most recently performed task. * @@ -43,19 +68,14 @@ class SermondistributorControllerSeries extends FormController protected $task; /** - * Class constructor. + * The URL view list variable. * - * @param array $config A named array of configuration variables. - * - * @since 1.6 + * @var string + * @since 1.6 */ - public function __construct($config = array()) - { - $this->view_list = 'Series_list'; // safeguard for setting the return view listing to the main view. - parent::__construct($config); - } + protected $view_list = 'series_list'; - /** + /** * Method override to check if you can add a new record. * * @param array $data An array of input data. @@ -64,10 +84,10 @@ class SermondistributorControllerSeries extends FormController * * @since 1.6 */ - protected function allowAdd($data = array()) + protected function allowAdd($data = []) { // Get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // Access check. $access = $user->authorise('series.access', 'com_sermondistributor'); if (!$access) @@ -75,7 +95,7 @@ class SermondistributorControllerSeries extends FormController return false; } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('series.create', $this->option); } @@ -89,16 +109,16 @@ class SermondistributorControllerSeries extends FormController * * @since 1.6 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // get record id. $recordId = (int) isset($data[$key]) ? $data[$key] : 0; // Access check. - $access = ($user->authorise('series.access', 'com_sermondistributor.series.' . (int) $recordId) && $user->authorise('series.access', 'com_sermondistributor')); + $access = ($user->authorise('series.access', 'com_sermondistributor.series.' . (int) $recordId) && $user->authorise('series.access', 'com_sermondistributor')); if (!$access) { return false; @@ -163,12 +183,12 @@ class SermondistributorControllerSeries extends FormController // set the referral options if ($refid && $ref) - { - $append = '&ref=' . (string)$ref . '&refid='. (int)$refid . $append; + { + $append = '&ref=' . (string) $ref . '&refid='. (int) $refid . $append; } elseif ($ref) { - $append = '&ref='. (string)$ref . $append; + $append = '&ref='. (string) $ref . $append; } return $append; @@ -185,13 +205,13 @@ class SermondistributorControllerSeries extends FormController */ public function batch($model = null) { - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); // Set the model - $model = $this->getModel('Series', '', array()); + $model = $this->getModel('Series', '', []); // Preset the redirect - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=series_list' . $this->getRedirectToListAppend(), false)); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=series_list' . $this->getRedirectToListAppend(), false)); return parent::batch($model); } @@ -216,13 +236,13 @@ class SermondistributorControllerSeries extends FormController $cancel = parent::cancel($key); - if (!is_null($return) && JUri::isInternal(base64_decode($return))) + if (!is_null($return) && Uri::isInternal(base64_decode($return))) { $redirect = base64_decode($return); // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); @@ -233,7 +253,7 @@ class SermondistributorControllerSeries extends FormController // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -244,7 +264,7 @@ class SermondistributorControllerSeries extends FormController // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -270,7 +290,7 @@ class SermondistributorControllerSeries extends FormController // Check if there is a return value $return = $this->input->get('return', null, 'base64'); - $canReturn = (!is_null($return) && JUri::isInternal(base64_decode($return))); + $canReturn = (!is_null($return) && Uri::isInternal(base64_decode($return))); if ($this->ref || $this->refid || $canReturn) { @@ -288,29 +308,29 @@ class SermondistributorControllerSeries extends FormController // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); } elseif ($this->refid && $this->ref) { - $redirect = '&view=' . (string)$this->ref . '&layout=edit&id=' . (int)$this->refid; + $redirect = '&view=' . (string) $this->ref . '&layout=edit&id=' . (int) $this->refid; // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); } elseif ($this->ref) { - $redirect = '&view=' . (string)$this->ref; + $redirect = '&view=' . (string) $this->ref; // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -322,16 +342,15 @@ class SermondistributorControllerSeries extends FormController * Function that allows child controller access to model data * after the data has been saved. * - * @param JModel &$model The data model object. - * @param array $validData The validated data. + * @param BaseDatabaseModel &$model The data model object. + * @param array $validData The validated data. * * @return void * * @since 11.1 */ - protected function postSaveHook(JModelLegacy $model, $validData = array()) + protected function postSaveHook(BaseDatabaseModel $model, $validData = []) { return; } - } diff --git a/admin/controllers/series_list.php b/admin/src/Controller/Series_listController.php similarity index 68% rename from admin/controllers/series_list.php rename to admin/src/Controller/Series_listController.php index 64a172fc..c6e200cc 100644 --- a/admin/controllers/series_list.php +++ b/admin/src/Controller/Series_listController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage series_list.php + @subpackage Series_listController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,27 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Controller\AdminController; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Series_list Admin Controller + * + * @since 1.6 */ -class SermondistributorControllerSeries_list extends AdminController +class Series_listController extends AdminController { /** * The prefix to use with controller messages. @@ -42,17 +52,17 @@ class SermondistributorControllerSeries_list extends AdminController protected $text_prefix = 'COM_SERMONDISTRIBUTOR_SERIES_LIST'; /** - * Method to get a model object, loading it if required. + * Proxy for getModel. * * @param string $name The model name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * - * @return JModelLegacy The model. + * @return \Joomla\CMS\MVC\Model\BaseDatabaseModel * * @since 1.6 */ - public function getModel($name = 'Series', $prefix = 'SermondistributorModel', $config = array('ignore_request' => true)) + public function getModel($name = 'Series', $prefix = 'Administrator', $config = ['ignore_request' => true]) { return parent::getModel($name, $prefix, $config); } @@ -60,13 +70,13 @@ class SermondistributorControllerSeries_list extends AdminController public function exportData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if export is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('series.export', 'com_sermondistributor') && $user->authorise('core.export', 'com_sermondistributor')) { // Get the input - $input = JFactory::getApplication()->input; + $input = Factory::getApplication()->input; $pks = $input->post->get('cid', array(), 'array'); // Sanitize the input $pks = ArrayHelper::toInteger($pks); @@ -74,16 +84,16 @@ class SermondistributorControllerSeries_list extends AdminController $model = $this->getModel('Series_list'); // get the data to export $data = $model->getExportData($pks); - if (SermondistributorHelper::checkArray($data)) + if (UtilitiesArrayHelper::check($data)) { // now set the data to the spreadsheet - $date = JFactory::getDate(); + $date = Factory::getDate(); SermondistributorHelper::xls($data,'Series_list_'.$date->format('jS_F_Y'),'Series list exported ('.$date->format('jS F, Y').')','series list'); } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=series_list', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=series_list', false), $message, 'error'); return; } @@ -91,32 +101,32 @@ class SermondistributorControllerSeries_list extends AdminController public function importData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if import is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('series.import', 'com_sermondistributor') && $user->authorise('core.import', 'com_sermondistributor')) { // Get the import model $model = $this->getModel('Series_list'); // get the headers to import $headers = $model->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { // Load headers to session. - $session = JFactory::getSession(); + $session = Factory::getSession(); $headers = json_encode($headers); $session->set('series_VDM_IMPORTHEADERS', $headers); $session->set('backto_VDM_IMPORT', 'series_list'); $session->set('dataType_VDM_IMPORTINTO', 'series'); // Redirect to import view. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_SERIES_LIST'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=import', false), $message); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_SERIES_LIST'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=import', false), $message); return; } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=series_list', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=series_list', false), $message, 'error'); return; } -} +} \ No newline at end of file diff --git a/admin/controllers/sermon.php b/admin/src/Controller/SermonController.php similarity index 78% rename from admin/controllers/sermon.php rename to admin/src/Controller/SermonController.php index 38d90ab9..528facfa 100644 --- a/admin/controllers/sermon.php +++ b/admin/src/Controller/SermonController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage sermon.php + @subpackage SermonController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,18 +21,43 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Form\FormFactoryInterface; +use Joomla\CMS\Application\CMSApplication; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\Input\Input; +use Joomla\CMS\Versioning\VersionableControllerTrait; +use Joomla\CMS\MVC\Controller\FormController; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\FormController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Sermon Form Controller + * + * @since 1.6 */ -class SermondistributorControllerSermon extends FormController +class SermonController extends FormController { + use VersionableControllerTrait; + + /** + * The prefix to use with controller messages. + * + * @var string + * @since 1.6 + */ + protected $text_prefix = 'COM_SERMONDISTRIBUTOR_SERMON'; + /** * Current or most recently performed task. * @@ -43,19 +68,14 @@ class SermondistributorControllerSermon extends FormController protected $task; /** - * Class constructor. + * The URL view list variable. * - * @param array $config A named array of configuration variables. - * - * @since 1.6 + * @var string + * @since 1.6 */ - public function __construct($config = array()) - { - $this->view_list = 'Sermons'; // safeguard for setting the return view listing to the main view. - parent::__construct($config); - } + protected $view_list = 'sermons'; - /** + /** * Method override to check if you can add a new record. * * @param array $data An array of input data. @@ -64,10 +84,10 @@ class SermondistributorControllerSermon extends FormController * * @since 1.6 */ - protected function allowAdd($data = array()) + protected function allowAdd($data = []) { // Get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // Access check. $access = $user->authorise('sermon.access', 'com_sermondistributor'); if (!$access) @@ -75,7 +95,7 @@ class SermondistributorControllerSermon extends FormController return false; } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('sermon.create', $this->option); } @@ -89,9 +109,9 @@ class SermondistributorControllerSermon extends FormController * * @since 1.6 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // get record id. $recordId = (int) isset($data[$key]) ? $data[$key] : 0; @@ -162,12 +182,12 @@ class SermondistributorControllerSermon extends FormController // set the referral options if ($refid && $ref) - { - $append = '&ref=' . (string)$ref . '&refid='. (int)$refid . $append; + { + $append = '&ref=' . (string) $ref . '&refid='. (int) $refid . $append; } elseif ($ref) { - $append = '&ref='. (string)$ref . $append; + $append = '&ref='. (string) $ref . $append; } return $append; @@ -184,13 +204,13 @@ class SermondistributorControllerSermon extends FormController */ public function batch($model = null) { - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); // Set the model - $model = $this->getModel('Sermon', '', array()); + $model = $this->getModel('Sermon', '', []); // Preset the redirect - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=sermons' . $this->getRedirectToListAppend(), false)); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=sermons' . $this->getRedirectToListAppend(), false)); return parent::batch($model); } @@ -215,13 +235,13 @@ class SermondistributorControllerSermon extends FormController $cancel = parent::cancel($key); - if (!is_null($return) && JUri::isInternal(base64_decode($return))) + if (!is_null($return) && Uri::isInternal(base64_decode($return))) { $redirect = base64_decode($return); // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); @@ -232,7 +252,7 @@ class SermondistributorControllerSermon extends FormController // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -243,7 +263,7 @@ class SermondistributorControllerSermon extends FormController // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -269,7 +289,7 @@ class SermondistributorControllerSermon extends FormController // Check if there is a return value $return = $this->input->get('return', null, 'base64'); - $canReturn = (!is_null($return) && JUri::isInternal(base64_decode($return))); + $canReturn = (!is_null($return) && Uri::isInternal(base64_decode($return))); if ($this->ref || $this->refid || $canReturn) { @@ -287,29 +307,29 @@ class SermondistributorControllerSermon extends FormController // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); } elseif ($this->refid && $this->ref) { - $redirect = '&view=' . (string)$this->ref . '&layout=edit&id=' . (int)$this->refid; + $redirect = '&view=' . (string) $this->ref . '&layout=edit&id=' . (int) $this->refid; // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); } elseif ($this->ref) { - $redirect = '&view=' . (string)$this->ref; + $redirect = '&view=' . (string) $this->ref; // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -321,16 +341,15 @@ class SermondistributorControllerSermon extends FormController * Function that allows child controller access to model data * after the data has been saved. * - * @param JModel &$model The data model object. - * @param array $validData The validated data. + * @param BaseDatabaseModel &$model The data model object. + * @param array $validData The validated data. * * @return void * * @since 11.1 */ - protected function postSaveHook(JModelLegacy $model, $validData = array()) + protected function postSaveHook(BaseDatabaseModel $model, $validData = []) { return; } - } diff --git a/admin/controllers/sermondistributor.php b/admin/src/Controller/SermondistributorController.php similarity index 79% rename from admin/controllers/sermondistributor.php rename to admin/src/Controller/SermondistributorController.php index cca77968..efa79840 100644 --- a/admin/controllers/sermondistributor.php +++ b/admin/src/Controller/SermondistributorController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage sermondistributor.php + @subpackage SermondistributorController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,25 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Controller\AdminController; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermondistributor Admin Controller + * + * @since 1.6 */ -class SermondistributorControllerSermondistributor extends AdminController +class SermondistributorController extends AdminController { } diff --git a/admin/controllers/sermons.php b/admin/src/Controller/SermonsController.php similarity index 68% rename from admin/controllers/sermons.php rename to admin/src/Controller/SermonsController.php index 3bb2b568..3bf5ecf6 100644 --- a/admin/controllers/sermons.php +++ b/admin/src/Controller/SermonsController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage sermons.php + @subpackage SermonsController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,27 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Controller\AdminController; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermons Admin Controller + * + * @since 1.6 */ -class SermondistributorControllerSermons extends AdminController +class SermonsController extends AdminController { /** * The prefix to use with controller messages. @@ -42,17 +52,17 @@ class SermondistributorControllerSermons extends AdminController protected $text_prefix = 'COM_SERMONDISTRIBUTOR_SERMONS'; /** - * Method to get a model object, loading it if required. + * Proxy for getModel. * * @param string $name The model name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * - * @return JModelLegacy The model. + * @return \Joomla\CMS\MVC\Model\BaseDatabaseModel * * @since 1.6 */ - public function getModel($name = 'Sermon', $prefix = 'SermondistributorModel', $config = array('ignore_request' => true)) + public function getModel($name = 'Sermon', $prefix = 'Administrator', $config = ['ignore_request' => true]) { return parent::getModel($name, $prefix, $config); } @@ -60,13 +70,13 @@ class SermondistributorControllerSermons extends AdminController public function exportData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if export is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('sermon.export', 'com_sermondistributor') && $user->authorise('core.export', 'com_sermondistributor')) { // Get the input - $input = JFactory::getApplication()->input; + $input = Factory::getApplication()->input; $pks = $input->post->get('cid', array(), 'array'); // Sanitize the input $pks = ArrayHelper::toInteger($pks); @@ -74,16 +84,16 @@ class SermondistributorControllerSermons extends AdminController $model = $this->getModel('Sermons'); // get the data to export $data = $model->getExportData($pks); - if (SermondistributorHelper::checkArray($data)) + if (UtilitiesArrayHelper::check($data)) { // now set the data to the spreadsheet - $date = JFactory::getDate(); + $date = Factory::getDate(); SermondistributorHelper::xls($data,'Sermons_'.$date->format('jS_F_Y'),'Sermons exported ('.$date->format('jS F, Y').')','sermons'); } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=sermons', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=sermons', false), $message, 'error'); return; } @@ -91,32 +101,32 @@ class SermondistributorControllerSermons extends AdminController public function importData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if import is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('sermon.import', 'com_sermondistributor') && $user->authorise('core.import', 'com_sermondistributor')) { // Get the import model $model = $this->getModel('Sermons'); // get the headers to import $headers = $model->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { // Load headers to session. - $session = JFactory::getSession(); + $session = Factory::getSession(); $headers = json_encode($headers); $session->set('sermon_VDM_IMPORTHEADERS', $headers); $session->set('backto_VDM_IMPORT', 'sermons'); $session->set('dataType_VDM_IMPORTINTO', 'sermon'); // Redirect to import view. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_SERMONS'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=import', false), $message); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_SERMONS'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=import', false), $message); return; } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=sermons', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=sermons', false), $message, 'error'); return; } -} +} \ No newline at end of file diff --git a/admin/controllers/statistic.php b/admin/src/Controller/StatisticController.php similarity index 76% rename from admin/controllers/statistic.php rename to admin/src/Controller/StatisticController.php index ea1fe35f..af556a46 100644 --- a/admin/controllers/statistic.php +++ b/admin/src/Controller/StatisticController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage statistic.php + @subpackage StatisticController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,18 +21,43 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Form\FormFactoryInterface; +use Joomla\CMS\Application\CMSApplication; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\Input\Input; +use Joomla\CMS\Versioning\VersionableControllerTrait; +use Joomla\CMS\MVC\Controller\FormController; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Controller\FormController; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Statistic Form Controller + * + * @since 1.6 */ -class SermondistributorControllerStatistic extends FormController +class StatisticController extends FormController { + use VersionableControllerTrait; + + /** + * The prefix to use with controller messages. + * + * @var string + * @since 1.6 + */ + protected $text_prefix = 'COM_SERMONDISTRIBUTOR_STATISTIC'; + /** * Current or most recently performed task. * @@ -43,19 +68,14 @@ class SermondistributorControllerStatistic extends FormController protected $task; /** - * Class constructor. + * The URL view list variable. * - * @param array $config A named array of configuration variables. - * - * @since 1.6 + * @var string + * @since 1.6 */ - public function __construct($config = array()) - { - $this->view_list = 'Statistics'; // safeguard for setting the return view listing to the main view. - parent::__construct($config); - } + protected $view_list = 'statistics'; - /** + /** * Method override to check if you can add a new record. * * @param array $data An array of input data. @@ -64,10 +84,10 @@ class SermondistributorControllerStatistic extends FormController * * @since 1.6 */ - protected function allowAdd($data = array()) + protected function allowAdd($data = []) { // Get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // Access check. $access = $user->authorise('statistic.access', 'com_sermondistributor'); if (!$access) @@ -75,7 +95,7 @@ class SermondistributorControllerStatistic extends FormController return false; } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('statistic.create', $this->option); } @@ -89,16 +109,16 @@ class SermondistributorControllerStatistic extends FormController * * @since 1.6 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // get user object. - $user = JFactory::getUser(); + $user = $this->app->getIdentity(); // get record id. $recordId = (int) isset($data[$key]) ? $data[$key] : 0; // Access check. - $access = ($user->authorise('statistic.access', 'com_sermondistributor.statistic.' . (int) $recordId) && $user->authorise('statistic.access', 'com_sermondistributor')); + $access = ($user->authorise('statistic.access', 'com_sermondistributor.statistic.' . (int) $recordId) && $user->authorise('statistic.access', 'com_sermondistributor')); if (!$access) { return false; @@ -163,12 +183,12 @@ class SermondistributorControllerStatistic extends FormController // set the referral options if ($refid && $ref) - { - $append = '&ref=' . (string)$ref . '&refid='. (int)$refid . $append; + { + $append = '&ref=' . (string) $ref . '&refid='. (int) $refid . $append; } elseif ($ref) { - $append = '&ref='. (string)$ref . $append; + $append = '&ref='. (string) $ref . $append; } return $append; @@ -185,13 +205,13 @@ class SermondistributorControllerStatistic extends FormController */ public function batch($model = null) { - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); // Set the model - $model = $this->getModel('Statistic', '', array()); + $model = $this->getModel('Statistic', '', []); // Preset the redirect - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=statistics' . $this->getRedirectToListAppend(), false)); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=statistics' . $this->getRedirectToListAppend(), false)); return parent::batch($model); } @@ -216,13 +236,13 @@ class SermondistributorControllerStatistic extends FormController $cancel = parent::cancel($key); - if (!is_null($return) && JUri::isInternal(base64_decode($return))) + if (!is_null($return) && Uri::isInternal(base64_decode($return))) { $redirect = base64_decode($return); // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); @@ -233,7 +253,7 @@ class SermondistributorControllerStatistic extends FormController // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -244,7 +264,7 @@ class SermondistributorControllerStatistic extends FormController // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -270,7 +290,7 @@ class SermondistributorControllerStatistic extends FormController // Check if there is a return value $return = $this->input->get('return', null, 'base64'); - $canReturn = (!is_null($return) && JUri::isInternal(base64_decode($return))); + $canReturn = (!is_null($return) && Uri::isInternal(base64_decode($return))); if ($this->ref || $this->refid || $canReturn) { @@ -288,29 +308,29 @@ class SermondistributorControllerStatistic extends FormController // Redirect to the return value. $this->setRedirect( - JRoute::_( + Route::_( $redirect, false ) ); } elseif ($this->refid && $this->ref) { - $redirect = '&view=' . (string)$this->ref . '&layout=edit&id=' . (int)$this->refid; + $redirect = '&view=' . (string) $this->ref . '&layout=edit&id=' . (int) $this->refid; // Redirect to the item screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); } elseif ($this->ref) { - $redirect = '&view=' . (string)$this->ref; + $redirect = '&view=' . (string) $this->ref; // Redirect to the list screen. $this->setRedirect( - JRoute::_( + Route::_( 'index.php?option=' . $this->option . $redirect, false ) ); @@ -322,16 +342,15 @@ class SermondistributorControllerStatistic extends FormController * Function that allows child controller access to model data * after the data has been saved. * - * @param JModel &$model The data model object. - * @param array $validData The validated data. + * @param BaseDatabaseModel &$model The data model object. + * @param array $validData The validated data. * * @return void * * @since 11.1 */ - protected function postSaveHook(JModelLegacy $model, $validData = array()) + protected function postSaveHook(BaseDatabaseModel $model, $validData = []) { return; } - } diff --git a/admin/controllers/statistics.php b/admin/src/Controller/StatisticsController.php similarity index 68% rename from admin/controllers/statistics.php rename to admin/src/Controller/StatisticsController.php index 44380186..35013bbe 100644 --- a/admin/controllers/statistics.php +++ b/admin/src/Controller/StatisticsController.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage statistics.php + @subpackage StatisticsController.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,17 +21,27 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Controller; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Controller\AdminController; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Statistics Admin Controller + * + * @since 1.6 */ -class SermondistributorControllerStatistics extends AdminController +class StatisticsController extends AdminController { /** * The prefix to use with controller messages. @@ -42,17 +52,17 @@ class SermondistributorControllerStatistics extends AdminController protected $text_prefix = 'COM_SERMONDISTRIBUTOR_STATISTICS'; /** - * Method to get a model object, loading it if required. + * Proxy for getModel. * * @param string $name The model name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * - * @return JModelLegacy The model. + * @return \Joomla\CMS\MVC\Model\BaseDatabaseModel * * @since 1.6 */ - public function getModel($name = 'Statistic', $prefix = 'SermondistributorModel', $config = array('ignore_request' => true)) + public function getModel($name = 'Statistic', $prefix = 'Administrator', $config = ['ignore_request' => true]) { return parent::getModel($name, $prefix, $config); } @@ -60,13 +70,13 @@ class SermondistributorControllerStatistics extends AdminController public function exportData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if export is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('statistic.export', 'com_sermondistributor') && $user->authorise('core.export', 'com_sermondistributor')) { // Get the input - $input = JFactory::getApplication()->input; + $input = Factory::getApplication()->input; $pks = $input->post->get('cid', array(), 'array'); // Sanitize the input $pks = ArrayHelper::toInteger($pks); @@ -74,16 +84,16 @@ class SermondistributorControllerStatistics extends AdminController $model = $this->getModel('Statistics'); // get the data to export $data = $model->getExportData($pks); - if (SermondistributorHelper::checkArray($data)) + if (UtilitiesArrayHelper::check($data)) { // now set the data to the spreadsheet - $date = JFactory::getDate(); + $date = Factory::getDate(); SermondistributorHelper::xls($data,'Statistics_'.$date->format('jS_F_Y'),'Statistics exported ('.$date->format('jS F, Y').')','statistics'); } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=statistics', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_EXPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=statistics', false), $message, 'error'); return; } @@ -91,32 +101,32 @@ class SermondistributorControllerStatistics extends AdminController public function importData() { // Check for request forgeries - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + Session::checkToken() or die(Text::_('JINVALID_TOKEN')); // check if import is allowed for this user. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); if ($user->authorise('statistic.import', 'com_sermondistributor') && $user->authorise('core.import', 'com_sermondistributor')) { // Get the import model $model = $this->getModel('Statistics'); // get the headers to import $headers = $model->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { // Load headers to session. - $session = JFactory::getSession(); + $session = Factory::getSession(); $headers = json_encode($headers); $session->set('statistic_VDM_IMPORTHEADERS', $headers); $session->set('backto_VDM_IMPORT', 'statistics'); $session->set('dataType_VDM_IMPORTINTO', 'statistic'); // Redirect to import view. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_STATISTICS'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=import', false), $message); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_SELECT_FILE_FOR_STATISTICS'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=import', false), $message); return; } } // Redirect to the list screen with error. - $message = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); - $this->setRedirect(JRoute::_('index.php?option=com_sermondistributor&view=statistics', false), $message, 'error'); + $message = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_FAILED'); + $this->setRedirect(Route::_('index.php?option=com_sermondistributor&view=statistics', false), $message, 'error'); return; } -} +} \ No newline at end of file diff --git a/admin/models/fields/index.html b/admin/src/Controller/index.html similarity index 100% rename from admin/models/fields/index.html rename to admin/src/Controller/index.html diff --git a/admin/src/Extension/SermondistributorComponent.php b/admin/src/Extension/SermondistributorComponent.php new file mode 100644 index 00000000..dcce293a --- /dev/null +++ b/admin/src/Extension/SermondistributorComponent.php @@ -0,0 +1,88 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Extension; + +use Joomla\CMS\Association\AssociationServiceInterface; +use Joomla\CMS\Association\AssociationServiceTrait; +use Joomla\CMS\Categories\CategoryServiceInterface; +use Joomla\CMS\Categories\CategoryServiceTrait; +use Joomla\CMS\Component\Router\RouterServiceInterface; +use Joomla\CMS\Component\Router\RouterServiceTrait; +use Joomla\CMS\Extension\BootableExtensionInterface; +use Joomla\CMS\Extension\MVCComponent; +use Joomla\CMS\Factory; +use Joomla\CMS\Fields\FieldsServiceInterface; +use Joomla\CMS\Form\Form; +use Joomla\CMS\HTML\HTMLRegistryAwareTrait; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Tag\TagServiceInterface; +use Joomla\CMS\Tag\TagServiceTrait; +use Joomla\CMS\User\UserFactoryInterface; +// (soon) use TrueChristianChurch\Component\Sermondistributor\Administrator\Service\HTML\AdministratorService; +use Psr\Container\ContainerInterface; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Component class for com_sermondistributor + * + * @since 4.0 + */ +class SermondistributorComponent extends MVCComponent implements + BootableExtensionInterface, + CategoryServiceInterface, + RouterServiceInterface +{ + use AssociationServiceTrait; + use HTMLRegistryAwareTrait; + use RouterServiceTrait; + use CategoryServiceTrait, TagServiceTrait { + CategoryServiceTrait::getTableNameForSection insteadof TagServiceTrait; + CategoryServiceTrait::getStateColumnForSection insteadof TagServiceTrait; + } + + /** + * 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 + */ + public function boot(ContainerInterface $container) + { + // (soon) $this->getRegistry()->register('sermondistributoradministrator', new AdministratorService()); + } + + // will fix these soon + protected function getTableNameForSection(string $section = null){} + public function countItems(array $items, string $section){} + +} diff --git a/admin/models/forms/index.html b/admin/src/Extension/index.html similarity index 100% rename from admin/models/forms/index.html rename to admin/src/Extension/index.html diff --git a/admin/src/Field/AdminviewfolderlistField.php b/admin/src/Field/AdminviewfolderlistField.php new file mode 100644 index 00000000..b5dfe904 --- /dev/null +++ b/admin/src/Field/AdminviewfolderlistField.php @@ -0,0 +1,82 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Adminviewfolderlist Form Field class for the Sermondistributor component + * + * @since 1.6 + */ +class AdminviewfolderlistField extends ListField +{ + /** + * The adminviewfolderlist field type. + * + * @var string + */ + public $type = 'Adminviewfolderlist'; + + /** + * Method to get a list of options for a list input. + * + * @return array An array of Html options. + * @since 1.6 + */ + protected function getOptions() + { + // get custom folder files + $localfolders = []; + $localfolders[] = JPATH_ADMINISTRATOR . '/components/com_sermondistributor/views'; + $localfolders[] = JPATH_ADMINISTRATOR . '/components/com_sermondistributor/src/View'; + // set the default + $options = []; + // now check if there are files in the folder + foreach ($localfolders as $localfolder) + { + if (is_dir($localfolder) && $folders = \Joomla\Filesystem\Folder::folders($localfolder)) + { + if ($this->multiple === false) + { + $options[] = Html::_('select.option', '', Text::_('COM_SERMONDISTRIBUTOR_SELECT_AN_ADMIN_VIEW')); + } + foreach ($folders as $folder) + { + $options[] = Html::_('select.option', $folder, StringHelper::safe($folder, 'W')); + } + } + } + return $options; + } +} diff --git a/admin/src/Field/ArticlesField.php b/admin/src/Field/ArticlesField.php new file mode 100644 index 00000000..dc2cd781 --- /dev/null +++ b/admin/src/Field/ArticlesField.php @@ -0,0 +1,77 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Articles Form Field class for the Sermondistributor component + * + * @since 1.6 + */ +class ArticlesField extends ListField +{ + /** + * The articles field type. + * + * @var string + */ + public $type = 'Articles'; + + /** + * Method to get a list of options for a list input. + * + * @return array An array of Html options. + * @since 1.6 + */ + protected function getOptions() + { + $db = Factory::getDBO(); + $query = $db->getQuery(true); + $query->select($db->quoteName(array('a.id','a.title','a.alias'),array('id','article_title','alias'))); + $query->from($db->quoteName('#__content', 'a')); + $query->where($db->quoteName('a.state') . ' = 1'); + $query->order('a.title ASC'); + $db->setQuery((string)$query); + $items = $db->loadObjectList(); + $options = array(); + if ($items) + { + $options[] = Html::_('select.option', '', 'Select an Article'); + foreach($items as $item) + { + $options[] = Html::_('select.option', $item->id, $item->article_title . ' (' . $item->alias . ')'); + } + } + return $options; + } +} diff --git a/admin/src/Field/ExternalsourceField.php b/admin/src/Field/ExternalsourceField.php new file mode 100644 index 00000000..71462789 --- /dev/null +++ b/admin/src/Field/ExternalsourceField.php @@ -0,0 +1,184 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Externalsource Form Field class for the Sermondistributor component + * + * @since 1.6 + */ +class ExternalsourceField extends ListField +{ + /** + * The externalsource field type. + * + * @var string + */ + public $type = 'Externalsource'; + + /** + * Override to add new button + * + * @return string The field input markup. + * + * @since 3.2 + */ + protected function getInput() + { + // see if we should add buttons + $set_button = $this->getAttribute('button'); + // get html + $html = parent::getInput(); + // if true set button + if ($set_button === 'true') + { + $button = array(); + $script = array(); + $button_code_name = $this->getAttribute('name'); + // get the input from url + $app = Factory::getApplication(); + $jinput = $app->input; + // get the view name & id + $values = $jinput->getArray(array( + 'id' => 'int', + 'view' => 'word' + )); + // check if new item + $ref = ''; + $refJ = ''; + if (!is_null($values['id']) && strlen($values['view'])) + { + // only load referral if not new item. + $ref = '&ref=' . $values['view'] . '&refid=' . $values['id']; + $refJ = '&ref=' . $values['view'] . '&refid=' . $values['id']; + // get the return value. + $_uri = (string) \Joomla\CMS\Uri\Uri::getInstance(); + $_return = urlencode(base64_encode($_uri)); + // load return value. + $ref .= '&return=' . $_return; + $refJ .= '&return=' . $_return; + } + // get button label + $button_label = trim($button_code_name); + $button_label = preg_replace('/_+/', ' ', $button_label); + $button_label = preg_replace('/\s+/', ' ', $button_label); + $button_label = preg_replace("/[^A-Za-z ]/", '', $button_label); + $button_label = ucfirst(strtolower($button_label)); + // get user object + $user = Factory::getApplication()->getIdentity(); + // only add if user allowed to create external_source + if ($user->authorise('external_source.create', 'com_sermondistributor') && $app->isClient('administrator')) // TODO for now only in admin area. + { + // build Create button + $button[] = ' + '; + } + // only add if user allowed to edit external_source + if ($user->authorise('external_source.edit', 'com_sermondistributor') && $app->isClient('administrator')) // TODO for now only in admin area. + { + // build edit button + $button[] = ''; + // build script + $script[] = " + document.addEventListener('DOMContentLoaded', function() { + document.getElementById('jform_".$button_code_name."').addEventListener('change', function(e) { + e.preventDefault(); + let ".$button_code_name."Value = this.value; + ".$button_code_name."Button(".$button_code_name."Value); + }); + let ".$button_code_name."Value = document.getElementById('jform_".$button_code_name."').value; + ".$button_code_name."Button(".$button_code_name."Value); + }); + function ".$button_code_name."Button(value) { + var createButton = document.getElementById('".$button_code_name."Create'); + var editButton = document.getElementById('".$button_code_name."Edit'); + if (value > 0) { + // hide the create button + createButton.style.display = 'none'; + // show edit button + editButton.style.display = 'block'; + let url = 'index.php?option=com_sermondistributor&view=external_sources&task=external_source.edit&id='+value+'".$refJ."'; + editButton.setAttribute('href', url); + } else { + // show the create button + createButton.style.display = 'block'; + // hide edit button + editButton.style.display = 'none'; + } + }"; + } + // check if button was created for external_source field. + if (is_array($button) && count($button) > 0) + { + // Load the needed script. + $document = Factory::getApplication()->getDocument(); + $document->addScriptDeclaration(implode(' ',$script)); + // return the button attached to input field. + return '
' .$html . implode('',$button).'
'; + } + } + return $html; + } + + /** + * Method to get a list of options for a list input. + * + * @return array An array of Html options. + * @since 1.6 + */ + protected function getOptions() + { + $db = Factory::getDBO(); + $query = $db->getQuery(true); + $query->select($db->quoteName(array('a.id','a.description','a.externalsources','a.update_method'),array('id','external_source_description','externalsources','update_method'))); + $query->from($db->quoteName('#__sermondistributor_external_source', 'a')); + $query->where($db->quoteName('a.published') . ' = 1'); + $query->order('a.description ASC'); + $db->setQuery((string)$query); + $items = $db->loadObjectList(); + $options = array(); + if ($items) + { + $model = SermondistributorHelper::getModel('external_sources', JPATH_COMPONENT_ADMINISTRATOR); + $options[] = Html::_('select.option', '', 'Select an option'); + foreach($items as $item) + { + $options[] = Html::_('select.option', $item->id, $item->external_source_description. ' (' . Text::_($model->selectionTranslation($item->externalsources,'externalsources')). ' ' . Text::_($model->selectionTranslation($item->update_method,'update_method')). ')'); + } + } + return $options; + } +} diff --git a/admin/models/fields/adminviewfolderlist.php b/admin/src/Field/ExternalsourcefilesField.php similarity index 61% rename from admin/models/fields/adminviewfolderlist.php rename to admin/src/Field/ExternalsourcefilesField.php index 3cdb37c8..42e487f4 100644 --- a/admin/models/fields/adminviewfolderlist.php +++ b/admin/src/Field/ExternalsourcefilesField.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage adminviewfolderlist.php + @subpackage ExternalsourcefilesField.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,49 +21,49 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -// import the list field type -jimport('joomla.form.helper'); -JFormHelper::loadFieldClass('list'); +\defined('_JEXEC') or die; /** - * Adminviewfolderlist Form Field class for the Sermondistributor component + * Externalsourcefiles Form Field class for the Sermondistributor component + * + * @since 1.6 */ -class JFormFieldAdminviewfolderlist extends JFormFieldList +class ExternalsourcefilesField extends ListField { /** - * The adminviewfolderlist field type. + * The externalsourcefiles field type. * - * @var string + * @var string */ - public $type = 'adminviewfolderlist'; + public $type = 'Externalsourcefiles'; /** * Method to get a list of options for a list input. * - * @return array An array of JHtml options. + * @return array An array of Html options. + * @since 1.6 */ protected function getOptions() { - // get custom folder files - $localfolder = JPATH_COMPONENT_ADMINISTRATOR.'/views'; // set the default - $options = array(); - // import all needed classes - jimport('joomla.filesystem.folder'); - // now check if there are files in the folder - if (JFolder::exists($localfolder) && $folders = JFolder::folders($localfolder)) + $options[] = Html::_('select.option', '', Text::_('COM_SERMONDISTRIBUTOR_THE_LOCAL_LISTING_OF_THE_MANUAL_EXTERNAL_SOURCE_FOLDERS_IS_EMPTY')); + $selection = SermondistributorHelper::getExternalSourceLink('manual', 2, false, 'select'); + if (SermondistributorHelper::checkArray($selection)) { - if ($this->multiple === false) + $options = array(); + foreach ($selection as $key => $name) { - $options[] = JHtml::_('select.option', '', JText::_('COM_SERMONDISTRIBUTOR_SELECT_AN_ADMIN_VIEW')); - } - foreach ($folders as $folder) - { - $options[] = JHtml::_('select.option', $folder, SermondistributorHelper::safeString($folder, 'W')); + $options[] = Html::_('select.option', $key, $name); } } return $options; diff --git a/admin/models/fields/externalsourcesfilterbuild.php b/admin/src/Field/ExternalsourcesfilterbuildField.php similarity index 67% rename from admin/models/fields/externalsourcesfilterbuild.php rename to admin/src/Field/ExternalsourcesfilterbuildField.php index 8fbc1a54..2edf6a0d 100644 --- a/admin/models/fields/externalsourcesfilterbuild.php +++ b/admin/src/Field/ExternalsourcesfilterbuildField.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage externalsourcesfilterbuild.php + @subpackage ExternalsourcesfilterbuildField.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,35 +21,42 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -// import the list field type -jimport('joomla.form.helper'); -JFormHelper::loadFieldClass('list'); +\defined('_JEXEC') or die; /** * Externalsourcesfilterbuild Form Field class for the Sermondistributor component + * + * @since 1.6 */ -class JFormFieldExternalsourcesfilterbuild extends JFormFieldList +class ExternalsourcesfilterbuildField extends ListField { /** * The externalsourcesfilterbuild field type. * - * @var string + * @var string */ - public $type = 'externalsourcesfilterbuild'; + public $type = 'Externalsourcesfilterbuild'; /** * Method to get a list of options for a list input. * - * @return array An array of JHtml options. + * @return array An array of Html options. + * @since 1.6 */ protected function getOptions() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class); // Create a new query object. $query = $db->getQuery(true); @@ -62,21 +69,21 @@ class JFormFieldExternalsourcesfilterbuild extends JFormFieldList // Reset the query using our newly populated query object. $db->setQuery($query); - $results = $db->loadColumn(); - $_filter = array(); - $_filter[] = JHtml::_('select.option', '', '- ' . JText::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_BUILD_OPTION') . ' -'); + $_results = $db->loadColumn(); + $_filter = []; + $_filter[] = Html::_('select.option', '', '- ' . Text::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_BUILD_OPTION') . ' -'); - if ($results) + if ($_results) { // get external_sourcesmodel - $model = SermondistributorHelper::getModel('external_sources'); - $results = array_unique($results); - foreach ($results as $build) + $_model = SermondistributorHelper::getModel('external_sources'); + $_results = array_unique($_results); + foreach ($_results as $build) { // Translate the build selection - $text = $model->selectionTranslation($build,'build'); + $_text = $_model->selectionTranslation($build,'build'); // Now add the build and its text to the options array - $_filter[] = JHtml::_('select.option', $build, JText::_($text)); + $_filter[] = Html::_('select.option', $build, Text::_($_text)); } } return $_filter; diff --git a/admin/models/fields/externalsourcesfilterexternalsources.php b/admin/src/Field/ExternalsourcesfilterexternalsourcesField.php similarity index 66% rename from admin/models/fields/externalsourcesfilterexternalsources.php rename to admin/src/Field/ExternalsourcesfilterexternalsourcesField.php index 4579ce75..7bcc7716 100644 --- a/admin/models/fields/externalsourcesfilterexternalsources.php +++ b/admin/src/Field/ExternalsourcesfilterexternalsourcesField.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage externalsourcesfilterexternalsources.php + @subpackage ExternalsourcesfilterexternalsourcesField.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,35 +21,42 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -// import the list field type -jimport('joomla.form.helper'); -JFormHelper::loadFieldClass('list'); +\defined('_JEXEC') or die; /** * Externalsourcesfilterexternalsources Form Field class for the Sermondistributor component + * + * @since 1.6 */ -class JFormFieldExternalsourcesfilterexternalsources extends JFormFieldList +class ExternalsourcesfilterexternalsourcesField extends ListField { /** * The externalsourcesfilterexternalsources field type. * - * @var string + * @var string */ - public $type = 'externalsourcesfilterexternalsources'; + public $type = 'Externalsourcesfilterexternalsources'; /** * Method to get a list of options for a list input. * - * @return array An array of JHtml options. + * @return array An array of Html options. + * @since 1.6 */ protected function getOptions() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class); // Create a new query object. $query = $db->getQuery(true); @@ -62,21 +69,21 @@ class JFormFieldExternalsourcesfilterexternalsources extends JFormFieldList // Reset the query using our newly populated query object. $db->setQuery($query); - $results = $db->loadColumn(); - $_filter = array(); - $_filter[] = JHtml::_('select.option', '', '- ' . JText::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_EXTERNAL_SOURCES') . ' -'); + $_results = $db->loadColumn(); + $_filter = []; + $_filter[] = Html::_('select.option', '', '- ' . Text::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_EXTERNAL_SOURCES') . ' -'); - if ($results) + if ($_results) { // get external_sourcesmodel - $model = SermondistributorHelper::getModel('external_sources'); - $results = array_unique($results); - foreach ($results as $externalsources) + $_model = SermondistributorHelper::getModel('external_sources'); + $_results = array_unique($_results); + foreach ($_results as $externalsources) { // Translate the externalsources selection - $text = $model->selectionTranslation($externalsources,'externalsources'); + $_text = $_model->selectionTranslation($externalsources,'externalsources'); // Now add the externalsources and its text to the options array - $_filter[] = JHtml::_('select.option', $externalsources, JText::_($text)); + $_filter[] = Html::_('select.option', $externalsources, Text::_($_text)); } } return $_filter; diff --git a/admin/models/fields/externalsourcesfilterupdatemethod.php b/admin/src/Field/ExternalsourcesfilterupdatemethodField.php similarity index 66% rename from admin/models/fields/externalsourcesfilterupdatemethod.php rename to admin/src/Field/ExternalsourcesfilterupdatemethodField.php index 05947981..93f266bf 100644 --- a/admin/models/fields/externalsourcesfilterupdatemethod.php +++ b/admin/src/Field/ExternalsourcesfilterupdatemethodField.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage externalsourcesfilterupdatemethod.php + @subpackage ExternalsourcesfilterupdatemethodField.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,35 +21,42 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -// import the list field type -jimport('joomla.form.helper'); -JFormHelper::loadFieldClass('list'); +\defined('_JEXEC') or die; /** * Externalsourcesfilterupdatemethod Form Field class for the Sermondistributor component + * + * @since 1.6 */ -class JFormFieldExternalsourcesfilterupdatemethod extends JFormFieldList +class ExternalsourcesfilterupdatemethodField extends ListField { /** * The externalsourcesfilterupdatemethod field type. * - * @var string + * @var string */ - public $type = 'externalsourcesfilterupdatemethod'; + public $type = 'Externalsourcesfilterupdatemethod'; /** * Method to get a list of options for a list input. * - * @return array An array of JHtml options. + * @return array An array of Html options. + * @since 1.6 */ protected function getOptions() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class); // Create a new query object. $query = $db->getQuery(true); @@ -62,21 +69,21 @@ class JFormFieldExternalsourcesfilterupdatemethod extends JFormFieldList // Reset the query using our newly populated query object. $db->setQuery($query); - $results = $db->loadColumn(); - $_filter = array(); - $_filter[] = JHtml::_('select.option', '', '- ' . JText::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_UPDATE_METHOD') . ' -'); + $_results = $db->loadColumn(); + $_filter = []; + $_filter[] = Html::_('select.option', '', '- ' . Text::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_UPDATE_METHOD') . ' -'); - if ($results) + if ($_results) { // get external_sourcesmodel - $model = SermondistributorHelper::getModel('external_sources'); - $results = array_unique($results); - foreach ($results as $update_method) + $_model = SermondistributorHelper::getModel('external_sources'); + $_results = array_unique($_results); + foreach ($_results as $update_method) { // Translate the update_method selection - $text = $model->selectionTranslation($update_method,'update_method'); + $_text = $_model->selectionTranslation($update_method,'update_method'); // Now add the update_method and its text to the options array - $_filter[] = JHtml::_('select.option', $update_method, JText::_($text)); + $_filter[] = Html::_('select.option', $update_method, Text::_($_text)); } } return $_filter; diff --git a/admin/models/fields/helpdocumentsfilterlocation.php b/admin/src/Field/HelpdocumentsfilterlocationField.php similarity index 67% rename from admin/models/fields/helpdocumentsfilterlocation.php rename to admin/src/Field/HelpdocumentsfilterlocationField.php index ef6a8811..cbd7f7f1 100644 --- a/admin/models/fields/helpdocumentsfilterlocation.php +++ b/admin/src/Field/HelpdocumentsfilterlocationField.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage helpdocumentsfilterlocation.php + @subpackage HelpdocumentsfilterlocationField.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,35 +21,42 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -// import the list field type -jimport('joomla.form.helper'); -JFormHelper::loadFieldClass('list'); +\defined('_JEXEC') or die; /** * Helpdocumentsfilterlocation Form Field class for the Sermondistributor component + * + * @since 1.6 */ -class JFormFieldHelpdocumentsfilterlocation extends JFormFieldList +class HelpdocumentsfilterlocationField extends ListField { /** * The helpdocumentsfilterlocation field type. * - * @var string + * @var string */ - public $type = 'helpdocumentsfilterlocation'; + public $type = 'Helpdocumentsfilterlocation'; /** * Method to get a list of options for a list input. * - * @return array An array of JHtml options. + * @return array An array of Html options. + * @since 1.6 */ protected function getOptions() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class); // Create a new query object. $query = $db->getQuery(true); @@ -62,21 +69,21 @@ class JFormFieldHelpdocumentsfilterlocation extends JFormFieldList // Reset the query using our newly populated query object. $db->setQuery($query); - $results = $db->loadColumn(); - $_filter = array(); - $_filter[] = JHtml::_('select.option', '', '- ' . JText::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_LOCATION') . ' -'); + $_results = $db->loadColumn(); + $_filter = []; + $_filter[] = Html::_('select.option', '', '- ' . Text::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_LOCATION') . ' -'); - if ($results) + if ($_results) { // get help_documentsmodel - $model = SermondistributorHelper::getModel('help_documents'); - $results = array_unique($results); - foreach ($results as $location) + $_model = SermondistributorHelper::getModel('help_documents'); + $_results = array_unique($_results); + foreach ($_results as $location) { // Translate the location selection - $text = $model->selectionTranslation($location,'location'); + $_text = $_model->selectionTranslation($location,'location'); // Now add the location and its text to the options array - $_filter[] = JHtml::_('select.option', $location, JText::_($text)); + $_filter[] = Html::_('select.option', $location, Text::_($_text)); } } return $_filter; diff --git a/admin/models/fields/helpdocumentsfiltertype.php b/admin/src/Field/HelpdocumentsfiltertypeField.php similarity index 67% rename from admin/models/fields/helpdocumentsfiltertype.php rename to admin/src/Field/HelpdocumentsfiltertypeField.php index c753f8ce..644c6523 100644 --- a/admin/models/fields/helpdocumentsfiltertype.php +++ b/admin/src/Field/HelpdocumentsfiltertypeField.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage helpdocumentsfiltertype.php + @subpackage HelpdocumentsfiltertypeField.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,35 +21,42 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -// import the list field type -jimport('joomla.form.helper'); -JFormHelper::loadFieldClass('list'); +\defined('_JEXEC') or die; /** * Helpdocumentsfiltertype Form Field class for the Sermondistributor component + * + * @since 1.6 */ -class JFormFieldHelpdocumentsfiltertype extends JFormFieldList +class HelpdocumentsfiltertypeField extends ListField { /** * The helpdocumentsfiltertype field type. * - * @var string + * @var string */ - public $type = 'helpdocumentsfiltertype'; + public $type = 'Helpdocumentsfiltertype'; /** * Method to get a list of options for a list input. * - * @return array An array of JHtml options. + * @return array An array of Html options. + * @since 1.6 */ protected function getOptions() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class); // Create a new query object. $query = $db->getQuery(true); @@ -62,21 +69,21 @@ class JFormFieldHelpdocumentsfiltertype extends JFormFieldList // Reset the query using our newly populated query object. $db->setQuery($query); - $results = $db->loadColumn(); - $_filter = array(); - $_filter[] = JHtml::_('select.option', '', '- ' . JText::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_TYPE') . ' -'); + $_results = $db->loadColumn(); + $_filter = []; + $_filter[] = Html::_('select.option', '', '- ' . Text::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_TYPE') . ' -'); - if ($results) + if ($_results) { // get help_documentsmodel - $model = SermondistributorHelper::getModel('help_documents'); - $results = array_unique($results); - foreach ($results as $type) + $_model = SermondistributorHelper::getModel('help_documents'); + $_results = array_unique($_results); + foreach ($_results as $type) { // Translate the type selection - $text = $model->selectionTranslation($type,'type'); + $_text = $_model->selectionTranslation($type,'type'); // Now add the type and its text to the options array - $_filter[] = JHtml::_('select.option', $type, JText::_($text)); + $_filter[] = Html::_('select.option', $type, Text::_($_text)); } } return $_filter; diff --git a/admin/src/Field/LocalfilesField.php b/admin/src/Field/LocalfilesField.php new file mode 100644 index 00000000..920442a8 --- /dev/null +++ b/admin/src/Field/LocalfilesField.php @@ -0,0 +1,78 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Localfiles Form Field class for the Sermondistributor component + * + * @since 1.6 + */ +class LocalfilesField extends ListField +{ + /** + * The localfiles field type. + * + * @var string + */ + public $type = 'Localfiles'; + + /** + * Method to get a list of options for a list input. + * + * @return array An array of Html options. + * @since 1.6 + */ + protected function getOptions() + { + // get local folder + $localfolder = \Joomla\CMS\Component\ComponentHelper::getParams('com_sermondistributor')->get('localfolder', JPATH_ROOT.'/images'); + // set the default + $options[] = Html::_('select.option', '', Text::sprintf('COM_SERMONDISTRIBUTOR_PLEASE_ADD_FILES_TO_S', $localfolder)); + // setup the folder if it does not exist + if (!\Joomla\CMS\Filesystem\Folder::exists($localfolder)) + { + \Joomla\CMS\Filesystem\Folder::create($localfolder); + } + // now check if there are files in the folder + if ($files = \Joomla\CMS\Filesystem\Folder::files($localfolder)) + { + $options = array(); + foreach ($files as $file) + { + $options[] = Html::_('select.option', $file, $file); + } + } + return $options; + } +} diff --git a/admin/models/fields/locallistingsfilterbuild.php b/admin/src/Field/LocallistingsfilterbuildField.php similarity index 67% rename from admin/models/fields/locallistingsfilterbuild.php rename to admin/src/Field/LocallistingsfilterbuildField.php index 3b02ab34..d67e3ca6 100644 --- a/admin/models/fields/locallistingsfilterbuild.php +++ b/admin/src/Field/LocallistingsfilterbuildField.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage locallistingsfilterbuild.php + @subpackage LocallistingsfilterbuildField.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,35 +21,42 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -// import the list field type -jimport('joomla.form.helper'); -JFormHelper::loadFieldClass('list'); +\defined('_JEXEC') or die; /** * Locallistingsfilterbuild Form Field class for the Sermondistributor component + * + * @since 1.6 */ -class JFormFieldLocallistingsfilterbuild extends JFormFieldList +class LocallistingsfilterbuildField extends ListField { /** * The locallistingsfilterbuild field type. * - * @var string + * @var string */ - public $type = 'locallistingsfilterbuild'; + public $type = 'Locallistingsfilterbuild'; /** * Method to get a list of options for a list input. * - * @return array An array of JHtml options. + * @return array An array of Html options. + * @since 1.6 */ protected function getOptions() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class); // Create a new query object. $query = $db->getQuery(true); @@ -62,21 +69,21 @@ class JFormFieldLocallistingsfilterbuild extends JFormFieldList // Reset the query using our newly populated query object. $db->setQuery($query); - $results = $db->loadColumn(); - $_filter = array(); - $_filter[] = JHtml::_('select.option', '', '- ' . JText::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_BUILD_OPTION') . ' -'); + $_results = $db->loadColumn(); + $_filter = []; + $_filter[] = Html::_('select.option', '', '- ' . Text::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_BUILD_OPTION') . ' -'); - if ($results) + if ($_results) { // get local_listingsmodel - $model = SermondistributorHelper::getModel('local_listings'); - $results = array_unique($results); - foreach ($results as $build) + $_model = SermondistributorHelper::getModel('local_listings'); + $_results = array_unique($_results); + foreach ($_results as $build) { // Translate the build selection - $text = $model->selectionTranslation($build,'build'); + $_text = $_model->selectionTranslation($build,'build'); // Now add the build and its text to the options array - $_filter[] = JHtml::_('select.option', $build, JText::_($text)); + $_filter[] = Html::_('select.option', $build, Text::_($_text)); } } return $_filter; diff --git a/admin/src/Field/PreachersField.php b/admin/src/Field/PreachersField.php new file mode 100644 index 00000000..c01847e2 --- /dev/null +++ b/admin/src/Field/PreachersField.php @@ -0,0 +1,188 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Preachers Form Field class for the Sermondistributor component + * + * @since 1.6 + */ +class PreachersField extends ListField +{ + /** + * The preachers field type. + * + * @var string + */ + public $type = 'Preachers'; + + /** + * Override to add new button + * + * @return string The field input markup. + * + * @since 3.2 + */ + protected function getInput() + { + // see if we should add buttons + $set_button = $this->getAttribute('button'); + // get html + $html = parent::getInput(); + // if true set button + if ($set_button === 'true') + { + $button = array(); + $script = array(); + $button_code_name = $this->getAttribute('name'); + // get the input from url + $app = Factory::getApplication(); + $jinput = $app->input; + // get the view name & id + $values = $jinput->getArray(array( + 'id' => 'int', + 'view' => 'word' + )); + // check if new item + $ref = ''; + $refJ = ''; + if (!is_null($values['id']) && strlen($values['view'])) + { + // only load referral if not new item. + $ref = '&ref=' . $values['view'] . '&refid=' . $values['id']; + $refJ = '&ref=' . $values['view'] . '&refid=' . $values['id']; + // get the return value. + $_uri = (string) \Joomla\CMS\Uri\Uri::getInstance(); + $_return = urlencode(base64_encode($_uri)); + // load return value. + $ref .= '&return=' . $_return; + $refJ .= '&return=' . $_return; + } + // get button label + $button_label = trim($button_code_name); + $button_label = preg_replace('/_+/', ' ', $button_label); + $button_label = preg_replace('/\s+/', ' ', $button_label); + $button_label = preg_replace("/[^A-Za-z ]/", '', $button_label); + $button_label = ucfirst(strtolower($button_label)); + // get user object + $user = Factory::getApplication()->getIdentity(); + // only add if user allowed to create preacher + if ($user->authorise('preacher.create', 'com_sermondistributor') && $app->isClient('administrator')) // TODO for now only in admin area. + { + // build Create button + $button[] = ' + '; + } + // only add if user allowed to edit preacher + if ($user->authorise('preacher.edit', 'com_sermondistributor') && $app->isClient('administrator')) // TODO for now only in admin area. + { + // build edit button + $button[] = ''; + // build script + $script[] = " + document.addEventListener('DOMContentLoaded', function() { + document.getElementById('jform_".$button_code_name."').addEventListener('change', function(e) { + e.preventDefault(); + let ".$button_code_name."Value = this.value; + ".$button_code_name."Button(".$button_code_name."Value); + }); + let ".$button_code_name."Value = document.getElementById('jform_".$button_code_name."').value; + ".$button_code_name."Button(".$button_code_name."Value); + }); + function ".$button_code_name."Button(value) { + var createButton = document.getElementById('".$button_code_name."Create'); + var editButton = document.getElementById('".$button_code_name."Edit'); + if (value > 0) { + // hide the create button + createButton.style.display = 'none'; + // show edit button + editButton.style.display = 'block'; + let url = 'index.php?option=com_sermondistributor&view=preachers&task=preacher.edit&id='+value+'".$refJ."'; + editButton.setAttribute('href', url); + } else { + // show the create button + createButton.style.display = 'block'; + // hide edit button + editButton.style.display = 'none'; + } + }"; + } + // check if button was created for preacher field. + if (is_array($button) && count($button) > 0) + { + // Load the needed script. + $document = Factory::getApplication()->getDocument(); + $document->addScriptDeclaration(implode(' ',$script)); + // return the button attached to input field. + return '
' .$html . implode('',$button).'
'; + } + } + return $html; + } + + /** + * Method to get a list of options for a list input. + * + * @return array An array of Html options. + * @since 1.6 + */ + protected function getOptions() + { + // Get the database object. + $db = Factory::getDBO(); + $query = $db->getQuery(true); + $query->select($db->quoteName(array('a.id','a.name'),array('id','preacher_name'))); + $query->from($db->quoteName('#__sermondistributor_preacher', 'a')); + $query->where($db->quoteName('a.published') . ' = 1'); + $query->order('a.name ASC'); + $db->setQuery((string)$query); + $items = $db->loadObjectList(); + $options = array(); + if ($items) + { + if ($this->multiple === false) + { + $options[] = Html::_('select.option', '', Text::_('COM_SERMONDISTRIBUTOR_SELECT_A_PREACHER')); + } + foreach($items as $item) + { + $options[] = Html::_('select.option', $item->id, $item->preacher_name); + } + } + + return $options; + } +} diff --git a/admin/src/Field/SeriesField.php b/admin/src/Field/SeriesField.php new file mode 100644 index 00000000..cbea9125 --- /dev/null +++ b/admin/src/Field/SeriesField.php @@ -0,0 +1,188 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Series Form Field class for the Sermondistributor component + * + * @since 1.6 + */ +class SeriesField extends ListField +{ + /** + * The series field type. + * + * @var string + */ + public $type = 'Series'; + + /** + * Override to add new button + * + * @return string The field input markup. + * + * @since 3.2 + */ + protected function getInput() + { + // see if we should add buttons + $set_button = $this->getAttribute('button'); + // get html + $html = parent::getInput(); + // if true set button + if ($set_button === 'true') + { + $button = array(); + $script = array(); + $button_code_name = $this->getAttribute('name'); + // get the input from url + $app = Factory::getApplication(); + $jinput = $app->input; + // get the view name & id + $values = $jinput->getArray(array( + 'id' => 'int', + 'view' => 'word' + )); + // check if new item + $ref = ''; + $refJ = ''; + if (!is_null($values['id']) && strlen($values['view'])) + { + // only load referral if not new item. + $ref = '&ref=' . $values['view'] . '&refid=' . $values['id']; + $refJ = '&ref=' . $values['view'] . '&refid=' . $values['id']; + // get the return value. + $_uri = (string) \Joomla\CMS\Uri\Uri::getInstance(); + $_return = urlencode(base64_encode($_uri)); + // load return value. + $ref .= '&return=' . $_return; + $refJ .= '&return=' . $_return; + } + // get button label + $button_label = trim($button_code_name); + $button_label = preg_replace('/_+/', ' ', $button_label); + $button_label = preg_replace('/\s+/', ' ', $button_label); + $button_label = preg_replace("/[^A-Za-z ]/", '', $button_label); + $button_label = ucfirst(strtolower($button_label)); + // get user object + $user = Factory::getApplication()->getIdentity(); + // only add if user allowed to create series + if ($user->authorise('series.create', 'com_sermondistributor') && $app->isClient('administrator')) // TODO for now only in admin area. + { + // build Create button + $button[] = ' + '; + } + // only add if user allowed to edit series + if ($user->authorise('series.edit', 'com_sermondistributor') && $app->isClient('administrator')) // TODO for now only in admin area. + { + // build edit button + $button[] = ''; + // build script + $script[] = " + document.addEventListener('DOMContentLoaded', function() { + document.getElementById('jform_".$button_code_name."').addEventListener('change', function(e) { + e.preventDefault(); + let ".$button_code_name."Value = this.value; + ".$button_code_name."Button(".$button_code_name."Value); + }); + let ".$button_code_name."Value = document.getElementById('jform_".$button_code_name."').value; + ".$button_code_name."Button(".$button_code_name."Value); + }); + function ".$button_code_name."Button(value) { + var createButton = document.getElementById('".$button_code_name."Create'); + var editButton = document.getElementById('".$button_code_name."Edit'); + if (value > 0) { + // hide the create button + createButton.style.display = 'none'; + // show edit button + editButton.style.display = 'block'; + let url = 'index.php?option=com_sermondistributor&view=all_series&task=series.edit&id='+value+'".$refJ."'; + editButton.setAttribute('href', url); + } else { + // show the create button + createButton.style.display = 'block'; + // hide edit button + editButton.style.display = 'none'; + } + }"; + } + // check if button was created for series field. + if (is_array($button) && count($button) > 0) + { + // Load the needed script. + $document = Factory::getApplication()->getDocument(); + $document->addScriptDeclaration(implode(' ',$script)); + // return the button attached to input field. + return '
' .$html . implode('',$button).'
'; + } + } + return $html; + } + + /** + * Method to get a list of options for a list input. + * + * @return array An array of Html options. + * @since 1.6 + */ + protected function getOptions() + { + // Get the database object. + $db = Factory::getDBO(); + $query = $db->getQuery(true); + $query->select($db->quoteName(array('a.id','a.name'),array('id','series_name'))); + $query->from($db->quoteName('#__sermondistributor_series', 'a')); + $query->where($db->quoteName('a.published') . ' = 1'); + $query->order('a.name ASC'); + $db->setQuery((string)$query); + $items = $db->loadObjectList(); + $options = array(); + if ($items) + { + if ($this->multiple === false) + { + $options[] = Html::_('select.option', '', Text::_('COM_SERMONDISTRIBUTOR_SELECT_A_SERIES')); + } + foreach($items as $item) + { + $options[] = Html::_('select.option', $item->id, $item->series_name); + } + } + + return $options; + } +} diff --git a/admin/src/Field/SermonField.php b/admin/src/Field/SermonField.php new file mode 100644 index 00000000..391aa758 --- /dev/null +++ b/admin/src/Field/SermonField.php @@ -0,0 +1,183 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermon Form Field class for the Sermondistributor component + * + * @since 1.6 + */ +class SermonField extends ListField +{ + /** + * The sermon field type. + * + * @var string + */ + public $type = 'Sermon'; + + /** + * Override to add new button + * + * @return string The field input markup. + * + * @since 3.2 + */ + protected function getInput() + { + // see if we should add buttons + $set_button = $this->getAttribute('button'); + // get html + $html = parent::getInput(); + // if true set button + if ($set_button === 'true') + { + $button = array(); + $script = array(); + $button_code_name = $this->getAttribute('name'); + // get the input from url + $app = Factory::getApplication(); + $jinput = $app->input; + // get the view name & id + $values = $jinput->getArray(array( + 'id' => 'int', + 'view' => 'word' + )); + // check if new item + $ref = ''; + $refJ = ''; + if (!is_null($values['id']) && strlen($values['view'])) + { + // only load referral if not new item. + $ref = '&ref=' . $values['view'] . '&refid=' . $values['id']; + $refJ = '&ref=' . $values['view'] . '&refid=' . $values['id']; + // get the return value. + $_uri = (string) \Joomla\CMS\Uri\Uri::getInstance(); + $_return = urlencode(base64_encode($_uri)); + // load return value. + $ref .= '&return=' . $_return; + $refJ .= '&return=' . $_return; + } + // get button label + $button_label = trim($button_code_name); + $button_label = preg_replace('/_+/', ' ', $button_label); + $button_label = preg_replace('/\s+/', ' ', $button_label); + $button_label = preg_replace("/[^A-Za-z ]/", '', $button_label); + $button_label = ucfirst(strtolower($button_label)); + // get user object + $user = Factory::getApplication()->getIdentity(); + // only add if user allowed to create sermon + if ($user->authorise('sermon.create', 'com_sermondistributor') && $app->isClient('administrator')) // TODO for now only in admin area. + { + // build Create button + $button[] = ' + '; + } + // only add if user allowed to edit sermon + if ($user->authorise('sermon.edit', 'com_sermondistributor') && $app->isClient('administrator')) // TODO for now only in admin area. + { + // build edit button + $button[] = ''; + // build script + $script[] = " + document.addEventListener('DOMContentLoaded', function() { + document.getElementById('jform_".$button_code_name."').addEventListener('change', function(e) { + e.preventDefault(); + let ".$button_code_name."Value = this.value; + ".$button_code_name."Button(".$button_code_name."Value); + }); + let ".$button_code_name."Value = document.getElementById('jform_".$button_code_name."').value; + ".$button_code_name."Button(".$button_code_name."Value); + }); + function ".$button_code_name."Button(value) { + var createButton = document.getElementById('".$button_code_name."Create'); + var editButton = document.getElementById('".$button_code_name."Edit'); + if (value > 0) { + // hide the create button + createButton.style.display = 'none'; + // show edit button + editButton.style.display = 'block'; + let url = 'index.php?option=com_sermondistributor&view=sermons&task=sermon.edit&id='+value+'".$refJ."'; + editButton.setAttribute('href', url); + } else { + // show the create button + createButton.style.display = 'block'; + // hide edit button + editButton.style.display = 'none'; + } + }"; + } + // check if button was created for sermon field. + if (is_array($button) && count($button) > 0) + { + // Load the needed script. + $document = Factory::getApplication()->getDocument(); + $document->addScriptDeclaration(implode(' ',$script)); + // return the button attached to input field. + return '
' .$html . implode('',$button).'
'; + } + } + return $html; + } + + /** + * Method to get a list of options for a list input. + * + * @return array An array of Html options. + * @since 1.6 + */ + protected function getOptions() + { + $db = Factory::getDBO(); + $query = $db->getQuery(true); + $query->select($db->quoteName(array('a.id','a.name'),array('id','sermon_name'))); + $query->from($db->quoteName('#__sermondistributor_sermon', 'a')); + $query->where($db->quoteName('a.published') . ' = 1'); + $query->order('a.name ASC'); + $db->setQuery((string)$query); + $items = $db->loadObjectList(); + $options = array(); + if ($items) + { + $options[] = Html::_('select.option', '', 'Select a sermon'); + foreach($items as $item) + { + $options[] = Html::_('select.option', $item->id, $item->sermon_name); + } + } + return $options; + } +} diff --git a/admin/models/fields/sermonsfilterlinktype.php b/admin/src/Field/SermonsfilterlinktypeField.php similarity index 67% rename from admin/models/fields/sermonsfilterlinktype.php rename to admin/src/Field/SermonsfilterlinktypeField.php index 1ca8cae0..d332618d 100644 --- a/admin/models/fields/sermonsfilterlinktype.php +++ b/admin/src/Field/SermonsfilterlinktypeField.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage sermonsfilterlinktype.php + @subpackage SermonsfilterlinktypeField.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,35 +21,42 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -// import the list field type -jimport('joomla.form.helper'); -JFormHelper::loadFieldClass('list'); +\defined('_JEXEC') or die; /** * Sermonsfilterlinktype Form Field class for the Sermondistributor component + * + * @since 1.6 */ -class JFormFieldSermonsfilterlinktype extends JFormFieldList +class SermonsfilterlinktypeField extends ListField { /** * The sermonsfilterlinktype field type. * - * @var string + * @var string */ - public $type = 'sermonsfilterlinktype'; + public $type = 'Sermonsfilterlinktype'; /** * Method to get a list of options for a list input. * - * @return array An array of JHtml options. + * @return array An array of Html options. + * @since 1.6 */ protected function getOptions() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class); // Create a new query object. $query = $db->getQuery(true); @@ -62,21 +69,21 @@ class JFormFieldSermonsfilterlinktype extends JFormFieldList // Reset the query using our newly populated query object. $db->setQuery($query); - $results = $db->loadColumn(); - $_filter = array(); - $_filter[] = JHtml::_('select.option', '', '- ' . JText::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_DOWNLOAD_LINK_OPTION') . ' -'); + $_results = $db->loadColumn(); + $_filter = []; + $_filter[] = Html::_('select.option', '', '- ' . Text::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_DOWNLOAD_LINK_OPTION') . ' -'); - if ($results) + if ($_results) { // get sermonsmodel - $model = SermondistributorHelper::getModel('sermons'); - $results = array_unique($results); - foreach ($results as $link_type) + $_model = SermondistributorHelper::getModel('sermons'); + $_results = array_unique($_results); + foreach ($_results as $link_type) { // Translate the link_type selection - $text = $model->selectionTranslation($link_type,'link_type'); + $_text = $_model->selectionTranslation($link_type,'link_type'); // Now add the link_type and its text to the options array - $_filter[] = JHtml::_('select.option', $link_type, JText::_($text)); + $_filter[] = Html::_('select.option', $link_type, Text::_($_text)); } } return $_filter; diff --git a/admin/models/fields/sermonsfiltersource.php b/admin/src/Field/SermonsfiltersourceField.php similarity index 67% rename from admin/models/fields/sermonsfiltersource.php rename to admin/src/Field/SermonsfiltersourceField.php index 93da4c4f..a99cc3b4 100644 --- a/admin/models/fields/sermonsfiltersource.php +++ b/admin/src/Field/SermonsfiltersourceField.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage sermonsfiltersource.php + @subpackage SermonsfiltersourceField.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,35 +21,42 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -// import the list field type -jimport('joomla.form.helper'); -JFormHelper::loadFieldClass('list'); +\defined('_JEXEC') or die; /** * Sermonsfiltersource Form Field class for the Sermondistributor component + * + * @since 1.6 */ -class JFormFieldSermonsfiltersource extends JFormFieldList +class SermonsfiltersourceField extends ListField { /** * The sermonsfiltersource field type. * - * @var string + * @var string */ - public $type = 'sermonsfiltersource'; + public $type = 'Sermonsfiltersource'; /** * Method to get a list of options for a list input. * - * @return array An array of JHtml options. + * @return array An array of Html options. + * @since 1.6 */ protected function getOptions() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class); // Create a new query object. $query = $db->getQuery(true); @@ -62,21 +69,21 @@ class JFormFieldSermonsfiltersource extends JFormFieldList // Reset the query using our newly populated query object. $db->setQuery($query); - $results = $db->loadColumn(); - $_filter = array(); - $_filter[] = JHtml::_('select.option', '', '- ' . JText::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_FILE_SOURCE') . ' -'); + $_results = $db->loadColumn(); + $_filter = []; + $_filter[] = Html::_('select.option', '', '- ' . Text::_('COM_SERMONDISTRIBUTOR_FILTER_SELECT_FILE_SOURCE') . ' -'); - if ($results) + if ($_results) { // get sermonsmodel - $model = SermondistributorHelper::getModel('sermons'); - $results = array_unique($results); - foreach ($results as $source) + $_model = SermondistributorHelper::getModel('sermons'); + $_results = array_unique($_results); + foreach ($_results as $source) { // Translate the source selection - $text = $model->selectionTranslation($source,'source'); + $_text = $_model->selectionTranslation($source,'source'); // Now add the source and its text to the options array - $_filter[] = JHtml::_('select.option', $source, JText::_($text)); + $_filter[] = Html::_('select.option', $source, Text::_($_text)); } } return $_filter; diff --git a/admin/src/Field/SiteviewfolderlistField.php b/admin/src/Field/SiteviewfolderlistField.php new file mode 100644 index 00000000..1bbc08ef --- /dev/null +++ b/admin/src/Field/SiteviewfolderlistField.php @@ -0,0 +1,82 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Field; + +use Joomla\CMS\Factory; +use Joomla\CMS\Form\Field\ListField; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Component\ComponentHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Siteviewfolderlist Form Field class for the Sermondistributor component + * + * @since 1.6 + */ +class SiteviewfolderlistField extends ListField +{ + /** + * The siteviewfolderlist field type. + * + * @var string + */ + public $type = 'Siteviewfolderlist'; + + /** + * Method to get a list of options for a list input. + * + * @return array An array of Html options. + * @since 1.6 + */ + protected function getOptions() + { + // get custom folder files + $localfolders = []; + $localfolders[] = JPATH_SITE . '/components/com_sermondistributor/views'; + $localfolders[] = JPATH_SITE . '/components/com_sermondistributor/src/View'; + // set the default + $options = []; + // now check if there are files in the folder + foreach ($localfolders as $localfolder) + { + if (is_dir($localfolder) && $folders = \Joomla\Filesystem\Folder::folders($localfolder)) + { + if ($this->multiple === false) + { + $options[] = Html::_('select.option', '', Text::_('COM_SERMONDISTRIBUTOR_SELECT_A_SITE_VIEW')); + } + foreach ($folders as $folder) + { + $options[] = Html::_('select.option', $folder, StringHelper::safe($folder, 'W')); + } + } + } + return $options; + } +} diff --git a/admin/models/index.html b/admin/src/Field/index.html similarity index 100% rename from admin/models/index.html rename to admin/src/Field/index.html diff --git a/admin/src/Helper/HeaderCheck.php b/admin/src/Helper/HeaderCheck.php new file mode 100644 index 00000000..e6e1d3a8 --- /dev/null +++ b/admin/src/Helper/HeaderCheck.php @@ -0,0 +1,143 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Helper; + +use Joomla\CMS\Factory; +use Joomla\CMS\Document\Document; +use Joomla\CMS\Application\CMSApplication; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Helper class for checking loaded scripts and styles in the document header. + * + * @since 3.2.0 + */ +class HeaderCheck +{ + /** + * @var CMSApplication Application object + * + * @since 3.2.0 + */ + protected CMSApplication $app; + + /** + * @var Document object + * + * @since 3.2.0 + */ + protected Document $document; + + /** + * Construct the app and document + * + * @since 3.2.0 + */ + public function __construct() + { + // Initializes the application object. + $this->app ??= Factory::getApplication(); + + // Initializes the document object. + $this->document = $this->app->getDocument(); + } + + /** + * Check if a JavaScript file is loaded in the document head. + * + * @param string $scriptName Name of the script to check. + * + * @return bool True if the script is loaded, false otherwise. + * @since 3.2.0 + */ + public function js_loaded(string $scriptName): bool + { + return $this->isLoaded($scriptName, 'scripts'); + } + + /** + * Check if a CSS file is loaded in the document head. + * + * @param string $scriptName Name of the stylesheet to check. + * + * @return bool True if the stylesheet is loaded, false otherwise. + * @since 3.2.0 + */ + public function css_loaded(string $scriptName): bool + { + return $this->isLoaded($scriptName, 'styleSheets'); + } + + /** + * Abstract method to check if a given script or stylesheet is loaded. + * + * @param string $scriptName Name of the script or stylesheet. + * @param string $type Type of asset to check ('scripts' or 'styleSheets'). + * + * @return bool True if the asset is loaded, false otherwise. + * @since 3.2.0 + */ + private function isLoaded(string $scriptName, string $type): bool + { + // UIkit specific check + if ($this->isUIkit($scriptName)) + { + return true; + } + + $head_data = $this->document->getHeadData(); + foreach (array_keys($head_data[$type]) as $script) + { + if (stristr($script, $scriptName)) + { + return true; + } + } + + return false; + } + + /** + * Check for UIkit framework specific conditions. + * + * @param string $scriptName Name of the script or stylesheet. + * + * @return bool True if UIkit specific conditions are met, false otherwise. + * @since 3.2.0 + */ + private function isUIkit(string $scriptName): bool + { + if (strpos($scriptName, 'uikit') !== false) + { + $get_template_name = $this->app->getTemplate('template')->template; + if (strpos($get_template_name, 'yoo') !== false) + { + return true; + } + } + return false; + } +} diff --git a/admin/src/Helper/SermondistributorHelper.php b/admin/src/Helper/SermondistributorHelper.php new file mode 100644 index 00000000..1cd86725 --- /dev/null +++ b/admin/src/Helper/SermondistributorHelper.php @@ -0,0 +1,3014 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Helper; + + + +// register additional namespace +\spl_autoload_register(function ($class) { + // project-specific base directories and namespace prefix + $search = [ + 'libraries/jcb_powers/VDM.Joomla.FOF' => 'VDM\\Joomla\\FOF', + 'libraries/jcb_powers/VDM.Joomla' => 'VDM\\Joomla' + ]; + // Start the search and load if found + $found = false; + $found_base_dir = ""; + $found_len = 0; + foreach ($search as $base_dir => $prefix) + { + // does the class use the namespace prefix? + $len = strlen($prefix); + if (strncmp($prefix, $class, $len) === 0) + { + // we have a match so load the values + $found = true; + $found_base_dir = $base_dir; + $found_len = $len; + // done here + break; + } + } + // check if we found a match + if (!$found) + { + // not found so move to the next registered autoloader + return; + } + // get the relative class name + $relative_class = substr($class, $found_len); + // replace the namespace prefix with the base directory, replace namespace + // separators with directory separators in the relative class name, append + // with .php + $file = JPATH_ROOT . '/' . $found_base_dir . '/src' . str_replace('\\', '/', $relative_class) . '.php'; + // if the file exists, require it + if (file_exists($file)) + { + require $file; + } +}); + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Access\Access; +use Joomla\CMS\Access\Rules as AccessRules; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Filesystem\File; +use Joomla\CMS\Language\Language; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Object\CMSObject; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Table\Table; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Version; +use Joomla\Database\DatabaseInterface; +use Joomla\Registry\Registry; +use Joomla\String\StringHelper; +use Joomla\Utilities\ArrayHelper; +use PhpOffice\PhpSpreadsheet\IOFactory; +use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Writer\Xlsx; +use Joomla\CMS\Filesystem\Folder; +use VDM\Joomla\FOF\Encrypt\AES; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\FileHelper; +use VDM\Joomla\Utilities\JsonHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper as UtilitiesStringHelper; +use VDM\Joomla\Utilities\MimeHelper; +use VDM\Joomla\Utilities\GetHelper; +use VDM\Joomla\Utilities\FormHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor component helper. + * + * @since 3.0 + */ +abstract class SermondistributorHelper +{ + /** + * Composer Switch + * + * @var array + */ + protected static $composer = []; + + /** + * The Main Active Language + * + * @var string + */ + public static $langTag; + + /** + * The global params + **/ + protected static $params = false; + + /** + * Update Watcher + **/ + public static $updateWatch = 1; + + /** + * Update Watcher (if array is only one value) + **/ + public static $updateWatch_ = 0; + + /** + * The external source links auto + **/ + protected static $links_externalsource_auto; + + /** + * The external source links manual + **/ + protected static $links_externalsource_manual; + + /** + * The external source selection auto + **/ + protected static $select_externalsource_auto; + + /** + * The external source selection manual + **/ + protected static $select_externalsource_manual; + + /** + * The update errors + **/ + protected static $updateErrors = array(); + + /** + * prepare base64 string for url + * + * @deprecate Use urlencode(); + */ + public static function base64_urlencode($string, $encode = false) + { + if ($encode) + { + $string = base64_encode($string); + } + return str_replace(array('+', '/'), array('-', '_'), $string); + } + + /** + * prepare base64 string form url + * + * @deprecate + */ + public static function base64_urldecode($string, $decode = false) + { + $string = str_replace(array('-', '_'), array('+', '/'), $string); + if ($decode) + { + $string = base64_decode($string); + } + return $string; + } + + /** + * get Download links of a sermon + **/ + public static function getDownloadLinks(&$sermon) + { + $links = array(); + // Get local key + $localkey = self::getLocalKey(); + // decrypt the urls + $safe = new AES($localkey, 128); + // internal download url + $keyCounter = new \stdClass; + $keyCounter->sermon = $sermon->id; + if ($sermon->preacher) + { + $keyCounter->preacher = $sermon->preacher; + } + if ($sermon->series) + { + $keyCounter->series = $sermon->series; + } + $keyCounterRAW = $safe->encryptString(json_encode($keyCounter)); + $keyCounter = self::base64_urlencode($keyCounterRAW); + $token = Session::getFormToken(); + $downloadURL = Uri::root().'index.php?option=com_sermondistributor&task=download.file&key='.$keyCounter.'&token='.$token; + // check if local .htaccess should be set + $setHtaccess = false; + $onclick = ' onclick="sermonCounter(\''.$keyCounterRAW.'\',\'FILENAME\');"'; + // check what source of our link + switch ($sermon->source) + { + case 1: + // local file get local folder and check if outside root (if not then allow direct) + $localFolder = ComponentHelper::getParams('com_sermondistributor')->get('localfolder', JPATH_ROOT.'/images').'/'; + // should we allow direct downloads + $allowDirect = false; + if (2 == $sermon->link_type && strpos($localFolder, JPATH_ROOT) !== false) + { + $allowDirect = true; + $localFolderURL = Uri::root().str_replace(JPATH_ROOT, '', $localFolder); + // insure no double // is in the URL + $localFolderURL = str_replace('//', '/', $localFolderURL); + $localFolderURL = str_replace(':/', '://', $localFolderURL); + } + // insure no double // is in the path name + $localFolder = str_replace('//', '/', $localFolder); + $localFolder = str_replace(':/', '://', $localFolder); + if (UtilitiesArrayHelper::check($sermon->local_files)) + { + foreach($sermon->local_files as $key) + { + if (1 == $sermon->link_type || !$allowDirect) + { + // get the file name use the same method as the auto + $filename = self::getDownloadFileName($sermon,$key,'local'); + $lockedFolderPath = $safe->encryptString($localFolder.$key); + $sermon->download_links[$filename] = $downloadURL.'&link='.self::base64_urlencode($lockedFolderPath).'&filename='.$filename; + $sermon->onclick[$filename] = ''; + } + elseif (2 == $sermon->link_type && $allowDirect) + { + $filename = $key; + $sermon->download_links[$filename] = $localFolderURL.$key; + $sermon->onclick[$filename] = str_replace('FILENAME', $filename, $onclick); + $setHtaccess = true; + } + } + } + break; + case 2: + // Dropbox get global dropbox switch + $addToButton = ComponentHelper::getParams('com_sermondistributor')->get('add_to_button', 0); + if (1 == $sermon->build) + { + if (UtilitiesArrayHelper::check($sermon->manual_files)) + { + // manual dropbox + foreach($sermon->manual_files as $key) + { + // get the link + $dropURL = self::getExternalSourceLink('manual',1,$key); + if (1 == $sermon->link_type && $dropURL) + { + // get the file name use the same method as the auto + $filename = self::getDownloadFileName($sermon,$key,'dropbox_manual'); + // should we encrypt string this string + if ('localKey34fdWEkl' == $localkey || (base64_encode(base64_decode($dropURL, true)) !== $dropURL)) // hmmm no global key has been set + { + $dropURL = $safe->encryptString($dropURL); + } + // lock the info key + $infoKey = $safe->encryptString($key); + $sermon->download_links[$filename] = $downloadURL.'&info='.self::base64_urlencode($infoKey).'&link='.self::base64_urlencode($dropURL).'&filename='.$filename; + $sermon->onclick[$filename] = ''; + } + elseif (2 == $sermon->link_type && $dropURL) + { + $filename = str_replace('VDM_pLeK_h0uEr/', '', $key); + if ('localKey34fdWEkl' == $localkey) // hmmm no global key has been set (so don't decrypt) + { + $sermon->download_links[$filename] = $dropURL; + } + else + { + $sermon->download_links[$filename] = rtrim($safe->decryptString($dropURL), "\0"); + } + $sermon->onclick[$filename] = str_replace('FILENAME', $filename, $onclick); + } + // build dropbox switch if needed + if (1 == $addToButton && $dropURL) + { + if ('localKey34fdWEkl' == $localkey) // hmmm no global key has been set (so don't decrypt) + { + $sermon->dropbox_buttons[$filename] = str_replace('?dl=1', '?dl=0', $dropURL); + } + else + { + $sermon->dropbox_buttons[$filename] = str_replace('?dl=1', '?dl=0', rtrim($safe->decryptString($dropURL), "\0")); + } + $sermon->onclick_drobox[$filename] = str_replace('FILENAME', $filename, $onclick); + } + } + } + } + elseif (2 == $sermon->build) + { + if (UtilitiesArrayHelper::check($sermon->auto_sermons)) + { + // automatic dropbox + foreach($sermon->auto_sermons as $filename => $key) + { + // get the link + $dropURL = self::getExternalSourceLink('auto',1,$key); + if (1 == $sermon->link_type && $dropURL) + { + // should we encrypt string this string + if ('localKey34fdWEkl' == $localkey || (base64_encode(base64_decode($dropURL, true)) !== $dropURL)) // hmmm no global key has been set + { + $dropURL = $safe->encryptString($dropURL); + } + // lock the info key + $infoKey = $safe->encryptString($key); + $sermon->download_links[$filename] = $downloadURL.'&info='.self::base64_urlencode($infoKey).'&link='.self::base64_urlencode($dropURL).'&filename='.$filename; + $sermon->onclick[$filename] = ''; + } + elseif (2 == $sermon->link_type && $dropURL) + { + if ('localKey34fdWEkl' == $localkey) // hmmm no global key has been set (so don't decrypt) + { + $sermon->download_links[$filename] = $dropURL; + } + else + { + $sermon->download_links[$filename] = rtrim($safe->decryptString($dropURL), "\0"); + } + $sermon->onclick[$filename] = str_replace('FILENAME', $filename, $onclick); + } + // build dropbox switch if needed + if (1 == $addToButton && $dropURL) + { + if ('localKey34fdWEkl' == $localkey) // hmmm no global key has been set (so don't decrypt) + { + $sermon->dropbox_buttons[$filename] = str_replace('?dl=1', '?dl=0', $dropURL); + } + else + { + $sermon->dropbox_buttons[$filename] = str_replace('?dl=1', '?dl=0', rtrim($safe->decryptString($dropURL), "\0")); + } + $sermon->onclick_drobox[$filename] = str_replace('FILENAME', $filename, $onclick); + } + } + } + } + break; + case 3: + // url get the file name use the same method as the auto + $filename = self::getDownloadFileName($sermon,$sermon->url,'url'); + if (1 == $sermon->link_type) + { + $lockedURL = $safe->encryptString($sermon->url); + $sermon->download_links[$filename] = $downloadURL.'&link='.self::base64_urlencode($lockedURL).'&filename='.$filename; + $sermon->onclick[$filename] = ''; + } + elseif (2 == $sermon->link_type) + { + $sermon->download_links[$filename] = $sermon->url; + $sermon->onclick[$filename] = str_replace('FILENAME', $filename, $onclick); + } + break; + } + // remove the values no longer needed + unset($sermon->local_files); + unset($sermon->manual_files); + unset($sermon->auto_sermons); + unset($sermon->url); + // should we set the local .htaccess for the download folder + if ($setHtaccess) + { + // TODO we may need to add this latter to enforce download of files. + } + return true; + } + + public static function getNextUpdateValues($asArray = false) + { + // find the next value + $next = false; + // get actual update values + $updates = self::getExternalListingUpdateKeys(); + // get last update + $updatePath = FileHelper::getPath('path', 'updatelast', 'txt', 'vDm', JPATH_COMPONENT_ADMINISTRATOR); + if (($lastUpdate = FileHelper::getContent($updatePath, FALSE)) !== FALSE && UtilitiesArrayHelper::check($updates)) + { + // is it time to watch + if (self::$updateWatch_ > 0) + { + // increment the watch, as this is the start of new round + self::$updateWatch++; + // new round has started + self::$updateWatch_ = 0; + } + // now check what is next + $lastKey = array_search($lastUpdate, $updates); + if (!is_null($lastKey)) + { + $nextKey = $lastKey + 1; + if (isset($updates[$nextKey])) + { + $next = $updates[$nextKey]; + } + else + { + // last item in array, so next round about to start + self::$updateWatch_++; + } + } + } + // rest and start with the first key + if (!$next && UtilitiesArrayHelper::check($updates)) + { + // save the first set + $start = reset($updates); + $next = $start; + } + // save to file if next is found + if ($next) + { + FileHelper::write($updatePath,$next); + // convert to array of needed + if ($asArray) + { + if (strpos($next, ',') !== false) + { + $next = array_map('trim', explode(',', $next)); + } + else + { + return false; + } + } + } + return $next; + } + + /** + * Get the file path or url + * + * @param string $type The (url/path) type to return + * @param string $target The Params Target name (if set) + * @param string $fileType The kind of filename to generate (if not set no file name is generated) + * @param string $key The key to adjust the filename (if not set ignored) + * @param string $default The default path if not set in Params (fallback path) + * @param bool $createIfNotSet The switch to create the folder if not found + * + * @return string On success the path or url is returned based on the type requested + * @deprecated 3.3 Use FileHelper::getPath(...); + */ + public static function getFilePath($type = 'path', $target = 'filepath', $fileType = null, $key = '', $default = '', $createIfNotSet = true) + { + // Get the file path or url + return FileHelper::getPath($type, $target, $fileType, $key, $default, $createIfNotSet); + } + + /** + * Write a file to the server + * + * @param string $path The path and file name where to safe the data + * @param string $data The data to safe + * + * @return bool true On success + * @deprecated 3.3 Use FileHelper::write(...); + */ + public static function writeFile($path, $data) + { + return FileHelper::write($path, $data); + } + protected static function saveFile($data, $path_filename) + { + return FileHelper::write($path_filename, $data); + } + + public static function getExternalListingUpdateKeys($id = null, $updateMethod = 2, $returnType = 1) + { + // first check if this file already has statistics + $db = Factory::getDbo(); + $query = $db->getQuery(true); + $query->select($db->quoteName(array('id','sharedurl','folder','permissiontype','dropboxoptions','build'))); + $query->from($db->quoteName('#__sermondistributor_external_source')); + if ($updateMethod && is_numeric($updateMethod)) + { + $query->where($db->quoteName('update_method') . ' = '. (int) $updateMethod); + } + if ($id && is_numeric($id)) + { + $query->where($db->quoteName('id') . ' = '. (int) $id); + } + elseif ($id && UtilitiesArrayHelper::check($id)) + { + $ids = implode(',', array_map( 'intval', $id)); + $query->where($db->quoteName('id') . ' IN (' . $ids . ')'); + } + $query->where($db->quoteName('published') . ' = 1'); + $db->setQuery($query); + $db->execute(); + if ($db->getNumRows()) + { + $results = $db->loadObjectList(); + $updates = array(); + foreach ($results as $result) + { + if ('full' == $result->permissiontype) + { + // load folder or urls + switch ($result->dropboxoptions) + { + case 1: // sharedurl + if (JsonHelper::check($result->sharedurl)) + { + $targets = json_decode($result->sharedurl)->tsharedurl; + } + break; + case 2: // folders + if (JsonHelper::check($result->folder)) + { + $targets = json_decode($result->folder)->tfolder; + } + break; + } + if (UtilitiesArrayHelper::check($targets)) + { + foreach ($targets as $key => $value) + { + $nr = $key + 1; + // id, target, type + if (1 == $returnType) + { + $updates[] = $result->id . ', '. $nr . ', ' . $result->build; + } + else // only return the targets + { + $updates[] = $nr; + } + } + } + } + else + { + // id, target, type + if (1 == $returnType) + { + $updates[] = $result->id . ', 1, '. $result->build; + } + else // only return the targets + { + $updates[] = 1; + } + } + } + return $updates; + } + return false; + } + + public static function getExternalSourceLink($type, $return = 7, $get = false, $target = 'links') + { + // make sure all defaults are set + $found = self::checkExternalSourceLocalListing($type, $target); + if ($found) + { + switch($return) + { + case 1: + // return a link + if (isset(self::${$target.'_externalsource_'.$type}[$get])) + { + return self::${$target.'_externalsource_'.$type}[$get]; + } + break; + case 2: + // return all links + return self::${$target.'_externalsource_'.$type}; + break; + default : + // just confirm that it is set + return true; + break; + } + } + return false; + } + + public static function countDownload($counter, $filename) + { + // Get local key + $localkey = self::getLocalKey(); + $opener = new AES($localkey, 128); + $counter = json_decode(rtrim($opener->decryptString($counter), "\0")); + if (ObjectHelper::check($counter)) + { + $counter->filename = $filename; + // set the date object + $date = Factory::getDate(); + // first check if this file already has statistics + $db = Factory::getDbo(); + $query = $db->getQuery(true); + $query->select($db->quoteName(array('id','counter'))); + $query->from($db->quoteName('#__sermondistributor_statistic')); + $query->where($db->quoteName('sermon') . ' = '. (int) $counter->sermon); + $query->where($db->quoteName('filename') . ' = '. $db->quote($counter->filename)); + $db->setQuery($query); + $db->execute(); + if ($db->getNumRows()) + { + $statistic = $db->loadObject(); + // already has an entry + $statistic->counter++; + $statistic->modified = $date->toSql(); + // update the entry + return $db->updateObject('#__sermondistributor_statistic', $statistic, 'id'); + } + else + { + // set a new entry + $counter->counter = 1; + $counter->published = 1; + $counter->created = $date->toSql(); + $counter->access = 1; + $counter->version = 1; + // set a new entry + $done = $db->insertObject('#__sermondistributor_statistic', $counter); + // if done return last used id + if ($done) + { + $newId = $db->insertid(); + // make sure the access of asset is set + return self::setAsset($newId,'statistic'); + } + } + } + return false; + } + + public static function getFileInfo($key) + { + if (UtilitiesStringHelper::check($key) && (base64_encode(base64_decode($key, true)) === $key)) + { + // Get local key + $localkey = self::getLocalKey(); + $opener = new AES($localkey, 128); + $key = rtrim($opener->decryptString($key), "\0"); + // load the links from the database + $db = Factory::getDbo(); + // Create a new query object. + $query = $db->getQuery(true); + $query->select('size'); + $query->from($db->quoteName('#__sermondistributor_local_listing')); + $query->where($db->quoteName('key') . ' = '. $db->quote($key)); + // Reset the query using our newly populated query object. + $db->setQuery($query); + $db->execute(); + if ($db->getNumRows()) + { + $info = array(); + // get the size of the file + $info['filesize'] = $db->loadResult(); + // get the mime type + $info['type'] = MimeHelper::mimeType($key); + // return info + return $info; + } + } + return false; + } + + protected static function getDownloadFileName(&$sermon, $file, $type) + { + // first get file name and file type + $file = str_replace('VDM_pLeK_h0uEr/', '', $file); + $fileType = pathinfo($file, PATHINFO_EXTENSION); + if ($fileType) + { + $file = str_replace('.'.$fileType, '', $file); + } + else + { + $fileType = 'error'; + } + // now build download name + $downloadName = array(); + // build the Download File Name - first add the preacher name if set + if ($sermon->preacher) + { + $downloadName[] = UtilitiesStringHelper::safe($sermon->preacher_name,'U'); + } + // add the series name if set + if ($sermon->series) + { + $downloadName[] = UtilitiesStringHelper::safe($sermon->series_name,'F'); + } + // add the category name if set + if ($sermon->catid && UtilitiesStringHelper::check($sermon->category)) + { + $downloadName[] = UtilitiesStringHelper::safe($sermon->category, 'F'); + } + if ('dropbox_manual' == $type || 'local' == $type) + { + // add the main file name + $downloadName[] = UtilitiesStringHelper::safe($sermon->name,'F'); + $downloadName[] = UtilitiesStringHelper::safe($file,'F'); + } + else + { + $downloadName[] = UtilitiesStringHelper::safe($sermon->name,'F'); + if ('error' == $fileType || strpos('?', $fileType) !== false || strpos('&', $fileType) !== false ) + { + $fileType = 'mp3'; // TODO we don't know the url filetype (setting to mp3 but this could be wrong) + } + } + // now build the download file name + return implode('__', $downloadName).'.'.$fileType; + } + + /** + * check External Source Local Listing (do we have the files) + **/ + public static function checkExternalSourceLocalListing($type, $get = 'links') + { + // get the local links + if (isset(self::${$get.'_externalsource_'.$type}) && UtilitiesArrayHelper::check(self::${$get.'_externalsource_'.$type})) + { + // return true we have links loaded + return true; + } + else + { + $target = array('links' => 'url', 'select' => 'name'); + $build = array( 'auto' => 2, 'manual' => 1); + if (isset($build[$type])) + { + // load the links from the database + $db = Factory::getDbo(); + // Create a new query object. + $query = $db->getQuery(true); + $query->select($db->quoteName(array('key', $target[$get]))); + $query->from($db->quoteName('#__sermondistributor_local_listing')); + $query->where($db->quoteName('build') . ' = '. (int) $build[$type]); + $query->where($db->quoteName('published') . ' = 1'); // TODO we can now limit the links to access groups + // Reset the query using our newly populated query object. + $db->setQuery($query); + $db->execute(); + if ($db->getNumRows()) + { + self::${$get.'_externalsource_'.$type} = $db->loadAssocList('key', $target[$get]); + // return true we have links loaded + return true; + } + } + } + return false; + } + + /** + * get the localkey + **/ + protected static $localkey = array(); + + public static function getLocalKey($type = 'basic_key') + { + if (!isset(self::$localkey[$type])) + { + // get the main key + self::$localkey[$type] = ComponentHelper::getParams('com_sermondistributor')->get($type, 'localKey34fdWEkl'); + } + return self::$localkey[$type]; + } + + public static function updateExternalSource($id, $target = 0, $type = false, $force = false, $sleutel = null) + { + $source = self::getVar('external_source', (int) $id, 'id', 'externalsources'); + if (1 == $source) // Dropbox is the source + { + // load the file + JLoader::import('dropboxupdater', JPATH_COMPONENT_SITE.'/helpers'); + // update types + $types = array('manual','auto'); + // okay now update this type + if (UtilitiesStringHelper::check($type) && in_array($type,$types)) + { + $dropbox = new Dropboxupdater(); + if ($dropbox->update($id, $target, $type, $force, $sleutel)) + { + return true; + } + self::setUpdateError($id, $dropbox->getErrors()); + return false; + } + } + self::setUpdateError($id, array(Text::_('COM_SERMONDISTRIBUTOR_THE_EXTERNAL_SOURCE_COULD_NOT_BE_FOUND'))); + return false; + } + + public static function getSourceStatus($id) + { + // fist get errors if any is found + $errors = array(); + if ($targets = self::getExternalListingUpdateKeys($id, null, 1)) + { + foreach ($targets as $target) + { + $key = preg_replace('/[ ,]+/', '', trim($target)); + if ($error = self::getUpdateError(0, $key)) + { + $errors[] = $error; + } + } + } + // check when was the last update + $updateInfo = self::updateInfo($id); + if (!$updateInfo) + { + $errors[] = Text::_('COM_SERMONDISTRIBUTOR_THIS_SOURCE_HAS_NO_LOCAL_LISTING_SET'); + } + // build the return string + if (isset($updateInfo['last']) || UtilitiesArrayHelper::check($errors)) + { + $body = array(); + // great we have source status + if (isset($updateInfo['last'])) + { + $body[] = '

'. Text::_('COM_SERMONDISTRIBUTOR_LISTING_INFO') . '

'; + $body[] = '

'. Text::_('COM_SERMONDISTRIBUTOR_LAST_UPDATE') . ': '.$updateInfo['last']; + $body[] = '
'. Text::_('COM_SERMONDISTRIBUTOR_NUMBER_OF_FILES_LISTED') . ': '.$updateInfo['qty']; + $body[] = '

'; + } + // now set any errors found + if (UtilitiesArrayHelper::check($errors)) + { + $body[] = '

'. Text::_('COM_SERMONDISTRIBUTOR_NOTICE') . '

'; + $body[] = implode('', $errors); + } + return ''.Text::_('COM_SERMONDISTRIBUTOR_VIEW_UPDATE_STATUS').'' + . Html::_('bootstrap.renderModal', 'source-status'.$id, array('title' => Text::_('COM_SERMONDISTRIBUTOR_SOURCE_STATUS_REPORT')), implode('', $body)); + } + // no status found + return false; + } + + public static function updateInfo($id) + { + $db = Factory::getDbo(); + // Create a new query object. + $query = $db->getQuery(true); + $query->select($db->quoteName(array('a.created','a.modified'))); + $query->from($db->quoteName('#__sermondistributor_local_listing', 'a')); + $query->where($db->quoteName('a.external_source') . ' = ' . (int) $id); + // Reset the query using our newly populated query object. + $db->setQuery($query); + $db->execute(); + if ($qty = $db->getNumRows()) + { + $data = $db->loadRowList(); + $last = 0; + foreach ($data as $dates) + { + foreach ($dates as $date) + { + $time = strtotime($date); + if ($time > $last) + { + $last = $time; + } + } + } + $info['qty'] = (int) $qty; + $info['last'] = self::fancyDate($last); + return $info; + } + return false; + } + + public static function getUpdateError($id, $fileKey = null) + { + // get update error from file + if ($fileKey) + { + $file_path = FileHelper::getPath('path', 'updateerror', 'txt', $fileKey, JPATH_COMPONENT_ADMINISTRATOR); + // check if it is set + if (($text = FileHelper::getContent($file_path, FALSE)) !== FALSE) + { + // no error on success + if ('success' != $text) + { + return $text; + } + } + return false; + } + elseif (isset(self::$updateErrors[$id]) && UtilitiesArrayHelper::check(self::$updateErrors[$id])) + { + return '
  • '.implode('
  • ', self::$updateErrors[$id]).'
'; + } + return Text::_('COM_SERMONDISTRIBUTOR_UNKNOWN_ERROR_HAS_OCCURRED'); + } + + protected static function setUpdateError($id, $errorArray) + { + if (UtilitiesArrayHelper::check($errorArray) && $id > 0) + { + foreach ($errorArray as $error) + { + if (!isset(self::$updateErrors[$id])) + { + self::$updateErrors[$id] = array(); + } + self::$updateErrors[$id][] = $error; + } + } + } + + /** + * Change to nice fancy date + */ + public static function fancyDate($date, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + return date('jS \o\f F Y',$date); + } + + /** + * get date based in period past + */ + public static function fancyDynamicDate($date, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + // older then year + $lastyear = date("Y", strtotime("-1 year")); + $tragetyear = date("Y", $date); + if ($tragetyear <= $lastyear) + { + return date('m/d/y', $date); + } + // same day + $yesterday = strtotime("-1 day"); + if ($date > $yesterday) + { + return date('g:i A', $date); + } + // just month day + return date('M j', $date); + } + + /** + * Change to nice fancy day time and date + */ + public static function fancyDayTimeDate($time, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($time)) + { + $time = strtotime($time); + } + return date('D ga jS \o\f F Y',$time); + } + + /** + * Change to nice fancy time and date + */ + public static function fancyDateTime($time, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($time)) + { + $time = strtotime($time); + } + return date('(G:i) jS \o\f F Y',$time); + } + + /** + * Change to nice hour:minutes time + */ + public static function fancyTime($time, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($time)) + { + $time = strtotime($time); + } + return date('G:i',$time); + } + + /** + * set the date day as Sunday through Saturday + */ + public static function setDayName($date, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + return date('l', $date); + } + + /** + * set the date month as January through December + */ + public static function setMonthName($date, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + return date('F', $date); + } + + /** + * set the date day as 1st + */ + public static function setDay($date, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + return date('jS', $date); + } + + /** + * set the date month as 5 + */ + public static function setMonth($date, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + return date('n', $date); + } + + /** + * set the date year as 2004 (for charts) + */ + public static function setYear($date, $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + return date('Y', $date); + } + + /** + * set the date as 2004/05 (for charts) + */ + public static function setYearMonth($date, $spacer = '/', $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + return date('Y' . $spacer . 'm', $date); + } + + /** + * set the date as 2004/05/03 (for charts) + */ + public static function setYearMonthDay($date, $spacer = '/', $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + return date('Y' . $spacer . 'm' . $spacer . 'd', $date); + } + + /** + * set the date as 03/05/2004 + */ + public static function setDayMonthYear($date, $spacer = '/', $check_stamp = true) + { + if ($check_stamp && !self::isValidTimeStamp($date)) + { + $date = strtotime($date); + } + return date('d' . $spacer . 'm' . $spacer . 'Y', $date); + } + + /** + * Check if string is a valid time stamp + */ + public static function isValidTimeStamp($timestamp) + { + return ((int) $timestamp === $timestamp) + && ($timestamp <= PHP_INT_MAX) + && ($timestamp >= ~PHP_INT_MAX); + } + + /** + * Check if string is a valid date + * https://www.php.net/manual/en/function.checkdate.php#113205 + */ + public static function isValidateDate($date, $format = 'Y-m-d H:i:s') + { + $d = DateTime::createFromFormat($format, $date); + return $d && $d->format($format) == $date; + } + + + /** + * Workers to load tasks + * + * @var array + * @since 3.1 + */ + protected static array $worker = []; + + /** + * Set a worker dynamic URLs + * + * @var array + * @since 3.1 + */ + protected static array $workerURL = []; + + /** + * Set a worker dynamic HEADERs + * + * @var array + * @since 3.1 + */ + protected static array $workerHEADER = []; + + /** + * Curl Error Notice + * + * @var bool + * @since 3.1 + */ + protected static bool $curlErrorLoaded = false; + + /** + * check if a worker has more work + * + * @param string $function The function to target to perform the task + * + * @return bool + * @since 3.1 + */ + public static function hasWork(string $function): bool + { + if (isset(self::$worker[$function]) && UtilitiesArrayHelper::check(self::$worker[$function])) + { + return count( (array) self::$worker[$function]); + } + return false; + } + + /** + * Set a worker url + * + * @param string $function The function to target to perform the task + * @param string $url The url of where the task is to be performed + * + * @return void + * @since 3.1 + */ + public static function setWorkerUrl(string $function, string $url): void + { + // set the URL if found + if (UtilitiesStringHelper::check($url)) + { + // make sure task function url is up + self::$workerURL[$function] = $url; + } + } + + /** + * Set a worker headers + * + * @param string $function The function to target to perform the task + * @param array|null $headers The headers needed for these workers/function + * + * @return void + * @since 3.1 + */ + public static function setWorkerHeaders(string $function, ?array $headers): void + { + // set the Headers if found + if (UtilitiesArrayHelper::check($headers)) + { + // make sure task function headers are set + self::$workerHEADER[$function] = $headers; + } + } + + /** + * Set a worker that needs to perform a task + * + * @param mixed $data The data to pass to the task + * @param string $function The function to target to perform the task + * @param string $url The url of where the task is to be performed + * @param array $headers The headers needed for these workers/function + * + * @return void + * @since 3.1 + */ + public static function setWorker($data, string $function, ?string $url = null, ?array $headers = null) + { + // make sure task function is up + if (!isset(self::$worker[$function])) + { + self::$worker[$function] = []; + } + + // load the task + self::$worker[$function][] = self::lock($data); + + // set the Headers if found + if ($headers && !isset(self::$workerHEADER[$function])) + { + self::setWorkerHeaders($function, $headers); + } + + // set the URL if found + if ($url && !isset(self::$workerURL[$function])) + { + self::setWorkerUrl($function, $url); + } + } + + /** + * Run set Workers + * + * @param string $function The function to target to perform the task + * @param string $perTask The amount of task per worker + * @param function $callback The option to do a call back when task is completed + * @param int $threadSize The size of the thread + * + * @return bool true On success + * @since 3.1 + */ + public static function runWorker(string $function, $perTask = 50, $callback = null, $threadSize = 20): bool + { + // set task + $task = self::lock($function); + // build headers + $headers = array('VDM-TASK: ' .$task); + // build dynamic headers + if (isset(self::$workerHEADER[$function]) && UtilitiesArrayHelper::check(self::$workerHEADER[$function])) + { + foreach (self::$workerHEADER[$function] as $header) + { + $headers[] = $header; + } + } + // build worker options + $options = array(); + // make sure worker is up + if (isset(self::$worker[$function]) && UtilitiesArrayHelper::check(self::$worker[$function])) + { + // this load method is for each + if (1 == $perTask) + { + // working with a string = 1 + $headers[] = 'VDM-VALUE-TYPE: ' .self::lock(1); + // now load the options + foreach (self::$worker[$function] as $data) + { + $options[] = array(CURLOPT_HTTPHEADER => $headers, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => 'VDM_DATA='. $data); + } + } + // this load method is for bundles + else + { + // working with an array = 2 + $headers[] = 'VDM-VALUE-TYPE: ' .self::lock(2); + // now load the options + $work = array_chunk(self::$worker[$function], $perTask); + foreach ($work as $data) + { + $options[] = array(CURLOPT_HTTPHEADER => $headers, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => 'VDM_DATA='. implode('___VDM___', $data)); + } + } + // relieve worker of task/function + self::$worker[$function] = array(); + } + // do the execution + if (UtilitiesArrayHelper::check($options)) + { + if (isset(self::$workerURL[$function])) + { + $url = self::$workerURL[$function]; + } + else + { + $url = Uri::root() . '/index.php?option=com_sermondistributor&task=api.worker'; + } + return self::curlMultiExec($url, $options, $callback, $threadSize); + } + return false; + } + + /** + * Do a multi curl execution of tasks + * + * @param string $url The url of where the task is to be performed + * @param array $_options The array of curl options/headers to set + * @param function $callback The option to do a call back when task is completed + * @param int $threadSize The size of the thread + * + * @return bool true On success + * @since 3.1 + */ + public static function curlMultiExec(&$url, &$_options, $callback = null, $threadSize = 20) + { + // make sure we have curl available + if (!function_exists('curl_version')) + { + if (!self::$curlErrorLoaded) + { + // set the notice + Factory::getApplication()->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_HTWOCURL_NOT_FOUNDHTWOPPLEASE_SETUP_CURL_ON_YOUR_SYSTEM_OR_BSERMONDISTRIBUTORB_WILL_NOT_FUNCTION_CORRECTLYP'), 'Error'); + // load the notice only once + self::$curlErrorLoaded = true; + } + return false; + } + // make sure we have an url + if (UtilitiesStringHelper::check($url)) + { + // make sure the thread size isn't greater than the # of _options + $threadSize = (count($_options) < $threadSize) ? count($_options) : $threadSize; + // set the options + $options = array(); + $options[CURLOPT_URL] = $url; + $options[CURLOPT_USERAGENT] = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12'; + $options[CURLOPT_RETURNTRANSFER] = TRUE; + $options[CURLOPT_SSL_VERIFYPEER] = FALSE; + // start multi threading :) + $handle = curl_multi_init(); + // start the first batch of requests + for ($i = 0; $i < $threadSize; $i++) + { + if (isset($_options[$i])) + { + $ch = curl_init(); + foreach ($_options[$i] as $curlopt => $string) + { + $options[$curlopt] = $string; + } + curl_setopt_array($ch, $options); + curl_multi_add_handle($handle, $ch); + } + } + // we wait for all the calls to finish (should not take long) + do { + while(($execrun = curl_multi_exec($handle, $working)) == CURLM_CALL_MULTI_PERFORM); + if($execrun != CURLM_OK) + break; + // a request was just completed -- find out which one + while($done = curl_multi_info_read($handle)) + { + if (is_callable($callback)) + { + // $info = curl_getinfo($done['handle']); + // request successful. process output using the callback function. + $output = curl_multi_getcontent($done['handle']); + $callback($output); + } + $key = $i + 1; + if(isset($_options[$key])) + { + // start a new request (it's important to do this before removing the old one) + $ch = curl_init(); $i++; + // add options + foreach ($_options[$key] as $curlopt => $string) + { + $options[$curlopt] = $string; + } + curl_setopt_array($ch, $options); + curl_multi_add_handle($handle, $ch); + // remove options again + foreach ($_options[$key] as $curlopt => $string) + { + unset($options[$curlopt]); + } + } + // remove the curl handle that just completed + curl_multi_remove_handle($handle, $done['handle']); + } + // stop wasting CPU cycles and rest for a couple ms + usleep(10000); + } while ($working); + // close the curl multi thread + curl_multi_close($handle); + // okay done + return true; + } + return false; + } + + /** + * the locker + * + * @var array + * @since 3.1 + */ + protected static array $locker = []; + + /** + * the dynamic replacement salt + * + * @var array + * @since 3.1 + */ + protected static array $globalSalt = []; + + /** + * the timer + * + * @var object + * @since 3.1 + */ + protected static $keytimer; + + /** + * To Lock string + * + * @param string $string The string/array to lock + * @param string|null $key The custom key to use + * @param int $salt The switch to add salt and type of salt + * @param int|null $dynamic The dynamic replacement array of salt build string + * @param int $urlencode The switch to control url encoding + * + * @return string Encrypted String + * @since 3.1 + */ + public static function lock(string $string, ?string $key = null, int $salt = 2, ?int $dynamic = null, $urlencode = true): string + { + // get the global settings + if (!$key || !UtilitiesStringHelper::check($key)) + { + // set temp timer + $timer = 2; + // if we have a timer use it + if ($salt > 0) + { + $timer = $salt; + } + // set the default key + $key = self::salt($timer, $dynamic); + // try getting the system key + if (method_exists(get_called_class(), "getCryptKey")) + { + // try getting the medium key first the fall back to basic, and then default + $key = self::getCryptKey('medium', self::getCryptKey('basic', $key)); + } + } + // check if we have a salt timer + if ($salt > 0) + { + $key .= self::salt($salt, $dynamic); + } + // get the locker settings + if (!isset(self::$locker[$key]) || !ObjectHelper::check(self::$locker[$key])) + { + self::$locker[$key] = new AES($key, 128); + } + // convert array or object to string + if (UtilitiesArrayHelper::check($string) || ObjectHelper::check($string)) + { + $string = serialize($string); + } + // prep for url + if ($urlencode && method_exists(get_called_class(), "base64_urlencode")) + { + return self::base64_urlencode(self::$locker[$key]->encryptString($string)); + } + return self::$locker[$key]->encryptString($string); + } + + /** + * To un-Lock string + * + * @param string $string The string to unlock + * @param string $key The custom key to use + * @param int $salt The switch to add salt and type of salt + * @param int $dynamic The dynamic replacement array of salt build string + * @param int $urlencode The switch to control url decoding + * + * @return string Decrypted String + * @since 3.1 + */ + public static function unlock($string, $key = null, $salt = 2, $dynamic = null, $urlencode = true): string + { + // get the global settings + if (!$key || !UtilitiesStringHelper::check($key)) + { + // set temp timer + $timer = 2; + // if we have a timer use it + if ($salt > 0) + { + $timer = $salt; + } + // set the default key + $key = self::salt($timer, $dynamic); + // try getting the system key + if (method_exists(get_called_class(), "getCryptKey")) + { + // try getting the medium key first the fall back to basic, and then default + $key = self::getCryptKey('medium', self::getCryptKey('basic', $key)); + } + } + // check if we have a salt timer + if ($salt > 0) + { + $key .= self::salt($salt, $dynamic); + } + // get the locker settings + if (!isset(self::$locker[$key]) || !ObjectHelper::check(self::$locker[$key])) + { + self::$locker[$key] = new AES($key, 128); + } + // make sure we have real base64 + if ($urlencode && method_exists(get_called_class(), "base64_urldecode")) + { + $string = self::base64_urldecode($string); + } + // basic decrypt string. + if (!empty($string) && !is_numeric($string) && $string === base64_encode(base64_decode($string, true))) + { + $string = rtrim(self::$locker[$key]->decryptString($string), "\0"); + // convert serial string to array + if (self::is_serial($string)) + { + $string = unserialize($string); + } + } + + return $string; + } + + /** + * The Salt + * + * @param int $type The type of length the salt should be valid + * @param int $dynamic The dynamic replacement array of salt build string + * + * @return string + * @since 3.1 + */ + public static function salt(int $type = 1, $dynamic = null): string + { + // get dynamic replacement salt + $dynamic = self::getDynamicSalt($dynamic); + // get the key timer + if (!ObjectHelper::check(self::$keytimer)) + { + // load the date time object + self::$keytimer = new DateTime; + // set the correct time stamp + $vdmLocalTime = new DateTimeZone('Africa/Windhoek'); + self::$keytimer->setTimezone($vdmLocalTime); + } + // set type + if ($type == 2) + { + // hour + $format = 'Y-m-d \o\n ' . self::periodFix(self::$keytimer->format('H')); + } + elseif ($type == 3) + { + // day + $format = 'Y-m-' . self::periodFix(self::$keytimer->format('d')); + } + elseif ($type == 4) + { + // month + $format = 'Y-' . self::periodFix(self::$keytimer->format('m')); + } + else + { + // minute + $format = 'Y-m-d \o\n H:' . self::periodFix(self::$keytimer->format('i')); + } + // get key + if (UtilitiesArrayHelper::check($dynamic)) + { + return md5(str_replace(array_keys($dynamic), array_values($dynamic), self::$keytimer->format($format) . ' @ VDM.I0')); + } + return md5(self::$keytimer->format($format) . ' @ VDM.I0'); + } + + /** + * The function to insure the salt is valid within the given period (third try) + * + * @param int $main The main number + * @since 3.1 + */ + protected static function periodFix(int $main): int + { + return round($main / 3) * 3; + } + + /** + * Check if a string is serialized + * + * @param string $string + * + * @return Boolean + * @since 3.1 + */ + public static function is_serial(string $string): bool + { + return (@unserialize($string) !== false); + } + + /** + * Get dynamic replacement salt + * @since 3.1 + */ + public static function getDynamicSalt($dynamic = null) + { + // load global if not manually set + if (!UtilitiesArrayHelper::check($dynamic)) + { + return self::getGlobalSalt(); + } + // return manual values if set + else + { + return $dynamic; + } + } + + /** + * The random or dynamic secret salt + * @since 3.1 + */ + public static function getSecretSalt($string = null, $size = 9) + { + // set the string + if (!$string) + { + // get random string + $string = self::randomkey($size); + } + // convert string to array + $string = UtilitiesStringHelper::safe($string); + // convert string to array + $array = str_split($string); + // insure only unique values are used + $array = array_unique($array); + // set the size + $size = ($size <= count($array)) ? $size : count($array); + // down size the + return array_slice($array, 0, $size); + } + + /** + * Get global replacement salt + * @since 3.1 + */ + public static function getGlobalSalt() + { + // load from memory if found + if (!UtilitiesArrayHelper::check(self::$globalSalt)) + { + // get the global settings + if (!ObjectHelper::check(self::$params)) + { + self::$params = ComponentHelper::getParams('com_sermondistributor'); + } + // check if we have a global dynamic replacement array available (format --> ' 1->!,3->E,4->A') + $tmp = self::$params->get('dynamic_salt', null); + if (UtilitiesStringHelper::check($tmp) && strpos($tmp, ',') !== false && strpos($tmp, '->') !== false) + { + $salt = array_map('trim', (array) explode(',', $tmp)); + if (UtilitiesArrayHelper::check($salt )) + { + foreach($salt as $replace) + { + $dynamic = array_map('trim', (array) explode('->', $replace)); + if (isset($dynamic[0]) && isset($dynamic[1])) + { + self::$globalSalt[$dynamic[0]] = $dynamic[1]; + } + } + } + } + } + // return global if found + if (UtilitiesArrayHelper::check(self::$globalSalt)) + { + return self::$globalSalt; + } + // return default as fail safe + return array('1' => '!', '3' => 'E', '4' => 'A'); + } + + /** + * Close public protocol + * @since 3.1 + */ + public static function closePublicProtocol($id, $public) + { + // get secret salt + $secretSalt = self::getSecretSalt(self::salt(1,array('4' => 'R','1' => 'E','2' => 'G','7' => 'J','8' => 'A'))); + // get the key + $key = self::salt(1, $secretSalt); + // get secret salt + $secret = self::getSecretSalt(); + // set the secret + $close['SECRET'] = self::lock($secret, $key, 1, array('1' => 's', '3' => 'R', '4' => 'D')); + // get the key + $key = self::salt(1, $secret); + // get the public key + $close['PUBLIC'] = self::lock($public, $key, 1, array('1' => '!', '3' => 'E', '4' => 'A')); + // get secret salt + $secretSalt = self::getSecretSalt($public); + // get the key + $key = self::salt(1, $secretSalt); + // get the ID + $close['ID'] = self::unlock($id, $key, 1, array('1' => 'i', '3' => 'e', '4' => 'B')); + // return closed values + return $close; + } + + /** + * Open public protocol + * @since 3.1 + */ + public static function openPublicProtocol($SECRET, $ID, $PUBLIC) + { + // get secret salt + $secretSalt = self::getSecretSalt(self::salt(1,array('4' => 'R','1' => 'E','2' => 'G','7' => 'J','8' => 'A'))); + // get the key + $key = self::salt(1, $secretSalt); + // get the $SECRET + $SECRET = self::unlock($SECRET, $key, 1, array('1' => 's', '3' => 'R', '4' => 'D')); + // get the key + $key = self::salt(1, $SECRET); + // get the public key + $open['public'] = self::unlock($PUBLIC, $key, 1, array('1' => '!', '3' => 'E', '4' => 'A')); + // get secret salt + $secretSalt = self::getSecretSalt($open['public']); + // get the key + $key = self::salt(1, $secretSalt); + // get the ID + $open['id'] = self::unlock($ID, $key, 1, array('1' => 'i', '3' => 'e', '4' => 'B')); + // return opened values + return $open; + } + + /** + * Load the Composer Vendors + */ + public static function composerAutoload($target) + { + // insure we load the composer vendor only once + if (!isset(self::$composer[$target])) + { + // get the function name + $functionName = UtilitiesStringHelper::safe('compose' . $target); + // check if method exist + if (method_exists(__CLASS__, $functionName)) + { + return self::{$functionName}(); + } + return false; + } + return self::$composer[$target]; + } + + /** + * Load the Component xml manifest. + */ + public static function manifest() + { + $manifestUrl = JPATH_ADMINISTRATOR."/components/com_sermondistributor/sermondistributor.xml"; + return simplexml_load_file($manifestUrl); + } + + /** + * Joomla version object + */ + protected static $JVersion; + + /** + * set/get Joomla version + */ + public static function jVersion() + { + // check if set + if (!ObjectHelper::check(self::$JVersion)) + { + self::$JVersion = new Version(); + } + return self::$JVersion; + } + + /** + * Load the Contributors details. + */ + public static function getContributors() + { + // get params + $params = ComponentHelper::getParams('com_sermondistributor'); + // start contributors array + $contributors = []; + // get all Contributors (max 20) + $searchArray = range('0','20'); + foreach($searchArray as $nr) + { + if ((NULL !== $params->get("showContributor".$nr)) && ($params->get("showContributor".$nr) == 1 || $params->get("showContributor".$nr) == 3)) + { + // set link based of selected option + if($params->get("useContributor".$nr) == 1) + { + $link_front = ''; + $link_back = ''; + } + elseif($params->get("useContributor".$nr) == 2) + { + $link_front = ''; + $link_back = ''; + } + else + { + $link_front = ''; + $link_back = ''; + } + $contributors[$nr]['title'] = UtilitiesStringHelper::html($params->get("titleContributor".$nr)); + $contributors[$nr]['name'] = $link_front.UtilitiesStringHelper::html($params->get("nameContributor".$nr)).$link_back; + } + } + return $contributors; + } + + /** + * Load the Component Help URLs. + **/ + public static function getHelpUrl($view) + { + $user = Factory::getApplication()->getIdentity(); + $groups = $user->get('groups'); + $db = Factory::getContainer()->get(DatabaseInterface::class); + $query = $db->getQuery(true); + $query->select(array('a.id','a.groups','a.target','a.type','a.article','a.url')); + $query->from('#__sermondistributor_help_document AS a'); + $query->where('a.admin_view = '.$db->quote($view)); + $query->where('a.location = 1'); + $query->where('a.published = 1'); + $db->setQuery($query); + $db->execute(); + if($db->getNumRows()) + { + $helps = $db->loadObjectList(); + if (UtilitiesArrayHelper::check($helps)) + { + foreach ($helps as $nr => $help) + { + if ($help->target == 1) + { + $targetgroups = json_decode($help->groups, true); + if (!array_intersect($targetgroups, $groups)) + { + // if user not in those target groups then remove the item + unset($helps[$nr]); + continue; + } + } + // set the return type + switch ($help->type) + { + // set joomla article + case 1: + return self::loadArticleLink($help->article); + break; + // set help text + case 2: + return self::loadHelpTextLink($help->id); + break; + // set Link + case 3: + return $help->url; + break; + } + } + } + } + return false; + } + + /** + * Get the Article Link. + **/ + protected static function loadArticleLink($id) + { + return Uri::root() . 'index.php?option=com_content&view=article&id='.$id.'&tmpl=component&layout=modal'; + } + + /** + * Get the Help Text Link. + **/ + protected static function loadHelpTextLink($id) + { + $token = Session::getFormToken(); + return 'index.php?option=com_sermondistributor&task=help.getText&id=' . (int) $id . '&' . $token . '=1'; + } + + /** + * Configure the Linkbar. + */ + public static function addSubmenu($submenu) + { + // load user for access menus + $user = Factory::getApplication()->getIdentity(); + // load the submenus to sidebar + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SUBMENU_DASHBOARD'), 'index.php?option=com_sermondistributor&view=sermondistributor', $submenu === 'sermondistributor'); + if ($user->authorise('preacher.access', 'com_sermondistributor') && $user->authorise('preacher.submenu', 'com_sermondistributor')) + { + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SUBMENU_PREACHERS'), 'index.php?option=com_sermondistributor&view=preachers', $submenu === 'preachers'); + } + if ($user->authorise('sermon.access', 'com_sermondistributor') && $user->authorise('sermon.submenu', 'com_sermondistributor')) + { + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SUBMENU_SERMONS'), 'index.php?option=com_sermondistributor&view=sermons', $submenu === 'sermons'); + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SERMON_SERMONS_CATEGORIES'), 'index.php?option=com_categories&view=categories&extension=com_sermondistributor.sermon', $submenu === 'categories.sermon'); + } + if ($user->authorise('series.access', 'com_sermondistributor') && $user->authorise('series.submenu', 'com_sermondistributor')) + { + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SUBMENU_SERIES_LIST'), 'index.php?option=com_sermondistributor&view=series_list', $submenu === 'series_list'); + } + if ($user->authorise('statistic.access', 'com_sermondistributor') && $user->authorise('statistic.submenu', 'com_sermondistributor')) + { + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SUBMENU_STATISTICS'), 'index.php?option=com_sermondistributor&view=statistics', $submenu === 'statistics'); + } + if ($user->authorise('external_source.access', 'com_sermondistributor') && $user->authorise('external_source.submenu', 'com_sermondistributor')) + { + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SUBMENU_EXTERNAL_SOURCES'), 'index.php?option=com_sermondistributor&view=external_sources', $submenu === 'external_sources'); + } + // Access control (manual_updater.access && manual_updater.submenu). + if ($user->authorise('manual_updater.access', 'com_sermondistributor') && $user->authorise('manual_updater.submenu', 'com_sermondistributor')) + { + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SUBMENU_MANUAL_UPDATER'), 'index.php?option=com_sermondistributor&view=manual_updater', $submenu === 'manual_updater'); + } + if ($user->authorise('local_listing.access', 'com_sermondistributor') && $user->authorise('local_listing.submenu', 'com_sermondistributor')) + { + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SUBMENU_LOCAL_LISTINGS'), 'index.php?option=com_sermondistributor&view=local_listings', $submenu === 'local_listings'); + } + if ($user->authorise('help_document.access', 'com_sermondistributor') && $user->authorise('help_document.submenu', 'com_sermondistributor')) + { + \JHtmlSidebar::addEntry(Text::_('COM_SERMONDISTRIBUTOR_SUBMENU_HELP_DOCUMENTS'), 'index.php?option=com_sermondistributor&view=help_documents', $submenu === 'help_documents'); + } + } + + /** + * Prepares the xml document + */ + public static function xls($rows, $fileName = null, $title = null, $subjectTab = null, $creator = 'Vast Development Method', $description = null, $category = null,$keywords = null, $modified = null) + { + // set the user + // set fileName if not set + if (!$fileName) + { + $fileName = 'exported_'.Factory::getDate()->format('jS_F_Y'); + } + // set modified if not set + if (!$modified) + { + $modified = $user->name; + } + // set title if not set + if (!$title) + { + $title = 'Book1'; + } + // set tab name if not set + if (!$subjectTab) + { + $subjectTab = 'Sheet1'; + } + + // make sure we have the composer classes loaded + self::composerAutoload('phpspreadsheet'); + + // Create new Spreadsheet object + $spreadsheet = new Spreadsheet(); + + // Set document properties + $spreadsheet->getProperties() + ->setCreator($creator) + ->setCompany('Vast Development Method') + ->setLastModifiedBy($modified) + ->setTitle($title) + ->setSubject($subjectTab); + // The file type + $file_type = 'Xls'; + // set description + if ($description) + { + $spreadsheet->getProperties()->setDescription($description); + } + // set keywords + if ($keywords) + { + $spreadsheet->getProperties()->setKeywords($keywords); + } + // set category + if ($category) + { + $spreadsheet->getProperties()->setCategory($category); + } + + // Some styles + $headerStyles = array( + 'font' => array( + 'bold' => true, + 'color' => array('rgb' => '1171A3'), + 'size' => 12, + 'name' => 'Verdana' + )); + $sideStyles = array( + 'font' => array( + 'bold' => true, + 'color' => array('rgb' => '444444'), + 'size' => 11, + 'name' => 'Verdana' + )); + $normalStyles = array( + 'font' => array( + 'color' => array('rgb' => '444444'), + 'size' => 11, + 'name' => 'Verdana' + )); + + // Add some data + if (($size = UtilitiesArrayHelper::check($rows)) !== false) + { + $i = 1; + + // Based on data size we adapt the behaviour. + $xls_mode = 1; + if ($size > 3000) + { + $xls_mode = 3; + $file_type = 'Csv'; + } + elseif ($size > 2000) + { + $xls_mode = 2; + } + + // Set active sheet and get it. + $active_sheet = $spreadsheet->setActiveSheetIndex(0); + foreach ($rows as $array) + { + $a = 'A'; + foreach ($array as $value) + { + $active_sheet->setCellValue($a.$i, $value); + if ($xls_mode != 3) + { + if ($i == 1) + { + $active_sheet->getColumnDimension($a)->setAutoSize(true); + $active_sheet->getStyle($a.$i)->applyFromArray($headerStyles); + $active_sheet->getStyle($a.$i)->getAlignment()->setHorizontal(PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); + } + elseif ($a === 'A') + { + $active_sheet->getStyle($a.$i)->applyFromArray($sideStyles); + } + elseif ($xls_mode == 1) + { + $active_sheet->getStyle($a.$i)->applyFromArray($normalStyles); + } + } + $a++; + } + $i++; + } + } + else + { + return false; + } + + // Rename worksheet + $spreadsheet->getActiveSheet()->setTitle($subjectTab); + + // Set active sheet index to the first sheet, so Excel opens this as the first sheet + $spreadsheet->setActiveSheetIndex(0); + + // Redirect output to a client's web browser (Excel5) + header('Content-Type: application/vnd.ms-excel'); + header('Content-Disposition: attachment;filename="' . $fileName . '.' . strtolower($file_type) .'"'); + header('Cache-Control: max-age=0'); + // If you're serving to IE 9, then the following may be needed + header('Cache-Control: max-age=1'); + + // If you're serving to IE over SSL, then the following may be needed + header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past + header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified + header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 + header ('Pragma: public'); // HTTP/1.0 + + $writer = IOFactory::createWriter($spreadsheet, $file_type); + $writer->save('php://output'); + jexit(); + } + + /** + * Get CSV Headers + */ + public static function getFileHeaders($dataType) + { + // make sure we have the composer classes loaded + self::composerAutoload('phpspreadsheet'); + // get session object + $session = Factory::getSession(); + $package = $session->get('package', null); + $package = json_decode($package, true); + // set the headers + if(isset($package['dir'])) + { + // only load first three rows + $chunkFilter = new PhpOffice\PhpSpreadsheet\Reader\chunkReadFilter(2,1); + // identify the file type + $inputFileType = IOFactory::identify($package['dir']); + // create the reader for this file type + $excelReader = IOFactory::createReader($inputFileType); + // load the limiting filter + $excelReader->setReadFilter($chunkFilter); + $excelReader->setReadDataOnly(true); + // load the rows (only first three) + $excelObj = $excelReader->load($package['dir']); + $headers = []; + foreach ($excelObj->getActiveSheet()->getRowIterator() as $row) + { + if($row->getRowIndex() == 1) + { + $cellIterator = $row->getCellIterator(); + $cellIterator->setIterateOnlyExistingCells(false); + foreach ($cellIterator as $cell) + { + if (!is_null($cell)) + { + $headers[$cell->getColumn()] = $cell->getValue(); + } + } + $excelObj->disconnectWorksheets(); + unset($excelObj); + break; + } + } + return $headers; + } + return false; + } + + /** + * Load the Composer Vendor phpspreadsheet + */ + protected static function composephpspreadsheet() + { + // load the autoloader for phpspreadsheet + require_once JPATH_SITE . '/libraries/phpspreadsheet/vendor/autoload.php'; + // do not load again + self::$composer['phpspreadsheet'] = true; + + return true; + } + + /** + * Get a Variable + * + * @param string $table The table from which to get the variable + * @param string $where The value where + * @param string $whereString The target/field string where/name + * @param string $what The return field + * @param string $operator The operator between $whereString/field and $where/value + * @param string $main The component in which the table is found + * + * @return mix string/int/float + * @deprecated 3.3 Use GetHelper::var(...); + */ + public static function getVar($table, $where = null, $whereString = 'user', $what = 'id', $operator = '=', $main = 'sermondistributor') + { + return GetHelper::var( + $table, + $where, + $whereString, + $what, + $operator, + $main + ); + } + + /** + * Get array of variables + * + * @param string $table The table from which to get the variables + * @param string $where The value where + * @param string $whereString The target/field string where/name + * @param string $what The return field + * @param string $operator The operator between $whereString/field and $where/value + * @param string $main The component in which the table is found + * @param bool $unique The switch to return a unique array + * + * @return array + * @deprecated 3.3 Use GetHelper::vars(...); + */ + public static function getVars($table, $where = null, $whereString = 'user', $what = 'id', $operator = 'IN', $main = 'sermondistributor', $unique = true) + { + return GetHelper::vars( + $table, + $where, + $whereString, + $what, + $operator, + $main, + $unique + ); + } + + /** + * Convert a json object to a string + * + * @input string $value The json string to convert + * + * @returns a string + * @deprecated 3.3 Use JsonHelper::string(...); + */ + public static function jsonToString($value, $sperator = ", ", $table = null, $id = 'id', $name = 'name') + { + return JsonHelper::string( + $value, + $sperator, + $table, + $id, + $name + ); + } + + public static function isPublished($id,$type) + { + if ($type == 'raw') + { + $type = 'item'; + } + $db = Factory::getContainer()->get(DatabaseInterface::class); + $query = $db->getQuery(true); + $query->select(array('a.published')); + $query->from('#__sermondistributor_'.$type.' AS a'); + $query->where('a.id = '. (int) $id); + $query->where('a.published = 1'); + $db->setQuery($query); + $db->execute(); + $found = $db->getNumRows(); + if($found) + { + return true; + } + return false; + } + + public static function getGroupName($id) + { + $db = Factory::getContainer()->get(DatabaseInterface::class); + $query = $db->getQuery(true); + $query->select(array('a.title')); + $query->from('#__usergroups AS a'); + $query->where('a.id = '. (int) $id); + $db->setQuery($query); + $db->execute(); + $found = $db->getNumRows(); + if($found) + { + return $db->loadResult(); + } + return $id; + } + + /** + * Get the action permissions + * + * @param string $view The related view name + * @param int $record The item to act upon + * @param string $views The related list view name + * @param mixed $target Only get this permission (like edit, create, delete) + * @param string $component The target component + * @param object $user The user whose permissions we are loading + * + * @return object The CMSObject of permission/authorised actions + * + */ + public static function getActions($view, &$record = null, $views = null, $target = null, $component = 'sermondistributor', $user = 'null') + { + // load the user if not given + if (!ObjectHelper::check($user)) + { + // get the user object + $user = Factory::getApplication()->getIdentity(); + } + // load the CMSObject + $result = new CMSObject; + // make view name safe (just incase) + $view = UtilitiesStringHelper::safe($view); + if (UtilitiesStringHelper::check($views)) + { + $views = UtilitiesStringHelper::safe($views); + } + // get all actions from component + $actions = Access::getActionsFromFile( + JPATH_ADMINISTRATOR . '/components/com_' . $component . '/access.xml', + "/access/section[@name='component']/" + ); + // if non found then return empty CMSObject + if (empty($actions)) + { + return $result; + } + // get created by if not found + if (ObjectHelper::check($record) && !isset($record->created_by) && isset($record->id)) + { + $record->created_by = GetHelper::var($view, $record->id, 'id', 'created_by', '=', $component); + } + // set actions only set in component settings + $componentActions = array('core.admin', 'core.manage', 'core.options', 'core.export'); + // check if we have a target + $checkTarget = false; + if ($target) + { + // convert to an array + if (UtilitiesStringHelper::check($target)) + { + $target = array($target); + } + // check if we are good to go + if (UtilitiesArrayHelper::check($target)) + { + $checkTarget = true; + } + } + // loop the actions and set the permissions + foreach ($actions as $action) + { + // check target action filter + if ($checkTarget && self::filterActions($view, $action->name, $target)) + { + continue; + } + // set to use component default + $fallback = true; + // reset permission per/action + $permission = false; + $catpermission = false; + // set area + $area = 'comp'; + // check if the record has an ID and the action is item related (not a component action) + if (ObjectHelper::check($record) && isset($record->id) && $record->id > 0 && !in_array($action->name, $componentActions) && + (strpos($action->name, 'core.') !== false || strpos($action->name, $view . '.') !== false)) + { + // we are in item + $area = 'item'; + // The record has been set. Check the record permissions. + $permission = $user->authorise($action->name, 'com_' . $component . '.' . $view . '.' . (int) $record->id); + // if no permission found, check edit own + if (!$permission) + { + // With edit, if the created_by matches current user then dig deeper. + if (($action->name === 'core.edit' || $action->name === $view . '.edit') && $record->created_by > 0 && ($record->created_by == $user->id)) + { + // the correct target + $coreCheck = (array) explode('.', $action->name); + // check that we have both local and global access + if ($user->authorise($coreCheck[0] . '.edit.own', 'com_' . $component . '.' . $view . '.' . (int) $record->id) && + $user->authorise($coreCheck[0] . '.edit.own', 'com_' . $component)) + { + // allow edit + $result->set($action->name, true); + // set not to use global default + // because we already validated it + $fallback = false; + } + else + { + // do not allow edit + $result->set($action->name, false); + $fallback = false; + } + } + } + elseif (UtilitiesStringHelper::check($views) && isset($record->catid) && $record->catid > 0) + { + // we are in item + $area = 'category'; + // set the core check + $coreCheck = explode('.', $action->name); + $core = $coreCheck[0]; + // make sure we use the core. action check for the categories + if (strpos($action->name, $view) !== false && strpos($action->name, 'core.') === false ) + { + $coreCheck[0] = 'core'; + $categoryCheck = implode('.', $coreCheck); + } + else + { + $categoryCheck = $action->name; + } + // The record has a category. Check the category permissions. + $catpermission = $user->authorise($categoryCheck, 'com_' . $component . '.' . $views . '.category.' . (int) $record->catid); + if (!$catpermission && !is_null($catpermission)) + { + // With edit, if the created_by matches current user then dig deeper. + if (($action->name === 'core.edit' || $action->name === $view . '.edit') && $record->created_by > 0 && ($record->created_by == $user->id)) + { + // check that we have both local and global access + if ($user->authorise('core.edit.own', 'com_' . $component . '.' . $views . '.category.' . (int) $record->catid) && + $user->authorise($core . '.edit.own', 'com_' . $component)) + { + // allow edit + $result->set($action->name, true); + // set not to use global default + // because we already validated it + $fallback = false; + } + else + { + // do not allow edit + $result->set($action->name, false); + $fallback = false; + } + } + } + } + } + // if allowed then fallback on component global settings + if ($fallback) + { + // if item/category blocks access then don't fall back on global + if ((($area === 'item') && !$permission) || (($area === 'category') && !$catpermission)) + { + // do not allow + $result->set($action->name, false); + } + // Finally remember the global settings have the final say. (even if item allow) + // The local item permissions can block, but it can't open and override of global permissions. + // Since items are created by users and global permissions is set by system admin. + else + { + $result->set($action->name, $user->authorise($action->name, 'com_' . $component)); + } + } + } + return $result; + } + + /** + * Filter the action permissions + * + * @param string $action The action to check + * @param array $targets The array of target actions + * + * @return boolean true if action should be filtered out + * + */ + protected static function filterActions(&$view, &$action, &$targets) + { + foreach ($targets as $target) + { + if (strpos($action, $view . '.' . $target) !== false || + strpos($action, 'core.' . $target) !== false) + { + return false; + break; + } + } + return true; + } + + /** + * Returns any Model object. + * + * @param string $type The model type to instantiate + * @param string $prefix Prefix for the model class name. Optional. + * @param string $component Component name the model belongs to. Optional. + * @param array $config Configuration array for model. Optional. + * + * @return \Joomla\CMS\MVC\Model\BaseDatabaseModel + * @throws \Exception + * @since 4.4 + */ + public static function getModel(string $type, string $prefix = 'Administrator', + string $component = 'sermondistributor', array $config = []) + { + // make sure the name is correct + $type = UtilitiesStringHelper::safe($type, 'F'); + $component = strtolower($component); + + if ($prefix !== 'Site' && $prefix !== 'Administrator') + { + $prefix = self::getPrefixFromModelPath($prefix); + } + + // Get the model through the MVCFactory + return Factory::getApplication()->bootComponent('com_' . $component)->getMVCFactory()->createModel($type, $prefix, $config); + } + + /** + * Get the prefix from the model path + * + * @param string $path The model path + * + * @return string The prefix value + * @since 4.4 + */ + protected static function getPrefixFromModelPath(string $path): string + { + // Check if $path starts with JPATH_ADMINISTRATOR path + if (str_starts_with($path, JPATH_ADMINISTRATOR . '/components/')) + { + return 'Administrator'; + } + // Check if $path starts with JPATH_SITE path + elseif (str_starts_with($path, JPATH_SITE . '/components/')) + { + return 'Site'; + } + + return 'Administrator'; + } + + /** + * Add to asset Table + */ + public static function setAsset($id, $table, $inherit = true) + { + $parent = Table::getInstance('Asset'); + $parent->loadByName('com_sermondistributor'); + + $parentId = $parent->id; + $name = 'com_sermondistributor.'.$table.'.'.$id; + $title = ''; + + $asset = Table::getInstance('Asset'); + $asset->loadByName($name); + + // Check for an error. + $error = $asset->getError(); + + if ($error) + { + return false; + } + else + { + // Specify how a new or moved node asset is inserted into the tree. + if ($asset->parent_id != $parentId) + { + $asset->setLocation($parentId, 'last-child'); + } + + // Prepare the asset to be stored. + $asset->parent_id = $parentId; + $asset->name = $name; + $asset->title = $title; + // get the default asset rules + $rules = self::getDefaultAssetRules('com_sermondistributor', $table, $inherit); + if ($rules instanceof AccessRules) + { + $asset->rules = (string) $rules; + } + + if (!$asset->check() || !$asset->store()) + { + Factory::getApplication()->enqueueMessage($asset->getError(), 'warning'); + return false; + } + else + { + // Create an asset_id or heal one that is corrupted. + $object = new \StdClass(); + + // Must be a valid primary key value. + $object->id = $id; + $object->asset_id = (int) $asset->id; + + // Update their asset_id to link to the asset table. + return Factory::getDbo()->updateObject('#__sermondistributor_'.$table, $object, 'id'); + } + } + return false; + } + + /** + * Gets the default asset Rules for a component/view. + */ + protected static function getDefaultAssetRules($component, $view, $inherit = true) + { + // if new or inherited + $assetId = 0; + // Only get the actual item rules if not inheriting + if (!$inherit) + { + // Need to find the asset id by the name of the component. + $db = Factory::getContainer()->get(DatabaseInterface::class); + $query = $db->getQuery(true) + ->select($db->quoteName('id')) + ->from($db->quoteName('#__assets')) + ->where($db->quoteName('name') . ' = ' . $db->quote($component)); + $db->setQuery($query); + $db->execute(); + // check that there is a value + if ($db->getNumRows()) + { + // asset already set so use saved rules + $assetId = (int) $db->loadResult(); + } + } + // get asset rules + $result = Access::getAssetRules($assetId); + if ($result instanceof AccessRules) + { + $_result = (string) $result; + $_result = json_decode($_result); + foreach ($_result as $name => &$rule) + { + $v = explode('.', $name); + if ($view !== $v[0]) + { + // remove since it is not part of this view + unset($_result->$name); + } + elseif ($inherit) + { + // clear the value since we inherit + $rule = []; + } + } + // check if there are any view values remaining + if (count((array) $_result)) + { + $_result = json_encode($_result); + $_result = array($_result); + // Instantiate and return the AccessRules object for the asset rules. + $rules = new AccessRules($_result); + // return filtered rules + return $rules; + } + } + return $result; + } + + /** + * xmlAppend + * + * @param SimpleXMLElement $xml The XML element reference in which to inject a comment + * @param mixed $node A SimpleXMLElement node to append to the XML element reference, or a stdClass object containing a comment attribute to be injected before the XML node and a fieldXML attribute containing a SimpleXMLElement + * + * @return void + * @deprecated 3.3 Use FormHelper::append($xml, $node); + */ + public static function xmlAppend(&$xml, $node) + { + FormHelper::append($xml, $node); + } + + /** + * xmlComment + * + * @param SimpleXMLElement $xml The XML element reference in which to inject a comment + * @param string $comment The comment to inject + * + * @return void + * @deprecated 3.3 Use FormHelper::comment($xml, $comment); + */ + public static function xmlComment(&$xml, $comment) + { + FormHelper::comment($xml, $comment); + } + + /** + * xmlAddAttributes + * + * @param SimpleXMLElement $xml The XML element reference in which to inject a comment + * @param array $attributes The attributes to apply to the XML element + * + * @return null + * @deprecated 3.3 Use FormHelper::attributes($xml, $attributes); + */ + public static function xmlAddAttributes(&$xml, $attributes = []) + { + FormHelper::attributes($xml, $attributes); + } + + /** + * xmlAddOptions + * + * @param SimpleXMLElement $xml The XML element reference in which to inject a comment + * @param array $options The options to apply to the XML element + * + * @return void + * @deprecated 3.3 Use FormHelper::options($xml, $options); + */ + public static function xmlAddOptions(&$xml, $options = []) + { + FormHelper::options($xml, $options); + } + + /** + * get the field object + * + * @param array $attributes The array of attributes + * @param string $default The default of the field + * @param array $options The options to apply to the XML element + * + * @return object + * @deprecated 3.3 Use FormHelper::field($attributes, $default, $options); + */ + public static function getFieldObject(&$attributes, $default = '', $options = null) + { + return FormHelper::field($attributes, $default, $options); + } + + /** + * get the field xml + * + * @param array $attributes The array of attributes + * @param array $options The options to apply to the XML element + * + * @return object + * @deprecated 3.3 Use FormHelper::xml($attributes, $options); + */ + public static function getFieldXML(&$attributes, $options = null) + { + return FormHelper::xml($attributes, $options); + } + + /** + * Render Bool Button + * + * @param array $args All the args for the button + * 0) name + * 1) additional (options class) // not used at this time + * 2) default + * 3) yes (name) + * 4) no (name) + * + * @return string The input html of the button + * + */ + public static function renderBoolButton() + { + $args = func_get_args(); + // check if there is additional button class + $additional = isset($args[1]) ? (string) $args[1] : ''; // not used at this time + // button attributes + $buttonAttributes = array( + 'type' => 'radio', + 'name' => isset($args[0]) ? UtilitiesStringHelper::html($args[0]) : 'bool_button', + 'label' => isset($args[0]) ? UtilitiesStringHelper::safe(UtilitiesStringHelper::html($args[0]), 'Ww') : 'Bool Button', // not seen anyway + 'class' => 'btn-group', + 'filter' => 'INT', + 'default' => isset($args[2]) ? (int) $args[2] : 0); + // set the button options + $buttonOptions = array( + '1' => isset($args[3]) ? UtilitiesStringHelper::html($args[3]) : 'JYES', + '0' => isset($args[4]) ? UtilitiesStringHelper::html($args[4]) : 'JNO'); + // return the input + return FormHelper::field($buttonAttributes, $buttonAttributes['default'], $buttonOptions)->input; + } + + /** + * Check if have an json string + * + * @input string The json string to check + * + * @returns bool true on success + * @deprecated 3.3 Use JsonHelper::check($string); + */ + public static function checkJson($string) + { + return JsonHelper::check($string); + } + + /** + * Check if have an object with a length + * + * @input object The object to check + * + * @returns bool true on success + * @deprecated 3.3 Use ObjectHelper::check($object); + */ + public static function checkObject($object) + { + return ObjectHelper::check($object); + } + + /** + * Check if have an array with a length + * + * @input array The array to check + * + * @returns bool/int number of items in array on success + * @deprecated 3.3 Use UtilitiesArrayHelper::check($array, $removeEmptyString); + */ + public static function checkArray($array, $removeEmptyString = false) + { + return UtilitiesArrayHelper::check($array, $removeEmptyString); + } + + /** + * Check if have a string with a length + * + * @input string The string to check + * + * @returns bool true on success + * @deprecated 3.3 Use UtilitiesStringHelper::check($string); + */ + public static function checkString($string) + { + return UtilitiesStringHelper::check($string); + } + + /** + * Check if we are connected + * Thanks https://stackoverflow.com/a/4860432/1429677 + * + * @returns bool true on success + */ + public static function isConnected() + { + // If example.com is down, then probably the whole internet is down, since IANA maintains the domain. Right? + $connected = @fsockopen("www.example.com", 80); + // website, port (try 80 or 443) + if ($connected) + { + //action when connected + $is_conn = true; + fclose($connected); + } + else + { + //action in connection failure + $is_conn = false; + } + return $is_conn; + } + + /** + * Merge an array of array's + * + * @input array The arrays you would like to merge + * + * @returns array on success + * @deprecated 3.3 Use UtilitiesArrayHelper::merge($arrays); + */ + public static function mergeArrays($arrays) + { + return UtilitiesArrayHelper::merge($arrays); + } + + // typo sorry! + public static function sorten($string, $length = 40, $addTip = true) + { + return self::shorten($string, $length, $addTip); + } + + /** + * Shorten a string + * + * @input string The you would like to shorten + * + * @returns string on success + * @deprecated 3.3 Use UtilitiesStringHelper::shorten(...); + */ + public static function shorten($string, $length = 40, $addTip = true) + { + return UtilitiesStringHelper::shorten($string, $length, $addTip); + } + + /** + * Making strings safe (various ways) + * + * @input string The you would like to make safe + * + * @returns string on success + * @deprecated 3.3 Use UtilitiesStringHelper::safe(...); + */ + public static function safeString($string, $type = 'L', $spacer = '_', $replaceNumbers = true, $keepOnlyCharacters = true) + { + return UtilitiesStringHelper::safe( + $string, + $type, + $spacer, + $replaceNumbers, + $keepOnlyCharacters + ); + } + + /** + * Convert none English strings to code usable string + * + * @input an string + * + * @returns a string + * @deprecated 3.3 Use UtilitiesStringHelper::transliterate($string); + */ + public static function transliterate($string) + { + return UtilitiesStringHelper::transliterate($string); + } + + /** + * make sure a string is HTML save + * + * @input an html string + * + * @returns a string + * @deprecated 3.3 Use UtilitiesStringHelper::html(...); + */ + public static function htmlEscape($var, $charset = 'UTF-8', $shorten = false, $length = 40) + { + return UtilitiesStringHelper::html( + $var, + $charset, + $shorten, + $length + ); + } + + /** + * Convert all int in a string to an English word string + * + * @input an string with numbers + * + * @returns a string + * @deprecated 3.3 Use UtilitiesStringHelper::numbers($string); + */ + public static function replaceNumbers($string) + { + return UtilitiesStringHelper::numbers($string); + } + + /** + * Convert an integer into an English word string + * Thanks to Tom Nicholson + * + * @input an int + * @returns a string + * @deprecated 3.3 Use UtilitiesStringHelper::number($x); + */ + public static function numberToString($x) + { + return UtilitiesStringHelper::number($x); + } + + /** + * Random Key + * + * @returns a string + * @deprecated 3.3 Use UtilitiesStringHelper::random($size); + */ + public static function randomkey($size) + { + return UtilitiesStringHelper::random($size); + } + + /** + * Get The Encryption Keys + * + * @param string $type The type of key + * @param string/bool $default The return value if no key was found + * + * @return string On success + * + **/ + public static function getCryptKey($type, $default = false) + { + // Get the global params + $params = ComponentHelper::getParams('com_sermondistributor', true); + // Basic Encryption Type + if ('basic' === $type) + { + $basic_key = $params->get('basic_key', $default); + if (UtilitiesStringHelper::check($basic_key)) + { + return $basic_key; + } + } + + return $default; + } +} diff --git a/admin/models/rules/index.html b/admin/src/Helper/index.html similarity index 100% rename from admin/models/rules/index.html rename to admin/src/Helper/index.html diff --git a/admin/models/ajax.php b/admin/src/Model/AjaxModel.php similarity index 78% rename from admin/models/ajax.php rename to admin/src/Model/AjaxModel.php index 8210fce0..f0a1f37e 100644 --- a/admin/models/ajax.php +++ b/admin/src/Model/AjaxModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage ajax.php + @subpackage AjaxModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,39 +21,92 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\LayoutHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\Registry\Registry; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\FileHelper; +use VDM\Joomla\Utilities\StringHelper; +use VDM\Joomla\Utilities\JsonHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\GetHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Sermondistributor Ajax List Model + * + * @since 1.6 */ -class SermondistributorModelAjax extends ListModel +class AjaxModel extends ListModel { - protected $app_params; - - public function __construct() - { - parent::__construct(); - // get params - $this->app_params = JComponentHelper::getParams('com_sermondistributor'); - + /** + * The component params. + * + * @var Registry + * @since 3.2.0 + */ + protected Registry $app_params; + + /** + * The application object. + * + * @var CMSApplicationInterface The application instance. + * @since 3.2.0 + */ + protected CMSApplicationInterface $app; + + /** + * Constructor + * + * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). + * @param ?MVCFactoryInterface $factory The factory. + * + * @since 1.6 + * @throws \Exception + */ + public function __construct($config = [], MVCFactoryInterface $factory = null) + { + parent::__construct($config, $factory); + + $this->app_params = ComponentHelper::getParams('com_sermondistributor'); + $this->app ??= Factory::getApplication(); } // Used in sermon /** - * Check and if a vdm notice is new (per/user) - **/ - public function isNew($notice) + * Check and if a notice is new (per/user) + * + * @param string|null $notice The current notice + * + * @return bool true if is new + * @since 2.0.0 + */ + public function isNew(?string $notice): bool { // first get the file path - $path_filename = SermondistributorHelper::getFilePath('path', 'usernotice', 'md', JFactory::getUser()->username, JPATH_COMPONENT_ADMINISTRATOR); + $path_filename = FileHelper::getPath('path', 'usernotice', 'md', Factory::getUser()->username, JPATH_COMPONENT_ADMINISTRATOR); + // check if the file is set - if (($content = @file_get_contents($path_filename)) !== FALSE) + if (($content = FileHelper::getContent($path_filename, FALSE)) !== FALSE) { if ($notice == $content) { @@ -64,33 +117,28 @@ class SermondistributorModelAjax extends ListModel } /** - * set That a notice has been read (per/user) - **/ - public function isRead($notice) + * Check if a notice has been read (per/user) + * + * @param string|null $notice The current notice + * + * @return bool true if is read + * @since 2.0.0 + */ + public function isRead(?string $notice): bool { // first get the file path - $path_filename = SermondistributorHelper::getFilePath('path', 'usernotice', 'md', JFactory::getUser()->username, JPATH_COMPONENT_ADMINISTRATOR); + $path_filename = FileHelper::getPath('path', 'usernotice', 'md', Factory::getUser()->username, JPATH_COMPONENT_ADMINISTRATOR); + // set as read if not already set - if (($content = @file_get_contents($path_filename)) !== FALSE) + if (($content = FileHelper::getContent($path_filename, FALSE)) !== FALSE) { if ($notice == $content) { return true; } } - return $this->saveFile($notice,$path_filename); - } - protected function saveFile($data,$path_filename) - { - if (SermondistributorHelper::checkString($data)) - { - $fp = fopen($path_filename, 'w'); - fwrite($fp, $data); - fclose($fp); - return true; - } - return false; + return FileHelper::write($path_filename, $notice); } // Used in external_source @@ -113,8 +161,8 @@ class SermondistributorModelAjax extends ListModel { // set the headers $headers = array( - 'tsharedurl' => JText::_('COM_SERMONDISTRIBUTOR_SHAREDURL'), - 'tfolder' => JText::_('COM_SERMONDISTRIBUTOR_TARGETED_FOLDER') + 'tsharedurl' => Text::_('COM_SERMONDISTRIBUTOR_SHAREDURL'), + 'tfolder' => Text::_('COM_SERMONDISTRIBUTOR_TARGETED_FOLDER') ); // loop the array foreach ($headers as $key => $lang) @@ -128,7 +176,7 @@ class SermondistributorModelAjax extends ListModel $functions = range(0,10); foreach ($functions as $function) { - $function = 'setAutoLang'.SermondistributorHelper::safeString($function, 'f'); + $function = 'setAutoLang'.StringHelper::safe($function, 'f'); if (method_exists($this, $function)) { $this->{$function}(); @@ -136,7 +184,7 @@ class SermondistributorModelAjax extends ListModel } foreach ($functions as $function) { - $function = 'setAutoFunc'.SermondistributorHelper::safeString($function, 'f'); + $function = 'setAutoFunc'.StringHelper::safe($function, 'f'); if (method_exists($this, $function)) { $this->{$function}(); @@ -146,10 +194,10 @@ class SermondistributorModelAjax extends ListModel public function getBuildTable($idName,$oject) { - if (SermondistributorHelper::checkJson($oject) && SermondistributorHelper::checkString($idName)) + if (JsonHelper::check($oject) && StringHelper::check($idName)) { $array = json_decode($oject, true); - if (SermondistributorHelper::checkArray($array)) + if (UtilitiesArrayHelper::check($array)) { // make sure we run the autoloader to insure all is set $this->autoLoader(); @@ -160,9 +208,9 @@ class SermondistributorModelAjax extends ListModel $rows = array(); foreach ($array as $header => $values) { - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { - $targetHeader = (isset($targetHeaders[$header])) ? $targetHeaders[$header] : SermondistributorHelper::safeString($header, 'W'); + $targetHeader = (isset($targetHeaders[$header])) ? $targetHeaders[$header] : StringHelper::safe($header, 'W'); $table .= ''.$targetHeader.''; foreach ($values as $nr => $value) { @@ -174,7 +222,7 @@ class SermondistributorModelAjax extends ListModel // close header start body $table .= ''; // add rows to table - if (SermondistributorHelper::checkArray($rows)) + if (UtilitiesArrayHelper::check($rows)) { foreach ($rows as $row) { @@ -198,7 +246,7 @@ class SermondistributorModelAjax extends ListModel $value = $this->{$this->functionArray[$header]}($header,$value); } // if no value are set - if (!SermondistributorHelper::checkString($value)) + if (!StringHelper::check($value)) { $value = '-'; } @@ -228,10 +276,10 @@ class SermondistributorModelAjax extends ListModel **/ public function getCronPath($type) { - $result = array('error' => '' . JText::_('COM_SERMONDISTRIBUTOR_NO_CRONJOB_PATH_FOUND_SINCE_INCORRECT_TYPE_REQUESTED') . ''); + $result = array('error' => '' . Text::_('COM_SERMONDISTRIBUTOR_NO_CRONJOB_PATH_FOUND_SINCE_INCORRECT_TYPE_REQUESTED') . ''); if ('externalUpdate' === $type) { - $result['error'] = '' . JText::sprintf('COM_SERMONDISTRIBUTOR_NO_CRONJOB_PATH_FOUND_FOR_S', $type) . ''; + $result['error'] = '' . Text::sprintf('COM_SERMONDISTRIBUTOR_NO_CRONJOB_PATH_FOUND_FOR_S', $type) . ''; if ($this->hasCurl()) { $path = '*/15 * * * * curl -s "' .JURI::root() . 'index.php?option=com_sermondistributor&task=api.externalUpdate" >/dev/null 2>&1'; @@ -265,14 +313,14 @@ class SermondistributorModelAjax extends ListModel $type = 'auto'; } // first get the file path - $path_filename = SermondistributorHelper::getFilePath('update', 'error', $id.$target.$typeID, '.txt', JPATH_COMPONENT_ADMINISTRATOR); + $path_filename = FileHelper::getPath('update', 'error', $id.$target.$typeID, '.txt', JPATH_COMPONENT_ADMINISTRATOR); // check "die sleutel" and the type - if (isset($type) && SermondistributorHelper::checkString($sleutel)) + if (isset($type) && StringHelper::check($sleutel)) { // get database object - if (!isset($this->db) || !SermondistributorHelper::checkObject($this->db)) + if (!isset($this->db) || !ObjectHelper::check($this->db)) { - $this->db = JFactory::getDBO(); + $this->db = Factory::getDBO(); } // run the update if (SermondistributorHelper::updateExternalSource($id, $target, $type, true, $sleutel)) @@ -292,7 +340,7 @@ class SermondistributorModelAjax extends ListModel return array('error' => $error); } // store the error - $error = JText::_('COM_SERMONDISTRIBUTOR_BCOULD_NOT_USE_THE_GIVEN_TOKEN_OR_THE_GIVEN_BUILD_OPTION_DOES_NOT_EXISTB'); + $error = Text::_('COM_SERMONDISTRIBUTOR_BCOULD_NOT_USE_THE_GIVEN_TOKEN_OR_THE_GIVEN_BUILD_OPTION_DOES_NOT_EXISTB'); SermondistributorHelper::writeFile($path_filename,$error); return array('error' => $error); } @@ -304,12 +352,12 @@ class SermondistributorModelAjax extends ListModel { // check if we should update with auto listing $links_dropbox_auto = SermondistributorHelper::getExternalSourceLink('auto', 2); - if (SermondistributorHelper::checkArray($links_dropbox_auto)) + if (UtilitiesArrayHelper::check($links_dropbox_auto)) { // load system aliases $this->getSermonAliasesUsed(); // set the class var for sermons - $this->sermons = new stdClass(); + $this->sermons = new \stdClass(); // we must first get all the preacher names foreach ($links_dropbox_auto as $placeholder => $link) { @@ -353,7 +401,7 @@ class SermondistributorModelAjax extends ListModel protected function setSermons() { // check if we have values - if (SermondistributorHelper::checkObject($this->sermons)) + if (ObjectHelper::check($this->sermons)) { foreach ($this->sermons as $sermon) { @@ -420,7 +468,7 @@ class SermondistributorModelAjax extends ListModel $fields = array( $this->db->quoteName('published') . ' = 0' ); - if (isset($this->allSermons) && SermondistributorHelper::checkArray($this->allSermons)) + if (isset($this->allSermons) && UtilitiesArrayHelper::check($this->allSermons)) { // unpublish those AUTO sermons not found in this id list $conditions = array( @@ -513,7 +561,7 @@ class SermondistributorModelAjax extends ListModel else { // load the sermon data - $this->sermons->$key = new stdClass(); + $this->sermons->$key = new \stdClass(); } // check if this value has been set if (!isset($this->sermons->$key->alias)) @@ -534,7 +582,7 @@ class SermondistributorModelAjax extends ListModel $this->sermons->$key->name = $name; } // check if this value has been set - if (!isset($this->sermons->$key->short_description) && SermondistributorHelper::checkString($description)) + if (!isset($this->sermons->$key->short_description) && StringHelper::check($description)) { $this->sermons->$key->short_description = $description; } @@ -557,32 +605,32 @@ class SermondistributorModelAjax extends ListModel if (!isset($this->sermons->$key->created)) { // set the date object - $date = JFactory::getDate(); + $date = Factory::getDate(); $this->sermons->$key->created = $date->toSql(); } // build the Download File NAme - first add the preacher name if set if ($preacher) { - $downloadName[] = SermondistributorHelper::safeString($preacherName,'U'); + $downloadName[] = StringHelper::safe($preacherName,'U'); } // add the series name if set if ($series) { - $downloadName[] = SermondistributorHelper::safeString($seriesName,'F'); + $downloadName[] = StringHelper::safe($seriesName,'F'); } // add the category name if set if ($category) { - $downloadName[] = SermondistributorHelper::safeString($categoryName, 'F'); + $downloadName[] = StringHelper::safe($categoryName, 'F'); } // add the main file name - $downloadName[] = SermondistributorHelper::safeString($name,'F'); + $downloadName[] = StringHelper::safe($name,'F'); // now build the download file name $downloadName = implode('__', $downloadName).'.'.$fileType; // load the placeholder to the sermon $this->sermons->$key->auto_sermons[$downloadName] = $placeholder; // set default metadate - if (!isset($this->sermons->$key->metadesc) && SermondistributorHelper::checkString($description)) + if (!isset($this->sermons->$key->metadesc) && StringHelper::check($description)) { // Only process once per/sermon $bad_characters = array("\"", "<", ">"); @@ -613,7 +661,7 @@ class SermondistributorModelAjax extends ListModel protected function getAlias($name,$type = false) { // sanitize the name to an alias - if (JFactory::getConfig()->get('unicodeslugs') == 1) + if (Factory::getConfig()->get('unicodeslugs') == 1) { $alias = JFilterOutput::stringURLUnicodeSlug($name); } @@ -633,7 +681,7 @@ class SermondistributorModelAjax extends ListModel // sanitize the name to an alias $alias = $this->getAlias($name); // check if there is a recored - if ($id = SermondistributorHelper::getVar($type, $alias, 'alias', 'id')) + if ($id = GetHelper::var($type, $alias, 'alias', 'id')) { return $id; } @@ -646,9 +694,9 @@ class SermondistributorModelAjax extends ListModel $name = ucwords($name); } // create the record - $object = new stdClass(); + $object = new \stdClass(); // set the date object - $date = JFactory::getDate(); + $date = Factory::getDate(); // build the object $object->name = $name; $object->alias = $alias; diff --git a/admin/models/external_source.php b/admin/src/Model/External_sourceModel.php similarity index 77% rename from admin/models/external_source.php rename to admin/src/Model/External_sourceModel.php index ed46cdc8..560e4121 100644 --- a/admin/models/external_source.php +++ b/admin/src/Model/External_sourceModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage external_source.php + @subpackage External_sourceModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,24 +21,49 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Form\Form; +use Joomla\CMS\Filter\InputFilter; +use Joomla\CMS\Filter\OutputFilter; use Joomla\CMS\MVC\Model\AdminModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Table\Table; +use Joomla\CMS\UCM\UCMType; +use Joomla\CMS\Versioning\VersionableModelTrait; +use Joomla\CMS\User\User; use Joomla\Registry\Registry; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\StringHelper as UtilitiesStringHelper; +use VDM\Joomla\Utilities\FileHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\FOF\Encrypt\AES; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermondistributor External_source Admin Model + * + * @since 1.6 */ -class SermondistributorModelExternal_source extends AdminModel +class External_sourceModel extends AdminModel { + use VersionableModelTrait; + /** * The tab layout fields array. * - * @var array + * @var array + * @since 3.0.0 */ protected $tabLayoutFields = array( 'details' => array( @@ -77,7 +102,29 @@ class SermondistributorModelExternal_source extends AdminModel ); /** - * @var string The prefix to use with controller messages. + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/external_source.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js', + 'media/com_sermondistributor/js/external_source.js' + ]; + + /** + * @var string The prefix to use with controller messages. * @since 1.6 */ protected $text_prefix = 'COM_SERMONDISTRIBUTOR'; @@ -97,16 +144,14 @@ class SermondistributorModelExternal_source extends AdminModel * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * - * @return JTable A database object - * - * @since 1.6 + * @return Table A database object + * @since 3.0 + * @throws \Exception */ - public function getTable($type = 'external_source', $prefix = 'SermondistributorTable', $config = array()) + public function getTable($type = 'external_source', $prefix = 'Administrator', $config = []) { - // add table path for when model gets used from other component - $this->addTablePath(JPATH_ADMINISTRATOR . '/components/com_sermondistributor/tables'); // get instance of the table - return JTable::getInstance($type, $prefix, $config); + return parent::getTable($type, $prefix, $config); } public function clearLocalListing($id) @@ -114,7 +159,7 @@ class SermondistributorModelExternal_source extends AdminModel // clear local listings if ($id > 0) { - $db = JFactory::getDbo(); + $db = Factory::getDbo(); $query = $db->getQuery(true); $conditions = array( @@ -146,7 +191,7 @@ class SermondistributorModelExternal_source extends AdminModel // build info file key $targetArray = explode(', ', $target); $targetArray[2] = ($targetArray[2] == 2) ? 'auto' : 'manual'; - $infoFileKey = SermondistributorHelper::safeString(implode('', $targetArray)); + $infoFileKey = UtilitiesStringHelper::safe(implode('', $targetArray)); $infoFileName = md5($infoFileKey.'info').'.json'; // info on update path $infoFilePath = JPATH_COMPONENT_SITE.'/helpers/'.$infoFileName; @@ -155,42 +200,41 @@ class SermondistributorModelExternal_source extends AdminModel { if (!JFile::delete($infoFilePath)) { - $errors[] = JText::sprintf('COM_SERMONDISTRIBUTOR_S_COULD_NOT_BE_REMOVE', $infoFileName); + $errors[] = Text::sprintf('COM_SERMONDISTRIBUTOR_S_COULD_NOT_BE_REMOVE', $infoFileName); } } // remove any notice on update errors $key = preg_replace('/[ ,]+/', '', trim($target)); - $noticeFilePath = SermondistributorHelper::getFilePath('update', 'error', $key, '.txt', JPATH_COMPONENT_ADMINISTRATOR); + $noticeFilePath = FileHelper::getPath('update', 'error', $key, '.txt', JPATH_COMPONENT_ADMINISTRATOR); // now remove file if found if (JFile::exists($noticeFilePath)) { if (!JFile::delete($noticeFilePath)) { $noticeFileName = basename($noticeFilePath); - $errors[] = JText::sprintf('COM_SERMONDISTRIBUTOR_S_COULD_NOT_BE_REMOVE', $noticeFileName); + $errors[] = Text::sprintf('COM_SERMONDISTRIBUTOR_S_COULD_NOT_BE_REMOVE', $noticeFileName); } } } // check if there was an error - if (SermondistributorHelper::checkArray($errors)) + if (UtilitiesArrayHelper::check($errors)) { return array('error' => '
  • '.implode('
  • ', $errors).'
'); } return true; } - return array('error' => JText::_('COM_SERMONDISTRIBUTOR_THERE_IS_NO_TARGETS_SET_FOR_THIS_SOURCE_CAN_NOT_RESET_THE_UPDATE_STATUS')); + return array('error' => Text::_('COM_SERMONDISTRIBUTOR_THERE_IS_NO_TARGETS_SET_FOR_THIS_SOURCE_CAN_NOT_RESET_THE_UPDATE_STATUS')); } - return array('error' => JText::_('COM_SERMONDISTRIBUTOR_NO_ID_FOUND_CAN_NOT_RESET_THE_UPDATE_STATUS')); + return array('error' => Text::_('COM_SERMONDISTRIBUTOR_NO_ID_FOUND_CAN_NOT_RESET_THE_UPDATE_STATUS')); } - + /** * 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) @@ -216,7 +260,7 @@ class SermondistributorModelExternal_source extends AdminModel // Get the basic encryption. $basickey = SermondistributorHelper::getCryptKey('basic'); // Get the encryption object. - $basic = new FOFEncryptAes($basickey); + $basic = new AES($basickey); if (!empty($item->oauthtoken) && $basickey && !is_numeric($item->oauthtoken) && $item->oauthtoken === base64_encode(base64_decode($item->oauthtoken, true))) { @@ -241,11 +285,10 @@ class SermondistributorModelExternal_source extends AdminModel * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @param array $options Optional array of options for the form creation. * - * @return mixed A JForm object on success, false on failure - * + * @return Form|boolean A Form object on success, false on failure * @since 1.6 */ - public function getForm($data = array(), $loadData = true, $options = array('control' => 'jform')) + public function getForm($data = [], $loadData = true, $options = ['control' => 'jform']) { // set load data option $options['load_data'] = $loadData; @@ -272,7 +315,7 @@ class SermondistributorModelExternal_source extends AdminModel return false; } - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first. if ($jinput->get('a_id')) @@ -285,7 +328,7 @@ class SermondistributorModelExternal_source extends AdminModel $id = $jinput->get('id', 0, 'INT'); } - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Check for existing item. // Modify the form based on Edit State access controls. @@ -346,38 +389,66 @@ class SermondistributorModelExternal_source extends AdminModel } /** - * Method to get the script that have to be included on the form + * Method to get the styles that have to be included on the view * - * @return string script files + * @return array styles files + * @since 4.3 */ - public function getScript() + public function getStyles(): array { - return 'media/com_sermondistributor/js/external_source.js'; + return $this->styles; } - + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * 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 set in the component. - * * @since 1.6 */ protected function canDelete($record) { - if (!empty($record->id)) + if (empty($record->id) || ($record->published != -2)) { - if ($record->published != -2) - { - return; - } - - $user = JFactory::getUser(); - // The record has been set. Check the record permissions. - return $user->authorise('external_source.delete', 'com_sermondistributor.external_source.' . (int) $record->id); + return false; } - return false; + + // The record has been set. Check the record permissions. + return $this->getCurrentUser()->authorise('external_source.delete', 'com_sermondistributor.external_source.' . (int) $record->id); } /** @@ -386,13 +457,12 @@ class SermondistributorModelExternal_source extends AdminModel * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. - * * @since 1.6 */ protected function canEditState($record) { - $user = JFactory::getUser(); - $recordId = (!empty($record->id)) ? $record->id : 0; + $user = $this->getCurrentUser(); + $recordId = $record->id ?? 0; if ($recordId) { @@ -403,51 +473,50 @@ class SermondistributorModelExternal_source extends AdminModel return false; } } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('external_source.edit.state', 'com_sermondistributor'); } - + /** * Method override to check if you can edit an existing record. * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key. + * @param array $data An array of input data. + * @param string $key The name of the key for the primary key. * - * @return boolean - * @since 2.5 + * @return boolean + * @since 2.5 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // Check specific edit permission then general edit permission. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); return $user->authorise('external_source.edit', 'com_sermondistributor.external_source.'. ((int) isset($data[$key]) ? $data[$key] : 0)) or $user->authorise('external_source.edit', 'com_sermondistributor'); } - + /** * Prepare and sanitise the table data prior to saving. * - * @param JTable $table A JTable object. + * @param Table $table A Table object. * * @return void - * * @since 1.6 */ protected function prepareTable($table) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); - + $date = Factory::getDate(); + $user = $this->getCurrentUser(); + if (isset($table->name)) { - $table->name = htmlspecialchars_decode($table->name, ENT_QUOTES); + $table->name = \htmlspecialchars_decode($table->name, ENT_QUOTES); } - + if (isset($table->alias) && empty($table->alias)) { $table->generateAlias(); } - + if (empty($table->id)) { $table->created = $date->toSql(); @@ -459,7 +528,7 @@ class SermondistributorModelExternal_source extends AdminModel // Set ordering to the last item if not set if (empty($table->ordering)) { - $db = JFactory::getDbo(); + $db = $this->getDatabase(); $query = $db->getQuery(true) ->select('MAX(ordering)') ->from($db->quoteName('#__sermondistributor_external_source')); @@ -474,7 +543,7 @@ class SermondistributorModelExternal_source extends AdminModel $table->modified = $date->toSql(); $table->modified_by = $user->id; } - + if (!empty($table->id)) { // Increment the items version number. @@ -486,21 +555,21 @@ class SermondistributorModelExternal_source extends AdminModel * Method to get the data that should be injected in the form. * * @return mixed The data for the form. - * * @since 1.6 */ - protected function loadFormData() + protected function loadFormData() { // Check the session for previously entered form data. - $data = JFactory::getApplication()->getUserState('com_sermondistributor.edit.external_source.data', array()); + $data = Factory::getApplication()->getUserState('com_sermondistributor.edit.external_source.data', []); if (empty($data)) { $data = $this->getItem(); - // run the perprocess of the data - $this->preprocessData('com_sermondistributor.external_source', $data); } + // run the perprocess of the data + $this->preprocessData('com_sermondistributor.external_source', $data); + return $data; } @@ -520,7 +589,7 @@ class SermondistributorModelExternal_source extends AdminModel public function validate($form, $data, $group = null) { // check if the not_required field is set - if (isset($data['not_required']) && SermondistributorHelper::checkString($data['not_required'])) + if (isset($data['not_required']) && UtilitiesStringHelper::check($data['not_required'])) { $requiredFields = (array) explode(',',(string) $data['not_required']); $requiredFields = array_unique($requiredFields); @@ -528,7 +597,7 @@ class SermondistributorModelExternal_source extends AdminModel foreach ($requiredFields as $requiredField) { // make sure there is a string value - if (SermondistributorHelper::checkString($requiredField)) + if (UtilitiesStringHelper::check($requiredField)) { // change to false $form->setFieldAttribute($requiredField, 'required', 'false'); @@ -551,14 +620,13 @@ class SermondistributorModelExternal_source extends AdminModel { return false; } - + /** * Method to delete one or more records. * * @param array &$pks An array of record primary keys. * - * @return boolean True if successful, false if an error occurs. - * + * @return boolean True if successful, false if an error occurs * @since 12.2 */ public function delete(&$pks) @@ -567,7 +635,7 @@ class SermondistributorModelExternal_source extends AdminModel { return false; } - + return true; } @@ -578,7 +646,6 @@ class SermondistributorModelExternal_source extends AdminModel * @param integer $value The value of the published state. * * @return boolean True on success. - * * @since 12.2 */ public function publish(&$pks, $value = 1) @@ -587,10 +654,10 @@ class SermondistributorModelExternal_source extends AdminModel { return false; } - + return true; - } - + } + /** * Method to perform batch operations on an item or a set of items. * @@ -599,7 +666,6 @@ class SermondistributorModelExternal_source extends AdminModel * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. - * * @since 12.2 */ public function batch($commands, $pks, $contexts) @@ -616,30 +682,30 @@ class SermondistributorModelExternal_source extends AdminModel if (empty($pks)) { - $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); + $this->setError(Text::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; // Set some needed variables. - $this->user = JFactory::getUser(); - $this->table = $this->getTable(); - $this->tableClassName = get_class($this->table); - $this->contentType = new JUcmType; - $this->type = $this->contentType->getTypeByTable($this->tableClassName); - $this->canDo = SermondistributorHelper::getActions('external_source'); - $this->batchSet = true; + $this->user ??= $this->getCurrentUser(); + $this->table = $this->getTable(); + $this->tableClassName = get_class($this->table); + $this->contentType = new UCMType; + $this->type = $this->contentType->getTypeByTable($this->tableClassName); + $this->canDo = SermondistributorHelper::getActions('external_source'); + $this->batchSet = true; if (!$this->canDo->get('core.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } - + if ($this->type == false) { - $type = new JUcmType; + $type = new UCMType; $this->type = $type->getTypeByAlias($this->typeAlias); } @@ -676,8 +742,7 @@ class SermondistributorModelExternal_source extends AdminModel if (!$done) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); - + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } @@ -703,7 +768,7 @@ class SermondistributorModelExternal_source extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('external_source'); @@ -729,7 +794,7 @@ class SermondistributorModelExternal_source extends AdminModel $values['published'] = 0; } - $newIds = array(); + $newIds = []; // Parent exists so let's proceed while (!empty($pks)) { @@ -742,7 +807,7 @@ class SermondistributorModelExternal_source extends AdminModel if (!$this->user->authorise('external_source.edit', $contexts[$pk])) { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } @@ -758,19 +823,19 @@ class SermondistributorModelExternal_source extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // Only for strings - if (SermondistributorHelper::checkString($this->table->description) && !is_numeric($this->table->description)) + if (UtilitiesStringHelper::check($this->table->description) && !is_numeric($this->table->description)) { $this->table->description = $this->generateUnique('description',$this->table->description); } // insert all set values - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -782,7 +847,7 @@ class SermondistributorModelExternal_source extends AdminModel } // update all unique fields - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -846,7 +911,7 @@ class SermondistributorModelExternal_source extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('external_source'); @@ -854,7 +919,7 @@ class SermondistributorModelExternal_source extends AdminModel if (!$this->canDo->get('external_source.edit') && !$this->canDo->get('external_source.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -871,7 +936,7 @@ class SermondistributorModelExternal_source extends AdminModel { if (!$this->user->authorise('external_source.edit', $contexts[$pk])) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -887,13 +952,13 @@ class SermondistributorModelExternal_source extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // insert all set values. - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -937,27 +1002,26 @@ class SermondistributorModelExternal_source extends AdminModel return true; } - + /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. - * * @since 1.6 */ public function save($data) { - $input = JFactory::getApplication()->input; - $filter = JFilterInput::getInstance(); - + $input = Factory::getApplication()->getInput(); + $filter = InputFilter::getInstance(); + // set the metadata to the Item Data if (isset($data['metadata']) && isset($data['metadata']['author'])) { $data['metadata']['author'] = $filter->clean($data['metadata']['author'], 'TRIM'); - - $metadata = new JRegistry; + + $metadata = new Registry; $metadata->loadArray($data['metadata']); $data['metadata'] = (string) $metadata; } @@ -971,18 +1035,18 @@ class SermondistributorModelExternal_source extends AdminModel // Get the basic encryption key. $basickey = SermondistributorHelper::getCryptKey('basic'); // Get the encryption object - $basic = new FOFEncryptAes($basickey); + $basic = new AES($basickey); // Encrypt data oauthtoken. if (isset($data['oauthtoken']) && $basickey) { $data['oauthtoken'] = $basic->encryptString($data['oauthtoken']); } - + // Set the Params Items to data if (isset($data['params']) && is_array($data['params'])) { - $params = new JRegistry; + $params = new Registry; $params->loadArray($data['params']); $data['params'] = (string) $params; } @@ -992,7 +1056,7 @@ class SermondistributorModelExternal_source extends AdminModel { // Automatic handling of other unique fields $uniqueFields = $this->getUniqueFields(); - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -1000,14 +1064,14 @@ class SermondistributorModelExternal_source extends AdminModel } } } - + if (parent::save($data)) { return true; } return false; } - + /** * Method to generate a unique value. * @@ -1015,16 +1079,14 @@ class SermondistributorModelExternal_source extends AdminModel * @param string $value data. * * @return string New value. - * * @since 3.0 */ - protected function generateUnique($field,$value) + protected function generateUnique($field, $value) { - // set field value unique $table = $this->getTable(); - while ($table->load(array($field => $value))) + while ($table->load([$field => $value])) { $value = StringHelper::increment($value); } @@ -1046,7 +1108,7 @@ class SermondistributorModelExternal_source extends AdminModel // Alter the title $table = $this->getTable(); - while ($table->load(array('title' => $title))) + while ($table->load(['title' => $title])) { $title = StringHelper::increment($title); } diff --git a/admin/models/external_sources.php b/admin/src/Model/External_sourcesModel.php similarity index 77% rename from admin/models/external_sources.php rename to admin/src/Model/External_sourcesModel.php index db5719f4..ce1d1980 100644 --- a/admin/models/external_sources.php +++ b/admin/src/Model/External_sourcesModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage external_sources.php + @subpackage External_sourcesModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,22 +21,78 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper; +use VDM\Joomla\FOF\Encrypt\AES; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * External_sources List Model + * + * @since 1.6 */ -class SermondistributorModelExternal_sources extends ListModel +class External_sourcesModel extends ListModel { - public function __construct($config = array()) + /** + * The application object. + * + * @var CMSApplicationInterface The application instance. + * @since 3.2.0 + */ + protected CMSApplicationInterface $app; + + /** + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/external_sources.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js' + ]; + + /** + * Constructor + * + * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). + * @param ?MVCFactoryInterface $factory The factory. + * + * @since 1.6 + * @throws \Exception + */ + public function __construct($config = [], MVCFactoryInterface $factory = null) { if (empty($config['filter_fields'])) - { + { $config['filter_fields'] = array( 'a.id','id', 'a.published','published', @@ -50,7 +106,9 @@ class SermondistributorModelExternal_sources extends ListModel ); } - parent::__construct($config); + parent::__construct($config, $factory); + + $this->app ??= Factory::getApplication(); } /** @@ -62,11 +120,11 @@ class SermondistributorModelExternal_sources extends ListModel * @param string $direction An optional direction (asc|desc). * * @return void - * + * @since 1.7.0 */ protected function populateState($ordering = null, $direction = null) { - $app = JFactory::getApplication(); + $app = $this->app; // Adjust the context to support modal layouts. if ($layout = $app->input->get('layout')) @@ -130,11 +188,12 @@ class SermondistributorModelExternal_sources extends ListModel // List state information. parent::populateState($ordering, $direction); } - + /** * Method to get an array of data items. * * @return mixed An array of data items on success, false on failure. + * @since 1.6 */ public function getItems() { @@ -145,12 +204,12 @@ class SermondistributorModelExternal_sources extends ListModel $items = parent::getItems(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -164,12 +223,12 @@ class SermondistributorModelExternal_sources extends ListModel // decode filetypes $filetypesArray = json_decode($item->filetypes, true); - if (SermondistributorHelper::checkArray($filetypesArray)) + if (UtilitiesArrayHelper::check($filetypesArray)) { - $filetypesNames = array(); + $filetypesNames = []; foreach ($filetypesArray as $filetypes) { - $filetypesNames[] = JText::_($this->selectionTranslation($filetypes, 'filetypes')); + $filetypesNames[] = Text::_($this->selectionTranslation($filetypes, 'filetypes')); } $item->filetypes = implode(', ', $filetypesNames); } @@ -177,7 +236,7 @@ class SermondistributorModelExternal_sources extends ListModel } // set selection value to a translatable value - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -192,7 +251,7 @@ class SermondistributorModelExternal_sources extends ListModel } } - + // return items return $items; } @@ -200,7 +259,7 @@ class SermondistributorModelExternal_sources extends ListModel /** * Method to convert selection values to translatable string. * - * @return translatable string + * @return string The translatable string. */ public function selectionTranslation($value,$name) { @@ -212,7 +271,7 @@ class SermondistributorModelExternal_sources extends ListModel 1 => 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_DROPBOX' ); // Now check if value is found in this array - if (isset($externalsourcesArray[$value]) && SermondistributorHelper::checkString($externalsourcesArray[$value])) + if (isset($externalsourcesArray[$value]) && StringHelper::check($externalsourcesArray[$value])) { return $externalsourcesArray[$value]; } @@ -225,7 +284,7 @@ class SermondistributorModelExternal_sources extends ListModel 2 => 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_AUTOMATIC' ); // Now check if value is found in this array - if (isset($update_methodArray[$value]) && SermondistributorHelper::checkString($update_methodArray[$value])) + if (isset($update_methodArray[$value]) && StringHelper::check($update_methodArray[$value])) { return $update_methodArray[$value]; } @@ -264,7 +323,7 @@ class SermondistributorModelExternal_sources extends ListModel '.gif' => 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_GIF' ); // Now check if value is found in this array - if (isset($filetypesArray[$value]) && SermondistributorHelper::checkString($filetypesArray[$value])) + if (isset($filetypesArray[$value]) && StringHelper::check($filetypesArray[$value])) { return $filetypesArray[$value]; } @@ -278,25 +337,26 @@ class SermondistributorModelExternal_sources extends ListModel 2 => 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_DYNAMIC_AUTOMATIC_BUILD' ); // Now check if value is found in this array - if (isset($buildArray[$value]) && SermondistributorHelper::checkString($buildArray[$value])) + if (isset($buildArray[$value]) && StringHelper::check($buildArray[$value])) { return $buildArray[$value]; } } return $value; } - + /** * Method to build an SQL query to load the list data. * - * @return string An SQL query + * @return string An SQL query + * @since 1.6 */ protected function getListQuery() { // Get the user object. - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -343,7 +403,7 @@ class SermondistributorModelExternal_sources extends ListModel $query->where('a.externalsources = ' . (int) $_externalsources); } } - elseif (SermondistributorHelper::checkString($_externalsources)) + elseif (StringHelper::check($_externalsources)) { $query->where('a.externalsources = ' . $db->quote($db->escape($_externalsources))); } @@ -360,7 +420,7 @@ class SermondistributorModelExternal_sources extends ListModel $query->where('a.update_method = ' . (int) $_update_method); } } - elseif (SermondistributorHelper::checkString($_update_method)) + elseif (StringHelper::check($_update_method)) { $query->where('a.update_method = ' . $db->quote($db->escape($_update_method))); } @@ -377,16 +437,18 @@ class SermondistributorModelExternal_sources extends ListModel $query->where('a.build = ' . (int) $_build); } } - elseif (SermondistributorHelper::checkString($_build)) + elseif (StringHelper::check($_build)) { $query->where('a.build = ' . $db->quote($db->escape($_build))); } // Add the list ordering clause. - $orderCol = $this->state->get('list.ordering', 'a.id'); - $orderDirn = $this->state->get('list.direction', 'desc'); + $orderCol = $this->getState('list.ordering', 'a.id'); + $orderDirn = $this->getState('list.direction', 'desc'); if ($orderCol != '') { + // Check that the order direction is valid encase we have a field called direction as part of filers. + $orderDirn = (is_string($orderDirn) && in_array(strtolower($orderDirn), ['asc', 'desc'])) ? $orderDirn : 'desc'; $query->order($db->escape($orderCol . ' ' . $orderDirn)); } @@ -404,17 +466,17 @@ class SermondistributorModelExternal_sources extends ListModel public function getExportData($pks, $user = null) { // setup the query - if (($pks_size = SermondistributorHelper::checkArray($pks)) !== false || 'bulk' === $pks) + if (($pks_size = UtilitiesArrayHelper::check($pks)) !== false || 'bulk' === $pks) { // Set a value to know this is export method. (USE IN CUSTOM CODE TO ALTER OUTCOME) $_export = true; // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -454,10 +516,10 @@ class SermondistributorModelExternal_sources extends ListModel // Get the basic encryption key. $basickey = SermondistributorHelper::getCryptKey('basic'); // Get the encryption object. - $basic = new FOFEncryptAes($basickey); + $basic = new AES($basickey); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -482,7 +544,7 @@ class SermondistributorModelExternal_sources extends ListModel } // Add headers to items array. $headers = $this->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { array_unshift($items,$headers); } @@ -500,16 +562,16 @@ class SermondistributorModelExternal_sources extends ListModel public function getExImPortHeaders() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getDbo(); // get the columns $columns = $db->getTableColumns("#__sermondistributor_external_source"); - if (SermondistributorHelper::checkArray($columns)) + if (UtilitiesArrayHelper::check($columns)) { // remove the headers you don't import/export. unset($columns['asset_id']); unset($columns['checked_out']); unset($columns['checked_out_time']); - $headers = new stdClass(); + $headers = new \stdClass(); foreach ($columns as $column => $type) { $headers->{$column} = $column; @@ -518,12 +580,12 @@ class SermondistributorModelExternal_sources extends ListModel } return false; } - + /** * Method to get a store id based on model configuration state. * * @return string A store id. - * + * @since 1.6 */ protected function getStoreId($id = '') { @@ -542,22 +604,65 @@ class SermondistributorModelExternal_sources extends ListModel return parent::getStoreId($id); } + /** + * Method to get the styles that have to be included on the view + * + * @return array styles files + * @since 4.3 + */ + public function getStyles(): array + { + return $this->styles; + } + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * Build an SQL query to checkin all items left checked out longer then a set time. * - * @return a bool - * + * @return bool + * @since 3.2.0 */ - protected function checkInNow() + protected function checkInNow(): bool { // Get set check in time - $time = JComponentHelper::getParams('com_sermondistributor')->get('check_in'); + $time = ComponentHelper::getParams('com_sermondistributor')->get('check_in'); if ($time) { - // Get a db connection. - $db = JFactory::getDbo(); + $db = $this->getDatabase(); // Reset query. $query = $db->getQuery(true); $query->select('*'); @@ -569,7 +674,7 @@ class SermondistributorModelExternal_sources extends ListModel if ($db->getNumRows()) { // Get Yesterdays date. - $date = JFactory::getDate()->modify($time)->toSql(); + $date = Factory::getDate()->modify($time)->toSql(); // Reset query. $query = $db->getQuery(true); @@ -590,7 +695,7 @@ class SermondistributorModelExternal_sources extends ListModel $db->setQuery($query); - $db->execute(); + return $db->execute(); } } diff --git a/admin/models/help_document.php b/admin/src/Model/Help_documentModel.php similarity index 78% rename from admin/models/help_document.php rename to admin/src/Model/Help_documentModel.php index 39fa2d8a..99a12fa7 100644 --- a/admin/models/help_document.php +++ b/admin/src/Model/Help_documentModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage help_document.php + @subpackage Help_documentModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,24 +21,47 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Form\Form; +use Joomla\CMS\Filter\InputFilter; +use Joomla\CMS\Filter\OutputFilter; use Joomla\CMS\MVC\Model\AdminModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Table\Table; +use Joomla\CMS\UCM\UCMType; +use Joomla\CMS\Versioning\VersionableModelTrait; +use Joomla\CMS\User\User; use Joomla\Registry\Registry; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\StringHelper as UtilitiesStringHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermondistributor Help_document Admin Model + * + * @since 1.6 */ -class SermondistributorModelHelp_document extends AdminModel +class Help_documentModel extends AdminModel { + use VersionableModelTrait; + /** * The tab layout fields array. * - * @var array + * @var array + * @since 3.0.0 */ protected $tabLayoutFields = array( 'details' => array( @@ -68,7 +91,29 @@ class SermondistributorModelHelp_document extends AdminModel ); /** - * @var string The prefix to use with controller messages. + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/help_document.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js', + 'media/com_sermondistributor/js/help_document.js' + ]; + + /** + * @var string The prefix to use with controller messages. * @since 1.6 */ protected $text_prefix = 'COM_SERMONDISTRIBUTOR'; @@ -88,25 +133,22 @@ class SermondistributorModelHelp_document extends AdminModel * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * - * @return JTable A database object - * - * @since 1.6 + * @return Table A database object + * @since 3.0 + * @throws \Exception */ - public function getTable($type = 'help_document', $prefix = 'SermondistributorTable', $config = array()) + public function getTable($type = 'help_document', $prefix = 'Administrator', $config = []) { - // add table path for when model gets used from other component - $this->addTablePath(JPATH_ADMINISTRATOR . '/components/com_sermondistributor/tables'); // get instance of the table - return JTable::getInstance($type, $prefix, $config); + return parent::getTable($type, $prefix, $config); } - + /** * 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) @@ -146,11 +188,10 @@ class SermondistributorModelHelp_document extends AdminModel * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @param array $options Optional array of options for the form creation. * - * @return mixed A JForm object on success, false on failure - * + * @return Form|boolean A Form object on success, false on failure * @since 1.6 */ - public function getForm($data = array(), $loadData = true, $options = array('control' => 'jform')) + public function getForm($data = [], $loadData = true, $options = ['control' => 'jform']) { // set load data option $options['load_data'] = $loadData; @@ -177,7 +218,7 @@ class SermondistributorModelHelp_document extends AdminModel return false; } - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first. if ($jinput->get('a_id')) @@ -190,7 +231,7 @@ class SermondistributorModelHelp_document extends AdminModel $id = $jinput->get('id', 0, 'INT'); } - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Check for existing item. // Modify the form based on Edit State access controls. @@ -249,38 +290,66 @@ class SermondistributorModelHelp_document extends AdminModel } /** - * Method to get the script that have to be included on the form + * Method to get the styles that have to be included on the view * - * @return string script files + * @return array styles files + * @since 4.3 */ - public function getScript() + public function getStyles(): array { - return 'media/com_sermondistributor/js/help_document.js'; + return $this->styles; } - + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * 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 set in the component. - * * @since 1.6 */ protected function canDelete($record) { - if (!empty($record->id)) + if (empty($record->id) || ($record->published != -2)) { - if ($record->published != -2) - { - return; - } - - $user = JFactory::getUser(); - // The record has been set. Check the record permissions. - return $user->authorise('help_document.delete', 'com_sermondistributor.help_document.' . (int) $record->id); + return false; } - return false; + + // The record has been set. Check the record permissions. + return $this->getCurrentUser()->authorise('help_document.delete', 'com_sermondistributor.help_document.' . (int) $record->id); } /** @@ -289,13 +358,12 @@ class SermondistributorModelHelp_document extends AdminModel * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. - * * @since 1.6 */ protected function canEditState($record) { - $user = JFactory::getUser(); - $recordId = (!empty($record->id)) ? $record->id : 0; + $user = $this->getCurrentUser(); + $recordId = $record->id ?? 0; if ($recordId) { @@ -306,51 +374,50 @@ class SermondistributorModelHelp_document extends AdminModel return false; } } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('help_document.edit.state', 'com_sermondistributor'); } - + /** * Method override to check if you can edit an existing record. * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key. + * @param array $data An array of input data. + * @param string $key The name of the key for the primary key. * - * @return boolean - * @since 2.5 + * @return boolean + * @since 2.5 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // Check specific edit permission then general edit permission. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); return $user->authorise('help_document.edit', 'com_sermondistributor.help_document.'. ((int) isset($data[$key]) ? $data[$key] : 0)) or $user->authorise('help_document.edit', 'com_sermondistributor'); } - + /** * Prepare and sanitise the table data prior to saving. * - * @param JTable $table A JTable object. + * @param Table $table A Table object. * * @return void - * * @since 1.6 */ protected function prepareTable($table) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); - + $date = Factory::getDate(); + $user = $this->getCurrentUser(); + if (isset($table->name)) { - $table->name = htmlspecialchars_decode($table->name, ENT_QUOTES); + $table->name = \htmlspecialchars_decode($table->name, ENT_QUOTES); } - + if (isset($table->alias) && empty($table->alias)) { $table->generateAlias(); } - + if (empty($table->id)) { $table->created = $date->toSql(); @@ -362,7 +429,7 @@ class SermondistributorModelHelp_document extends AdminModel // Set ordering to the last item if not set if (empty($table->ordering)) { - $db = JFactory::getDbo(); + $db = $this->getDatabase(); $query = $db->getQuery(true) ->select('MAX(ordering)') ->from($db->quoteName('#__sermondistributor_help_document')); @@ -377,7 +444,7 @@ class SermondistributorModelHelp_document extends AdminModel $table->modified = $date->toSql(); $table->modified_by = $user->id; } - + if (!empty($table->id)) { // Increment the items version number. @@ -389,21 +456,21 @@ class SermondistributorModelHelp_document extends AdminModel * Method to get the data that should be injected in the form. * * @return mixed The data for the form. - * * @since 1.6 */ - protected function loadFormData() + protected function loadFormData() { // Check the session for previously entered form data. - $data = JFactory::getApplication()->getUserState('com_sermondistributor.edit.help_document.data', array()); + $data = Factory::getApplication()->getUserState('com_sermondistributor.edit.help_document.data', []); if (empty($data)) { $data = $this->getItem(); - // run the perprocess of the data - $this->preprocessData('com_sermondistributor.help_document', $data); } + // run the perprocess of the data + $this->preprocessData('com_sermondistributor.help_document', $data); + return $data; } @@ -423,7 +490,7 @@ class SermondistributorModelHelp_document extends AdminModel public function validate($form, $data, $group = null) { // check if the not_required field is set - if (isset($data['not_required']) && SermondistributorHelper::checkString($data['not_required'])) + if (isset($data['not_required']) && UtilitiesStringHelper::check($data['not_required'])) { $requiredFields = (array) explode(',',(string) $data['not_required']); $requiredFields = array_unique($requiredFields); @@ -431,7 +498,7 @@ class SermondistributorModelHelp_document extends AdminModel foreach ($requiredFields as $requiredField) { // make sure there is a string value - if (SermondistributorHelper::checkString($requiredField)) + if (UtilitiesStringHelper::check($requiredField)) { // change to false $form->setFieldAttribute($requiredField, 'required', 'false'); @@ -454,14 +521,13 @@ class SermondistributorModelHelp_document extends AdminModel { return false; } - + /** * Method to delete one or more records. * * @param array &$pks An array of record primary keys. * - * @return boolean True if successful, false if an error occurs. - * + * @return boolean True if successful, false if an error occurs * @since 12.2 */ public function delete(&$pks) @@ -470,7 +536,7 @@ class SermondistributorModelHelp_document extends AdminModel { return false; } - + return true; } @@ -481,7 +547,6 @@ class SermondistributorModelHelp_document extends AdminModel * @param integer $value The value of the published state. * * @return boolean True on success. - * * @since 12.2 */ public function publish(&$pks, $value = 1) @@ -490,10 +555,10 @@ class SermondistributorModelHelp_document extends AdminModel { return false; } - + return true; - } - + } + /** * Method to perform batch operations on an item or a set of items. * @@ -502,7 +567,6 @@ class SermondistributorModelHelp_document extends AdminModel * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. - * * @since 12.2 */ public function batch($commands, $pks, $contexts) @@ -519,30 +583,30 @@ class SermondistributorModelHelp_document extends AdminModel if (empty($pks)) { - $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); + $this->setError(Text::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; // Set some needed variables. - $this->user = JFactory::getUser(); - $this->table = $this->getTable(); - $this->tableClassName = get_class($this->table); - $this->contentType = new JUcmType; - $this->type = $this->contentType->getTypeByTable($this->tableClassName); - $this->canDo = SermondistributorHelper::getActions('help_document'); - $this->batchSet = true; + $this->user ??= $this->getCurrentUser(); + $this->table = $this->getTable(); + $this->tableClassName = get_class($this->table); + $this->contentType = new UCMType; + $this->type = $this->contentType->getTypeByTable($this->tableClassName); + $this->canDo = SermondistributorHelper::getActions('help_document'); + $this->batchSet = true; if (!$this->canDo->get('core.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } - + if ($this->type == false) { - $type = new JUcmType; + $type = new UCMType; $this->type = $type->getTypeByAlias($this->typeAlias); } @@ -579,8 +643,7 @@ class SermondistributorModelHelp_document extends AdminModel if (!$done) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); - + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } @@ -606,7 +669,7 @@ class SermondistributorModelHelp_document extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('help_document'); @@ -632,7 +695,7 @@ class SermondistributorModelHelp_document extends AdminModel $values['published'] = 0; } - $newIds = array(); + $newIds = []; // Parent exists so let's proceed while (!empty($pks)) { @@ -645,7 +708,7 @@ class SermondistributorModelHelp_document extends AdminModel if (!$this->user->authorise('help_document.edit', $contexts[$pk])) { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } @@ -661,14 +724,14 @@ class SermondistributorModelHelp_document extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } list($this->table->title, $this->table->alias) = $this->_generateNewTitle($this->table->alias, $this->table->title); // insert all set values - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -680,7 +743,7 @@ class SermondistributorModelHelp_document extends AdminModel } // update all unique fields - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -744,7 +807,7 @@ class SermondistributorModelHelp_document extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('help_document'); @@ -752,7 +815,7 @@ class SermondistributorModelHelp_document extends AdminModel if (!$this->canDo->get('help_document.edit') && !$this->canDo->get('help_document.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -769,7 +832,7 @@ class SermondistributorModelHelp_document extends AdminModel { if (!$this->user->authorise('help_document.edit', $contexts[$pk])) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -785,13 +848,13 @@ class SermondistributorModelHelp_document extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // insert all set values. - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -835,27 +898,26 @@ class SermondistributorModelHelp_document extends AdminModel return true; } - + /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. - * * @since 1.6 */ public function save($data) { - $input = JFactory::getApplication()->input; - $filter = JFilterInput::getInstance(); - + $input = Factory::getApplication()->getInput(); + $filter = InputFilter::getInstance(); + // set the metadata to the Item Data if (isset($data['metadata']) && isset($data['metadata']['author'])) { $data['metadata']['author'] = $filter->clean($data['metadata']['author'], 'TRIM'); - - $metadata = new JRegistry; + + $metadata = new Registry; $metadata->loadArray($data['metadata']); $data['metadata'] = (string) $metadata; } @@ -865,11 +927,11 @@ class SermondistributorModelHelp_document extends AdminModel { $data['groups'] = (string) json_encode($data['groups']); } - + // Set the Params Items to data if (isset($data['params']) && is_array($data['params'])) { - $params = new JRegistry; + $params = new Registry; $params->loadArray($data['params']); $data['params'] = (string) $params; } @@ -902,27 +964,27 @@ class SermondistributorModelHelp_document extends AdminModel { if ($data['alias'] == null || empty($data['alias'])) { - if (JFactory::getConfig()->get('unicodeslugs') == 1) + if (Factory::getConfig()->get('unicodeslugs') == 1) { - $data['alias'] = JFilterOutput::stringURLUnicodeSlug($data['title']); + $data['alias'] = OutputFilter::stringURLUnicodeSlug($data['title']); } else { - $data['alias'] = JFilterOutput::stringURLSafe($data['title']); + $data['alias'] = OutputFilter::stringURLSafe($data['title']); } - $table = JTable::getInstance('help_document', 'sermondistributorTable'); + $table = clone $this->getTable(); if ($table->load(array('alias' => $data['alias'])) && ($table->id != $data['id'] || $data['id'] == 0)) { - $msg = JText::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_SAVE_WARNING'); + $msg = Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_SAVE_WARNING'); } $data['alias'] = $this->_generateNewTitle($data['alias']); if (isset($msg)) { - JFactory::getApplication()->enqueueMessage($msg, 'warning'); + Factory::getApplication()->enqueueMessage($msg, 'warning'); } } } @@ -932,7 +994,7 @@ class SermondistributorModelHelp_document extends AdminModel { // Automatic handling of other unique fields $uniqueFields = $this->getUniqueFields(); - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -940,14 +1002,14 @@ class SermondistributorModelHelp_document extends AdminModel } } } - + if (parent::save($data)) { return true; } return false; } - + /** * Method to generate a unique value. * @@ -955,16 +1017,14 @@ class SermondistributorModelHelp_document extends AdminModel * @param string $value data. * * @return string New value. - * * @since 3.0 */ - protected function generateUnique($field,$value) + protected function generateUnique($field, $value) { - // set field value unique $table = $this->getTable(); - while ($table->load(array($field => $value))) + while ($table->load([$field => $value])) { $value = StringHelper::increment($value); } @@ -987,10 +1047,10 @@ class SermondistributorModelHelp_document extends AdminModel // Alter the title/s & alias $table = $this->getTable(); - while ($table->load(array('alias' => $alias))) + while ($table->load(['alias' => $alias])) { // Check if this is an array of titles - if (SermondistributorHelper::checkArray($title)) + if (UtilitiesArrayHelper::check($title)) { foreach($title as $nr => &$_title) { @@ -1005,7 +1065,7 @@ class SermondistributorModelHelp_document extends AdminModel $alias = StringHelper::increment($alias, 'dash'); } // Check if this is an array of titles - if (SermondistributorHelper::checkArray($title)) + if (UtilitiesArrayHelper::check($title)) { $title[] = $alias; return $title; diff --git a/admin/models/help_documents.php b/admin/src/Model/Help_documentsModel.php similarity index 76% rename from admin/models/help_documents.php rename to admin/src/Model/Help_documentsModel.php index f0e6dfa3..52281852 100644 --- a/admin/models/help_documents.php +++ b/admin/src/Model/Help_documentsModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage help_documents.php + @subpackage Help_documentsModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,22 +21,78 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\JsonHelper; +use VDM\Joomla\Utilities\StringHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Help_documents List Model + * + * @since 1.6 */ -class SermondistributorModelHelp_documents extends ListModel +class Help_documentsModel extends ListModel { - public function __construct($config = array()) + /** + * The application object. + * + * @var CMSApplicationInterface The application instance. + * @since 3.2.0 + */ + protected CMSApplicationInterface $app; + + /** + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/help_documents.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js' + ]; + + /** + * Constructor + * + * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). + * @param ?MVCFactoryInterface $factory The factory. + * + * @since 1.6 + * @throws \Exception + */ + public function __construct($config = [], MVCFactoryInterface $factory = null) { if (empty($config['filter_fields'])) - { + { $config['filter_fields'] = array( 'a.id','id', 'a.published','published', @@ -52,7 +108,9 @@ class SermondistributorModelHelp_documents extends ListModel ); } - parent::__construct($config); + parent::__construct($config, $factory); + + $this->app ??= Factory::getApplication(); } /** @@ -64,11 +122,11 @@ class SermondistributorModelHelp_documents extends ListModel * @param string $direction An optional direction (asc|desc). * * @return void - * + * @since 1.7.0 */ protected function populateState($ordering = null, $direction = null) { - $app = JFactory::getApplication(); + $app = $this->app; // Adjust the context to support modal layouts. if ($layout = $app->input->get('layout')) @@ -139,11 +197,12 @@ class SermondistributorModelHelp_documents extends ListModel // List state information. parent::populateState($ordering, $direction); } - + /** * Method to get an array of data items. * * @return mixed An array of data items on success, false on failure. + * @since 1.6 */ public function getItems() { @@ -154,12 +213,12 @@ class SermondistributorModelHelp_documents extends ListModel $items = parent::getItems(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -171,22 +230,13 @@ class SermondistributorModelHelp_documents extends ListModel continue; } - // decode groups - $groupsArray = json_decode($item->groups, true); - if (SermondistributorHelper::checkArray($groupsArray)) - { - $groupsNames = array(); - foreach ($groupsArray as $groups) - { - $groupsNames[] = SermondistributorHelper::getGroupName($groups); - } - $item->groups = implode(', ', $groupsNames); - } + // convert groups + $item->groups = JsonHelper::string($item->groups, ', ', 'groups'); } } // set selection value to a translatable value - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -197,7 +247,7 @@ class SermondistributorModelHelp_documents extends ListModel } } - + // return items return $items; } @@ -205,7 +255,7 @@ class SermondistributorModelHelp_documents extends ListModel /** * Method to convert selection values to translatable string. * - * @return translatable string + * @return string The translatable string. */ public function selectionTranslation($value,$name) { @@ -219,7 +269,7 @@ class SermondistributorModelHelp_documents extends ListModel 3 => 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_URL' ); // Now check if value is found in this array - if (isset($typeArray[$value]) && SermondistributorHelper::checkString($typeArray[$value])) + if (isset($typeArray[$value]) && StringHelper::check($typeArray[$value])) { return $typeArray[$value]; } @@ -232,25 +282,26 @@ class SermondistributorModelHelp_documents extends ListModel 2 => 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_SITE' ); // Now check if value is found in this array - if (isset($locationArray[$value]) && SermondistributorHelper::checkString($locationArray[$value])) + if (isset($locationArray[$value]) && StringHelper::check($locationArray[$value])) { return $locationArray[$value]; } } return $value; } - + /** * Method to build an SQL query to load the list data. * - * @return string An SQL query + * @return string An SQL query + * @since 1.6 */ protected function getListQuery() { // Get the user object. - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -279,7 +330,7 @@ class SermondistributorModelHelp_documents extends ListModel { $query->where('a.access = ' . (int) $_access); } - elseif (SermondistributorHelper::checkArray($_access)) + elseif (UtilitiesArrayHelper::check($_access)) { // Secure the array for the query $_access = ArrayHelper::toInteger($_access); @@ -303,7 +354,7 @@ class SermondistributorModelHelp_documents extends ListModel else { $search = $db->quote('%' . $db->escape($search) . '%'); - $query->where('(a.title LIKE '.$search.' OR a.type LIKE '.$search.' OR a.location LIKE '.$search.' OR a.admin_view LIKE '.$search.' OR g. LIKE '.$search.' OR a.site_view LIKE '.$search.' OR h. LIKE '.$search.')'); + $query->where('(a.title LIKE '.$search.' OR a.type LIKE '.$search.' OR a.location LIKE '.$search.' OR a.admin_view LIKE '.$search.' OR h. LIKE '.$search.' OR a.site_view LIKE '.$search.' OR i. LIKE '.$search.')'); } } @@ -320,7 +371,7 @@ class SermondistributorModelHelp_documents extends ListModel $query->where('a.type = ' . (int) $_type); } } - elseif (SermondistributorHelper::checkString($_type)) + elseif (StringHelper::check($_type)) { $query->where('a.type = ' . $db->quote($db->escape($_type))); } @@ -337,7 +388,7 @@ class SermondistributorModelHelp_documents extends ListModel $query->where('a.location = ' . (int) $_location); } } - elseif (SermondistributorHelper::checkString($_location)) + elseif (StringHelper::check($_location)) { $query->where('a.location = ' . $db->quote($db->escape($_location))); } @@ -354,7 +405,7 @@ class SermondistributorModelHelp_documents extends ListModel $query->where('a.admin_view = ' . (int) $_admin_view); } } - elseif (SermondistributorHelper::checkString($_admin_view)) + elseif (StringHelper::check($_admin_view)) { $query->where('a.admin_view = ' . $db->quote($db->escape($_admin_view))); } @@ -371,16 +422,18 @@ class SermondistributorModelHelp_documents extends ListModel $query->where('a.site_view = ' . (int) $_site_view); } } - elseif (SermondistributorHelper::checkString($_site_view)) + elseif (StringHelper::check($_site_view)) { $query->where('a.site_view = ' . $db->quote($db->escape($_site_view))); } // Add the list ordering clause. - $orderCol = $this->state->get('list.ordering', 'a.id'); - $orderDirn = $this->state->get('list.direction', 'desc'); + $orderCol = $this->getState('list.ordering', 'a.id'); + $orderDirn = $this->getState('list.direction', 'desc'); if ($orderCol != '') { + // Check that the order direction is valid encase we have a field called direction as part of filers. + $orderDirn = (is_string($orderDirn) && in_array(strtolower($orderDirn), ['asc', 'desc'])) ? $orderDirn : 'desc'; $query->order($db->escape($orderCol . ' ' . $orderDirn)); } @@ -398,17 +451,17 @@ class SermondistributorModelHelp_documents extends ListModel public function getExportData($pks, $user = null) { // setup the query - if (($pks_size = SermondistributorHelper::checkArray($pks)) !== false || 'bulk' === $pks) + if (($pks_size = UtilitiesArrayHelper::check($pks)) !== false || 'bulk' === $pks) { // Set a value to know this is export method. (USE IN CUSTOM CODE TO ALTER OUTCOME) $_export = true; // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -452,7 +505,7 @@ class SermondistributorModelHelp_documents extends ListModel $items = $db->loadObjectList(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -472,7 +525,7 @@ class SermondistributorModelHelp_documents extends ListModel } // Add headers to items array. $headers = $this->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { array_unshift($items,$headers); } @@ -490,16 +543,16 @@ class SermondistributorModelHelp_documents extends ListModel public function getExImPortHeaders() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getDbo(); // get the columns $columns = $db->getTableColumns("#__sermondistributor_help_document"); - if (SermondistributorHelper::checkArray($columns)) + if (UtilitiesArrayHelper::check($columns)) { // remove the headers you don't import/export. unset($columns['asset_id']); unset($columns['checked_out']); unset($columns['checked_out_time']); - $headers = new stdClass(); + $headers = new \stdClass(); foreach ($columns as $column => $type) { $headers->{$column} = $column; @@ -508,12 +561,12 @@ class SermondistributorModelHelp_documents extends ListModel } return false; } - + /** * Method to get a store id based on model configuration state. * * @return string A store id. - * + * @since 1.6 */ protected function getStoreId($id = '') { @@ -523,13 +576,13 @@ class SermondistributorModelHelp_documents extends ListModel $id .= ':' . $this->getState('filter.published'); // Check if the value is an array $_access = $this->getState('filter.access'); - if (SermondistributorHelper::checkArray($_access)) + if (UtilitiesArrayHelper::check($_access)) { $id .= ':' . implode(':', $_access); } // Check if this is only an number or string elseif (is_numeric($_access) - || SermondistributorHelper::checkString($_access)) + || StringHelper::check($_access)) { $id .= ':' . $_access; } @@ -545,22 +598,65 @@ class SermondistributorModelHelp_documents extends ListModel return parent::getStoreId($id); } + /** + * Method to get the styles that have to be included on the view + * + * @return array styles files + * @since 4.3 + */ + public function getStyles(): array + { + return $this->styles; + } + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * Build an SQL query to checkin all items left checked out longer then a set time. * - * @return a bool - * + * @return bool + * @since 3.2.0 */ - protected function checkInNow() + protected function checkInNow(): bool { // Get set check in time - $time = JComponentHelper::getParams('com_sermondistributor')->get('check_in'); + $time = ComponentHelper::getParams('com_sermondistributor')->get('check_in'); if ($time) { - // Get a db connection. - $db = JFactory::getDbo(); + $db = $this->getDatabase(); // Reset query. $query = $db->getQuery(true); $query->select('*'); @@ -572,7 +668,7 @@ class SermondistributorModelHelp_documents extends ListModel if ($db->getNumRows()) { // Get Yesterdays date. - $date = JFactory::getDate()->modify($time)->toSql(); + $date = Factory::getDate()->modify($time)->toSql(); // Reset query. $query = $db->getQuery(true); @@ -593,7 +689,7 @@ class SermondistributorModelHelp_documents extends ListModel $db->setQuery($query); - $db->execute(); + return $db->execute(); } } diff --git a/admin/models/import.php b/admin/src/Model/ImportModel.php similarity index 82% rename from admin/models/import.php rename to admin/src/Model/ImportModel.php index 8171a98c..2db5852b 100644 --- a/admin/models/import.php +++ b/admin/src/Model/ImportModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage import.php + @subpackage ImportModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,26 +21,37 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; use Joomla\CMS\Filesystem\File; use Joomla\CMS\Filesystem\Folder; +use Joomla\CMS\Filesystem\Path; +use Joomla\CMS\Filter\OutputFilter; +use Joomla\CMS\Installer\InstallerHelper; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; use PhpOffice\PhpSpreadsheet\IOFactory; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /*** * Sermondistributor Import Base Database Model + * + * @since 1.6 */ -class SermondistributorModelImport extends BaseDatabaseModel +class ImportModel extends BaseDatabaseModel { // set uploading values protected $use_streams = false; protected $allow_unsafe = false; - protected $safeFileOptions = array(); - + protected $safeFileOptions = []; + /** * @var object JTable object */ @@ -57,13 +68,13 @@ class SermondistributorModelImport extends BaseDatabaseModel * @var string */ protected $_context = 'com_sermondistributor.import'; - + /** * Import Settings */ - protected $getType = NULL; - protected $dataType = NULL; - + protected $getType = NULL; + protected $dataType = NULL; + /** * Method to auto-populate the model state. * @@ -74,7 +85,7 @@ class SermondistributorModelImport extends BaseDatabaseModel */ protected function populateState() { - $app = JFactory::getApplication('administrator'); + $app = Factory::getApplication('administrator'); $this->setState('message', $app->getUserState('com_sermondistributor.message')); $app->setUserState('com_sermondistributor.message', ''); @@ -94,14 +105,14 @@ class SermondistributorModelImport extends BaseDatabaseModel public function import() { $this->setState('action', 'import'); - $app = JFactory::getApplication(); - $session = JFactory::getSession(); + $app = Factory::getApplication(); + $session = Factory::getSession(); $package = null; $continue = false; // get import type $this->getType = $app->input->getString('gettype', NULL); // get import type - $this->dataType = $session->get('dataType_VDM_IMPORTINTO', NULL); + $this->dataType = $session->get('dataType_VDM_IMPORTINTO', NULL); if ($package === null) { @@ -122,9 +133,9 @@ class SermondistributorModelImport extends BaseDatabaseModel break; case 'continue': - $continue = true; - $package = $session->get('package', null); - $package = json_decode($package, true); + $continue = true; + $package = $session->get('package', null); + $package = json_decode($package, true); // clear session $session->clear('package'); $session->clear('dataType'); @@ -132,7 +143,7 @@ class SermondistributorModelImport extends BaseDatabaseModel break; default: - $app->setUserState('com_sermondistributor.message', JText::_('COM_SERMONDISTRIBUTOR_IMPORT_NO_IMPORT_TYPE_FOUND')); + $app->setUserState('com_sermondistributor.message', Text::_('COM_SERMONDISTRIBUTOR_IMPORT_NO_IMPORT_TYPE_FOUND')); return false; break; @@ -146,10 +157,10 @@ class SermondistributorModelImport extends BaseDatabaseModel $this->remove($package['packagename']); } - $app->setUserState('com_sermondistributor.message', JText::_('COM_SERMONDISTRIBUTOR_IMPORT_UNABLE_TO_FIND_IMPORT_PACKAGE')); + $app->setUserState('com_sermondistributor.message', Text::_('COM_SERMONDISTRIBUTOR_IMPORT_UNABLE_TO_FIND_IMPORT_PACKAGE')); return false; } - + // first link data to table headers if(!$continue){ $package = json_encode($package); @@ -158,13 +169,13 @@ class SermondistributorModelImport extends BaseDatabaseModel $session->set('hasPackage', true); return true; } - + // set the data $headerList = json_decode($session->get($this->dataType.'_VDM_IMPORTHEADERS', false), true); if (!$this->setData($package,$this->dataType,$headerList)) { // There was an error importing the package - $msg = JText::_('COM_SERMONDISTRIBUTOR_IMPORT_ERROR'); + $msg = Text::_('COM_SERMONDISTRIBUTOR_IMPORT_ERROR'); $back = $session->get('backto_VDM_IMPORT', NULL); if ($back) { @@ -176,12 +187,12 @@ class SermondistributorModelImport extends BaseDatabaseModel else { // Package imported sucessfully - $msg = JText::sprintf('COM_SERMONDISTRIBUTOR_IMPORT_SUCCESS', $package['packagename']); + $msg = Text::sprintf('COM_SERMONDISTRIBUTOR_IMPORT_SUCCESS', $package['packagename']); $back = $session->get('backto_VDM_IMPORT', NULL); if ($back) { - $app->setUserState('com_sermondistributor.redirect_url', 'index.php?option=com_sermondistributor&view='.$back); - $session->clear('backto_VDM_IMPORT'); + $app->setUserState('com_sermondistributor.redirect_url', 'index.php?option=com_sermondistributor&view='.$back); + $session->clear('backto_VDM_IMPORT'); } $result = true; } @@ -192,7 +203,7 @@ class SermondistributorModelImport extends BaseDatabaseModel // remove file after import $this->remove($package['packagename']); $session->clear($this->getType.'_VDM_IMPORTHEADERS'); - + return $result; } @@ -202,48 +213,47 @@ class SermondistributorModelImport extends BaseDatabaseModel * @return spreadsheet definition or false on failure */ protected function _getPackageFromUpload() - { + { // Get the uploaded file information - $app = JFactory::getApplication(); + $app = Factory::getApplication(); $input = $app->input; // Do not change the filter type 'raw'. We need this to let files containing PHP code to upload. See JInputFiles::get. $userfile = $input->files->get('import_package', null, 'raw'); - + // Make sure that file uploads are enabled in php if (!(bool) ini_get('file_uploads')) { - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_WARNIMPORTFILE'), 'warning'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_WARNIMPORTFILE'), 'warning'); return false; } // If there is no uploaded file, we have a problem... if (!is_array($userfile)) { - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_NO_FILE_SELECTED'), 'warning'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_NO_FILE_SELECTED'), 'warning'); return false; } // Check if there was a problem uploading the file. if ($userfile['error'] || $userfile['size'] < 1) { - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_WARNIMPORTUPLOADERROR'), 'warning'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_WARNIMPORTUPLOADERROR'), 'warning'); return false; } // Build the appropriate paths - $config = JFactory::getConfig(); + $config = Factory::getConfig(); $tmp_dest = $config->get('tmp_path') . '/' . $userfile['name']; $tmp_src = $userfile['tmp_name']; // Move uploaded file - jimport('joomla.filesystem.file'); $p_file = File::upload($tmp_src, $tmp_dest, $this->use_streams, $this->allow_unsafe, $this->safeFileOptions); // Was the package downloaded? if (!$p_file) { - $session = JFactory::getSession(); + $session = Factory::getSession(); $session->clear('package'); $session->clear('dataType'); $session->clear('hasPackage'); @@ -265,16 +275,16 @@ class SermondistributorModelImport extends BaseDatabaseModel */ protected function _getPackageFromFolder() { - $app = JFactory::getApplication(); + $app = Factory::getApplication(); $input = $app->input; // Get the path to the package to import $p_dir = $input->getString('import_directory'); - $p_dir = JPath::clean($p_dir); + $p_dir = Path::clean($p_dir); // Did you give us a valid path? if (!file_exists($p_dir)) { - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_PLEASE_ENTER_A_PACKAGE_DIRECTORY'), 'warning'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_PLEASE_ENTER_A_PACKAGE_DIRECTORY'), 'warning'); return false; } @@ -284,17 +294,17 @@ class SermondistributorModelImport extends BaseDatabaseModel // Did you give us a valid package? if (!$type) { - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_PATH_DOES_NOT_HAVE_A_VALID_PACKAGE'), 'warning'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_PATH_DOES_NOT_HAVE_A_VALID_PACKAGE'), 'warning'); } - + // check the extention if(!$this->checkExtension($p_dir)) { // set error message - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_DOES_NOT_HAVE_A_VALID_FILE_TYPE'), 'warning'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_DOES_NOT_HAVE_A_VALID_FILE_TYPE'), 'warning'); return false; } - + $package['packagename'] = null; $package['dir'] = $p_dir; $package['type'] = $type; @@ -310,26 +320,26 @@ class SermondistributorModelImport extends BaseDatabaseModel */ protected function _getPackageFromUrl() { - $app = JFactory::getApplication(); + $app = Factory::getApplication(); $input = $app->input; - + // Get the URL of the package to import $url = $input->getString('import_url'); // Did you give us a URL? if (!$url) { - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_ENTER_A_URL'), 'warning'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_ENTER_A_URL'), 'warning'); return false; } // Download the package at the URL given - $p_file = JInstallerHelper::downloadPackage($url); + $p_file = InstallerHelper::downloadPackage($url); // Was the package downloaded? if (!$p_file) { - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_INVALID_URL'), 'warning'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_INVALID_URL'), 'warning'); return false; } @@ -338,7 +348,7 @@ class SermondistributorModelImport extends BaseDatabaseModel return $package; } - + /** * Check a file and verifies it as a spreadsheet file * Supports .csv .xlsx .xls and .ods @@ -350,29 +360,29 @@ class SermondistributorModelImport extends BaseDatabaseModel */ protected function check($archivename) { - $app = JFactory::getApplication(); + $app = Factory::getApplication(); // Clean the name - $archivename = JPath::clean($archivename); - + $archivename = Path::clean($archivename); + // check the extention if(!$this->checkExtension($archivename)) { // Cleanup the import files $this->remove($archivename); - $app->enqueueMessage(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_DOES_NOT_HAVE_A_VALID_FILE_TYPE'), 'warning'); + $app->enqueueMessage(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_MSG_DOES_NOT_HAVE_A_VALID_FILE_TYPE'), 'warning'); return false; } - - $config = JFactory::getConfig(); + + $config = Factory::getConfig(); // set Package Name $check['packagename'] = $archivename; - + // set directory $check['dir'] = $config->get('tmp_path'). '/' .$archivename; - + // set type $check['type'] = $this->getType; - + return $check; } @@ -409,8 +419,8 @@ class SermondistributorModelImport extends BaseDatabaseModel protected function remove($package) { jimport('joomla.filesystem.file'); - - $config = JFactory::getConfig(); + + $config = Factory::getConfig(); $package = $config->get('tmp_path'). '/' .$package; // Is the package file a valid file? @@ -418,10 +428,10 @@ class SermondistributorModelImport extends BaseDatabaseModel { File::delete($package); } - elseif (is_file(JPath::clean($package))) + elseif (is_file(Path::clean($package))) { // It might also be just a base filename - File::delete(JPath::clean($package)); + File::delete(Path::clean($package)); } } @@ -435,11 +445,11 @@ class SermondistributorModelImport extends BaseDatabaseModel **/ protected function setData($package,$table,$target_headers) { - if (SermondistributorHelper::checkArray($target_headers)) + if (UtilitiesArrayHelper::check($target_headers)) { // make sure the file is loaded SermondistributorHelper::composerAutoload('phpspreadsheet'); - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; foreach($target_headers as $header) { if (($column = $jinput->getString($header, false)) !== false || @@ -479,10 +489,10 @@ class SermondistributorModelImport extends BaseDatabaseModel protected function save($data,$table) { // import the data if there is any - if(SermondistributorHelper::checkArray($data['array'])) + if(UtilitiesArrayHelper::check($data['array'])) { // get user object - $user = JFactory::getUser(); + $user = Factory::getUser(); // remove header if it has headers $id_key = $data['target_headers']['id']; $published_key = $data['target_headers']['published']; @@ -497,14 +507,14 @@ class SermondistributorModelImport extends BaseDatabaseModel } // make sure there is still values in array and that it was not only headers - if(SermondistributorHelper::checkArray($data['array']) && $user->authorise($table.'.import', 'com_sermondistributor') && $user->authorise('core.import', 'com_sermondistributor')) + if(UtilitiesArrayHelper::check($data['array']) && $user->authorise($table.'.import', 'com_sermondistributor') && $user->authorise('core.import', 'com_sermondistributor')) { // set target. $target = array_flip($data['target_headers']); // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getDbo(); // set some defaults - $todayDate = JFactory::getDate()->toSql(); + $todayDate = Factory::getDate()->toSql(); // get global action permissions $canDo = SermondistributorHelper::getActions($table); $canEdit = $canDo->get('core.edit'); @@ -691,13 +701,13 @@ class SermondistributorModelImport extends BaseDatabaseModel protected function getAlias($name,$type = false) { // sanitize the name to an alias - if (JFactory::getConfig()->get('unicodeslugs') == 1) + if (Factory::getConfig()->get('unicodeslugs') == 1) { - $alias = JFilterOutput::stringURLUnicodeSlug($name); + $alias = OutputFilter::stringURLUnicodeSlug($name); } else { - $alias = JFilterOutput::stringURLSafe($name); + $alias = OutputFilter::stringURLSafe($name); } // must be a uniqe alias if ($type) @@ -706,7 +716,7 @@ class SermondistributorModelImport extends BaseDatabaseModel } return $alias; } - + /** * Method to generate a uniqe value. * @@ -721,16 +731,16 @@ class SermondistributorModelImport extends BaseDatabaseModel // insure the filed is always uniqe while (isset($this->uniqeValueArray[$type][$field][$value])) { - $value = JString::increment($value, 'dash'); + $value = StringHelper::increment($value, 'dash'); } $this->uniqeValueArray[$type][$field][$value] = $value; return $value; } - + protected function getAliasesUsed($table) { // Get a db connection. - $db = JFactory::getDbo(); + $db = $this->getDatabase(); // first we check if there is a alias column $columns = $db->getTableColumns('#__sermondistributor_'.$table); if(isset($columns['alias'])){ diff --git a/admin/models/local_listing.php b/admin/src/Model/Local_listingModel.php similarity index 81% rename from admin/models/local_listing.php rename to admin/src/Model/Local_listingModel.php index ead9f874..83be4850 100644 --- a/admin/models/local_listing.php +++ b/admin/src/Model/Local_listingModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage local_listing.php + @subpackage Local_listingModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,24 +21,48 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Form\Form; +use Joomla\CMS\Filter\InputFilter; +use Joomla\CMS\Filter\OutputFilter; use Joomla\CMS\MVC\Model\AdminModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Table\Table; +use Joomla\CMS\UCM\UCMType; +use Joomla\CMS\Versioning\VersionableModelTrait; +use Joomla\CMS\User\User; use Joomla\Registry\Registry; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\FOF\Encrypt\AES; +use VDM\Joomla\Utilities\StringHelper as UtilitiesStringHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermondistributor Local_listing Admin Model + * + * @since 1.6 */ -class SermondistributorModelLocal_listing extends AdminModel +class Local_listingModel extends AdminModel { + use VersionableModelTrait; + /** * The tab layout fields array. * - * @var array + * @var array + * @since 3.0.0 */ protected $tabLayoutFields = array( 'details' => array( @@ -60,7 +84,29 @@ class SermondistributorModelLocal_listing extends AdminModel ); /** - * @var string The prefix to use with controller messages. + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/local_listing.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js', + 'media/com_sermondistributor/js/local_listing.js' + ]; + + /** + * @var string The prefix to use with controller messages. * @since 1.6 */ protected $text_prefix = 'COM_SERMONDISTRIBUTOR'; @@ -80,16 +126,14 @@ class SermondistributorModelLocal_listing extends AdminModel * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * - * @return JTable A database object - * - * @since 1.6 + * @return Table A database object + * @since 3.0 + * @throws \Exception */ - public function getTable($type = 'local_listing', $prefix = 'SermondistributorTable', $config = array()) + public function getTable($type = 'local_listing', $prefix = 'Administrator', $config = []) { - // add table path for when model gets used from other component - $this->addTablePath(JPATH_ADMINISTRATOR . '/components/com_sermondistributor/tables'); // get instance of the table - return JTable::getInstance($type, $prefix, $config); + return parent::getTable($type, $prefix, $config); } /** @@ -103,7 +147,7 @@ class SermondistributorModelLocal_listing extends AdminModel public function searchForId($value, $key = 'key') { // Create a new query object. - $db = JFactory::getDBO(); + $db = Factory::getDBO(); $query = $db->getQuery(true); // Select some fields @@ -123,14 +167,13 @@ class SermondistributorModelLocal_listing extends AdminModel } return false; } - + /** * 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) @@ -156,7 +199,7 @@ class SermondistributorModelLocal_listing extends AdminModel // Get the basic encryption. $basickey = SermondistributorHelper::getCryptKey('basic'); // Get the encryption object. - $basic = new FOFEncryptAes($basickey); + $basic = new AES($basickey); if (!empty($item->url) && $basickey && !is_numeric($item->url) && $item->url === base64_encode(base64_decode($item->url, true))) { @@ -175,11 +218,10 @@ class SermondistributorModelLocal_listing extends AdminModel * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @param array $options Optional array of options for the form creation. * - * @return mixed A JForm object on success, false on failure - * + * @return Form|boolean A Form object on success, false on failure * @since 1.6 */ - public function getForm($data = array(), $loadData = true, $options = array('control' => 'jform')) + public function getForm($data = [], $loadData = true, $options = ['control' => 'jform']) { // set load data option $options['load_data'] = $loadData; @@ -206,7 +248,7 @@ class SermondistributorModelLocal_listing extends AdminModel return false; } - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first. if ($jinput->get('a_id')) @@ -219,7 +261,7 @@ class SermondistributorModelLocal_listing extends AdminModel $id = $jinput->get('id', 0, 'INT'); } - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Check for existing item. // Modify the form based on Edit State access controls. @@ -382,38 +424,66 @@ class SermondistributorModelLocal_listing extends AdminModel } /** - * Method to get the script that have to be included on the form + * Method to get the styles that have to be included on the view * - * @return string script files + * @return array styles files + * @since 4.3 */ - public function getScript() + public function getStyles(): array { - return 'media/com_sermondistributor/js/local_listing.js'; + return $this->styles; } - + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * 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 set in the component. - * * @since 1.6 */ protected function canDelete($record) { - if (!empty($record->id)) + if (empty($record->id) || ($record->published != -2)) { - if ($record->published != -2) - { - return; - } - - $user = JFactory::getUser(); - // The record has been set. Check the record permissions. - return $user->authorise('local_listing.delete', 'com_sermondistributor.local_listing.' . (int) $record->id); + return false; } - return false; + + // The record has been set. Check the record permissions. + return $this->getCurrentUser()->authorise('local_listing.delete', 'com_sermondistributor.local_listing.' . (int) $record->id); } /** @@ -422,13 +492,12 @@ class SermondistributorModelLocal_listing extends AdminModel * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. - * * @since 1.6 */ protected function canEditState($record) { - $user = JFactory::getUser(); - $recordId = (!empty($record->id)) ? $record->id : 0; + $user = $this->getCurrentUser(); + $recordId = $record->id ?? 0; if ($recordId) { @@ -439,51 +508,50 @@ class SermondistributorModelLocal_listing extends AdminModel return false; } } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('local_listing.edit.state', 'com_sermondistributor'); } - + /** * Method override to check if you can edit an existing record. * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key. + * @param array $data An array of input data. + * @param string $key The name of the key for the primary key. * - * @return boolean - * @since 2.5 + * @return boolean + * @since 2.5 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // Check specific edit permission then general edit permission. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); return $user->authorise('local_listing.edit', 'com_sermondistributor.local_listing.'. ((int) isset($data[$key]) ? $data[$key] : 0)) or $user->authorise('local_listing.edit', 'com_sermondistributor'); } - + /** * Prepare and sanitise the table data prior to saving. * - * @param JTable $table A JTable object. + * @param Table $table A Table object. * * @return void - * * @since 1.6 */ protected function prepareTable($table) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); - + $date = Factory::getDate(); + $user = $this->getCurrentUser(); + if (isset($table->name)) { - $table->name = htmlspecialchars_decode($table->name, ENT_QUOTES); + $table->name = \htmlspecialchars_decode($table->name, ENT_QUOTES); } - + if (isset($table->alias) && empty($table->alias)) { $table->generateAlias(); } - + if (empty($table->id)) { $table->created = $date->toSql(); @@ -495,7 +563,7 @@ class SermondistributorModelLocal_listing extends AdminModel // Set ordering to the last item if not set if (empty($table->ordering)) { - $db = JFactory::getDbo(); + $db = $this->getDatabase(); $query = $db->getQuery(true) ->select('MAX(ordering)') ->from($db->quoteName('#__sermondistributor_local_listing')); @@ -510,7 +578,7 @@ class SermondistributorModelLocal_listing extends AdminModel $table->modified = $date->toSql(); $table->modified_by = $user->id; } - + if (!empty($table->id)) { // Increment the items version number. @@ -522,21 +590,21 @@ class SermondistributorModelLocal_listing extends AdminModel * Method to get the data that should be injected in the form. * * @return mixed The data for the form. - * * @since 1.6 */ - protected function loadFormData() + protected function loadFormData() { // Check the session for previously entered form data. - $data = JFactory::getApplication()->getUserState('com_sermondistributor.edit.local_listing.data', array()); + $data = Factory::getApplication()->getUserState('com_sermondistributor.edit.local_listing.data', []); if (empty($data)) { $data = $this->getItem(); - // run the perprocess of the data - $this->preprocessData('com_sermondistributor.local_listing', $data); } + // run the perprocess of the data + $this->preprocessData('com_sermondistributor.local_listing', $data); + return $data; } @@ -551,14 +619,13 @@ class SermondistributorModelLocal_listing extends AdminModel { return false; } - + /** * Method to delete one or more records. * * @param array &$pks An array of record primary keys. * - * @return boolean True if successful, false if an error occurs. - * + * @return boolean True if successful, false if an error occurs * @since 12.2 */ public function delete(&$pks) @@ -567,7 +634,7 @@ class SermondistributorModelLocal_listing extends AdminModel { return false; } - + return true; } @@ -578,7 +645,6 @@ class SermondistributorModelLocal_listing extends AdminModel * @param integer $value The value of the published state. * * @return boolean True on success. - * * @since 12.2 */ public function publish(&$pks, $value = 1) @@ -587,10 +653,10 @@ class SermondistributorModelLocal_listing extends AdminModel { return false; } - + return true; - } - + } + /** * Method to perform batch operations on an item or a set of items. * @@ -599,7 +665,6 @@ class SermondistributorModelLocal_listing extends AdminModel * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. - * * @since 12.2 */ public function batch($commands, $pks, $contexts) @@ -616,30 +681,30 @@ class SermondistributorModelLocal_listing extends AdminModel if (empty($pks)) { - $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); + $this->setError(Text::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; // Set some needed variables. - $this->user = JFactory::getUser(); - $this->table = $this->getTable(); - $this->tableClassName = get_class($this->table); - $this->contentType = new JUcmType; - $this->type = $this->contentType->getTypeByTable($this->tableClassName); - $this->canDo = SermondistributorHelper::getActions('local_listing'); - $this->batchSet = true; + $this->user ??= $this->getCurrentUser(); + $this->table = $this->getTable(); + $this->tableClassName = get_class($this->table); + $this->contentType = new UCMType; + $this->type = $this->contentType->getTypeByTable($this->tableClassName); + $this->canDo = SermondistributorHelper::getActions('local_listing'); + $this->batchSet = true; if (!$this->canDo->get('core.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } - + if ($this->type == false) { - $type = new JUcmType; + $type = new UCMType; $this->type = $type->getTypeByAlias($this->typeAlias); } @@ -676,8 +741,7 @@ class SermondistributorModelLocal_listing extends AdminModel if (!$done) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); - + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } @@ -703,7 +767,7 @@ class SermondistributorModelLocal_listing extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('local_listing'); @@ -729,7 +793,7 @@ class SermondistributorModelLocal_listing extends AdminModel $values['published'] = 0; } - $newIds = array(); + $newIds = []; // Parent exists so let's proceed while (!empty($pks)) { @@ -742,7 +806,7 @@ class SermondistributorModelLocal_listing extends AdminModel if (!$this->user->authorise('local_listing.edit', $contexts[$pk])) { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } @@ -758,19 +822,19 @@ class SermondistributorModelLocal_listing extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // Only for strings - if (SermondistributorHelper::checkString($this->table->name) && !is_numeric($this->table->name)) + if (UtilitiesStringHelper::check($this->table->name) && !is_numeric($this->table->name)) { $this->table->name = $this->generateUnique('name',$this->table->name); } // insert all set values - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -782,7 +846,7 @@ class SermondistributorModelLocal_listing extends AdminModel } // update all unique fields - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -846,7 +910,7 @@ class SermondistributorModelLocal_listing extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('local_listing'); @@ -854,7 +918,7 @@ class SermondistributorModelLocal_listing extends AdminModel if (!$this->canDo->get('local_listing.edit') && !$this->canDo->get('local_listing.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -871,7 +935,7 @@ class SermondistributorModelLocal_listing extends AdminModel { if (!$this->user->authorise('local_listing.edit', $contexts[$pk])) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -887,13 +951,13 @@ class SermondistributorModelLocal_listing extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // insert all set values. - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -937,27 +1001,26 @@ class SermondistributorModelLocal_listing extends AdminModel return true; } - + /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. - * * @since 1.6 */ public function save($data) { - $input = JFactory::getApplication()->input; - $filter = JFilterInput::getInstance(); - + $input = Factory::getApplication()->getInput(); + $filter = InputFilter::getInstance(); + // set the metadata to the Item Data if (isset($data['metadata']) && isset($data['metadata']['author'])) { $data['metadata']['author'] = $filter->clean($data['metadata']['author'], 'TRIM'); - - $metadata = new JRegistry; + + $metadata = new Registry; $metadata->loadArray($data['metadata']); $data['metadata'] = (string) $metadata; } @@ -965,18 +1028,18 @@ class SermondistributorModelLocal_listing extends AdminModel // Get the basic encryption key. $basickey = SermondistributorHelper::getCryptKey('basic'); // Get the encryption object - $basic = new FOFEncryptAes($basickey); + $basic = new AES($basickey); // Encrypt data url. if (isset($data['url']) && $basickey) { $data['url'] = $basic->encryptString($data['url']); } - + // Set the Params Items to data if (isset($data['params']) && is_array($data['params'])) { - $params = new JRegistry; + $params = new Registry; $params->loadArray($data['params']); $data['params'] = (string) $params; } @@ -986,7 +1049,7 @@ class SermondistributorModelLocal_listing extends AdminModel { // Automatic handling of other unique fields $uniqueFields = $this->getUniqueFields(); - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -994,14 +1057,14 @@ class SermondistributorModelLocal_listing extends AdminModel } } } - + if (parent::save($data)) { return true; } return false; } - + /** * Method to generate a unique value. * @@ -1009,16 +1072,14 @@ class SermondistributorModelLocal_listing extends AdminModel * @param string $value data. * * @return string New value. - * * @since 3.0 */ - protected function generateUnique($field,$value) + protected function generateUnique($field, $value) { - // set field value unique $table = $this->getTable(); - while ($table->load(array($field => $value))) + while ($table->load([$field => $value])) { $value = StringHelper::increment($value); } @@ -1040,7 +1101,7 @@ class SermondistributorModelLocal_listing extends AdminModel // Alter the title $table = $this->getTable(); - while ($table->load(array('title' => $title))) + while ($table->load(['title' => $title])) { $title = StringHelper::increment($title); } diff --git a/admin/models/local_listings.php b/admin/src/Model/Local_listingsModel.php similarity index 76% rename from admin/models/local_listings.php rename to admin/src/Model/Local_listingsModel.php index 0885ef43..6c957533 100644 --- a/admin/models/local_listings.php +++ b/admin/src/Model/Local_listingsModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage local_listings.php + @subpackage Local_listingsModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,22 +21,78 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper; +use VDM\Joomla\FOF\Encrypt\AES; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Local_listings List Model + * + * @since 1.6 */ -class SermondistributorModelLocal_listings extends ListModel +class Local_listingsModel extends ListModel { - public function __construct($config = array()) + /** + * The application object. + * + * @var CMSApplicationInterface The application instance. + * @since 3.2.0 + */ + protected CMSApplicationInterface $app; + + /** + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/local_listings.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js' + ]; + + /** + * Constructor + * + * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). + * @param ?MVCFactoryInterface $factory The factory. + * + * @since 1.6 + * @throws \Exception + */ + public function __construct($config = [], MVCFactoryInterface $factory = null) { if (empty($config['filter_fields'])) - { + { $config['filter_fields'] = array( 'a.id','id', 'a.published','published', @@ -51,7 +107,9 @@ class SermondistributorModelLocal_listings extends ListModel ); } - parent::__construct($config); + parent::__construct($config, $factory); + + $this->app ??= Factory::getApplication(); } /** @@ -63,11 +121,11 @@ class SermondistributorModelLocal_listings extends ListModel * @param string $direction An optional direction (asc|desc). * * @return void - * + * @since 1.7.0 */ protected function populateState($ordering = null, $direction = null) { - $app = JFactory::getApplication(); + $app = $this->app; // Adjust the context to support modal layouts. if ($layout = $app->input->get('layout')) @@ -138,11 +196,12 @@ class SermondistributorModelLocal_listings extends ListModel // List state information. parent::populateState($ordering, $direction); } - + /** * Method to get an array of data items. * * @return mixed An array of data items on success, false on failure. + * @since 1.6 */ public function getItems() { @@ -153,12 +212,12 @@ class SermondistributorModelLocal_listings extends ListModel $items = parent::getItems(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -174,7 +233,7 @@ class SermondistributorModelLocal_listings extends ListModel } // set selection value to a translatable value - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -183,7 +242,7 @@ class SermondistributorModelLocal_listings extends ListModel } } - + // return items return $items; } @@ -191,7 +250,7 @@ class SermondistributorModelLocal_listings extends ListModel /** * Method to convert selection values to translatable string. * - * @return translatable string + * @return string The translatable string. */ public function selectionTranslation($value,$name) { @@ -204,25 +263,26 @@ class SermondistributorModelLocal_listings extends ListModel 2 => 'COM_SERMONDISTRIBUTOR_LOCAL_LISTING_DYNAMIC_AUTOMATIC_BUILD' ); // Now check if value is found in this array - if (isset($buildArray[$value]) && SermondistributorHelper::checkString($buildArray[$value])) + if (isset($buildArray[$value]) && StringHelper::check($buildArray[$value])) { return $buildArray[$value]; } } return $value; } - + /** * Method to build an SQL query to load the list data. * - * @return string An SQL query + * @return string An SQL query + * @since 1.6 */ protected function getListQuery() { // Get the user object. - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -273,7 +333,7 @@ class SermondistributorModelLocal_listings extends ListModel $query->where('a.build = ' . (int) $_build); } } - elseif (SermondistributorHelper::checkString($_build)) + elseif (StringHelper::check($_build)) { $query->where('a.build = ' . $db->quote($db->escape($_build))); } @@ -290,16 +350,18 @@ class SermondistributorModelLocal_listings extends ListModel $query->where('a.external_source = ' . (int) $_external_source); } } - elseif (SermondistributorHelper::checkString($_external_source)) + elseif (StringHelper::check($_external_source)) { $query->where('a.external_source = ' . $db->quote($db->escape($_external_source))); } // Add the list ordering clause. - $orderCol = $this->state->get('list.ordering', 'a.id'); - $orderDirn = $this->state->get('list.direction', 'desc'); + $orderCol = $this->getState('list.ordering', 'a.id'); + $orderDirn = $this->getState('list.direction', 'desc'); if ($orderCol != '') { + // Check that the order direction is valid encase we have a field called direction as part of filers. + $orderDirn = (is_string($orderDirn) && in_array(strtolower($orderDirn), ['asc', 'desc'])) ? $orderDirn : 'desc'; $query->order($db->escape($orderCol . ' ' . $orderDirn)); } @@ -317,17 +379,17 @@ class SermondistributorModelLocal_listings extends ListModel public function getExportData($pks, $user = null) { // setup the query - if (($pks_size = SermondistributorHelper::checkArray($pks)) !== false || 'bulk' === $pks) + if (($pks_size = UtilitiesArrayHelper::check($pks)) !== false || 'bulk' === $pks) { // Set a value to know this is export method. (USE IN CUSTOM CODE TO ALTER OUTCOME) $_export = true; // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -367,10 +429,10 @@ class SermondistributorModelLocal_listings extends ListModel // Get the basic encryption key. $basickey = SermondistributorHelper::getCryptKey('basic'); // Get the encryption object. - $basic = new FOFEncryptAes($basickey); + $basic = new AES($basickey); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -395,7 +457,7 @@ class SermondistributorModelLocal_listings extends ListModel } // Add headers to items array. $headers = $this->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { array_unshift($items,$headers); } @@ -413,16 +475,16 @@ class SermondistributorModelLocal_listings extends ListModel public function getExImPortHeaders() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getDbo(); // get the columns $columns = $db->getTableColumns("#__sermondistributor_local_listing"); - if (SermondistributorHelper::checkArray($columns)) + if (UtilitiesArrayHelper::check($columns)) { // remove the headers you don't import/export. unset($columns['asset_id']); unset($columns['checked_out']); unset($columns['checked_out_time']); - $headers = new stdClass(); + $headers = new \stdClass(); foreach ($columns as $column => $type) { $headers->{$column} = $column; @@ -431,12 +493,12 @@ class SermondistributorModelLocal_listings extends ListModel } return false; } - + /** * Method to get a store id based on model configuration state. * * @return string A store id. - * + * @since 1.6 */ protected function getStoreId($id = '') { @@ -456,22 +518,65 @@ class SermondistributorModelLocal_listings extends ListModel return parent::getStoreId($id); } + /** + * Method to get the styles that have to be included on the view + * + * @return array styles files + * @since 4.3 + */ + public function getStyles(): array + { + return $this->styles; + } + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * Build an SQL query to checkin all items left checked out longer then a set time. * - * @return a bool - * + * @return bool + * @since 3.2.0 */ - protected function checkInNow() + protected function checkInNow(): bool { // Get set check in time - $time = JComponentHelper::getParams('com_sermondistributor')->get('check_in'); + $time = ComponentHelper::getParams('com_sermondistributor')->get('check_in'); if ($time) { - // Get a db connection. - $db = JFactory::getDbo(); + $db = $this->getDatabase(); // Reset query. $query = $db->getQuery(true); $query->select('*'); @@ -483,7 +588,7 @@ class SermondistributorModelLocal_listings extends ListModel if ($db->getNumRows()) { // Get Yesterdays date. - $date = JFactory::getDate()->modify($time)->toSql(); + $date = Factory::getDate()->modify($time)->toSql(); // Reset query. $query = $db->getQuery(true); @@ -504,7 +609,7 @@ class SermondistributorModelLocal_listings extends ListModel $db->setQuery($query); - $db->execute(); + return $db->execute(); } } diff --git a/admin/src/Model/Manual_updaterModel.php b/admin/src/Model/Manual_updaterModel.php new file mode 100644 index 00000000..d80bce48 --- /dev/null +++ b/admin/src/Model/Manual_updaterModel.php @@ -0,0 +1,290 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\FOF\Encrypt\AES; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\JsonHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor List Model for Manual_updater + * + * @since 1.6 + */ +class Manual_updaterModel extends ListModel +{ + /** + * Represents the current user object. + * + * @var User The user object representing the current user. + * @since 3.2.0 + */ + protected User $user; + + /** + * The unique identifier of the current user. + * + * @var int|null The ID of the current user. + * @since 3.2.0 + */ + protected ?int $userId; + + /** + * Flag indicating whether the current user is a guest. + * + * @var int 1 if the user is a guest, 0 otherwise. + * @since 3.2.0 + */ + protected int $guest; + + /** + * An array of groups that the current user belongs to. + * + * @var array|null An array of user group IDs. + * @since 3.2.0 + */ + protected ?array $groups; + + /** + * An array of view access levels for the current user. + * + * @var array|null An array of access level IDs. + * @since 3.2.0 + */ + protected ?array $levels; + + /** + * The application object. + * + * @var CMSApplicationInterface The application instance. + * @since 3.2.0 + */ + protected CMSApplicationInterface $app; + + /** + * The input object, providing access to the request data. + * + * @var Input The input object. + * @since 3.2.0 + */ + protected Input $input; + + /** + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/manual_updater.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js' + ]; + + /** + * A custom property for UIKit components. (not used unless you load v2) + */ + protected $uikitComp; + + /** + * Constructor + * + * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). + * @param ?MVCFactoryInterface $factory The factory. + * + * @since 1.6 + * @throws \Exception + */ + public function __construct($config = [], MVCFactoryInterface $factory = null) + { + parent::__construct($config, $factory); + + $this->app ??= Factory::getApplication(); + $this->input ??= $this->app->getInput(); + + // Set the current user for authorisation checks (for those calling this model directly) + $this->user ??= $this->getCurrentUser(); + $this->userId = $this->user->get('id'); + $this->guest = $this->user->get('guest'); + $this->groups = $this->user->get('groups'); + $this->authorisedGroups = $this->user->getAuthorisedGroups(); + $this->levels = $this->user->getAuthorisedViewLevels(); + + // will be removed + $this->initSet = true; + } + + /** + * Method to build an SQL query to load the list data. + * + * @return string An SQL query + * @since 1.6 + */ + protected function getListQuery() + { + // Make sure all records load, since no pagination allowed. + $this->setState('list.limit', 0); + // Get a db connection. + $db = $this->getDatabase(); + + // Create a new query object. + $query = $db->getQuery(true); + + // Get from #__sermondistributor_external_source as a + $query->select($db->quoteName( + array('a.id','a.description','a.externalsources','a.build','a.update_method','a.update_timer','a.filetypes','a.oauthtoken','a.permissiontype','a.dropboxoptions','a.sharedurl','a.folder'), + array('id','description','externalsources','build','update_method','update_timer','filetypes','oauthtoken','permissiontype','dropboxoptions','sharedurl','folder'))); + $query->from($db->quoteName('#__sermondistributor_external_source', 'a')); + // Get where a.update_method is 1 + $query->where('a.update_method = 1'); + // Get where a.published is 1 + $query->where('a.published = 1'); + $query->order('a.description ASC'); + + // return the query object + return $query; + } + + /** + * Method to get an array of data items. + * + * @return mixed An array of data items on success, false on failure. + * @since 1.6 + */ + public function getItems() + { + $user = $this->user; + // check if this user has permission to access items + if (!$user->authorise('manual_updater.access', 'com_sermondistributor')) + { + $this->app->enqueueMessage(Text::_('Not authorised!'), 'error'); + // redirect away if not a correct to default view + $this->app->redirect('index.php?option=com_sermondistributor'); + return false; + } + // load parent items + $items = parent::getItems(); + + // Get the global params + $globalParams = ComponentHelper::getParams('com_sermondistributor', true); + + // Get the basic encryption. + $basickey = SermondistributorHelper::getCryptKey('basic'); + // Get the encryption object. + $basic = new AES($basickey); + + // Insure all item fields are adapted where needed. + if (UtilitiesArrayHelper::check($items)) + { + foreach ($items as $nr => &$item) + { + // Always create a slug for sef URL's + $item->slug = ($item->id ?? '0') . (isset($item->alias) ? ':' . $item->alias : ''); + // Check if we can decode filetypes + if (isset($item->filetypes) && JsonHelper::check($item->filetypes)) + { + // Decode filetypes + $item->filetypes = json_decode($item->filetypes, true); + } + // Check if we can decode oauthtoken + if (!empty($item->oauthtoken) && $basickey && !is_numeric($item->oauthtoken) && $item->oauthtoken === base64_encode(base64_decode($item->oauthtoken, true))) + { + // Decode oauthtoken + $item->oauthtoken = rtrim($basic->decryptString($item->oauthtoken), "\0"); + } + } + } + + // return items + return $items; + } + + /** + * Method to get the styles that have to be included on the view + * + * @return array styles files + * @since 4.3 + */ + public function getStyles(): array + { + return $this->styles; + } + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } +} diff --git a/admin/models/preacher.php b/admin/src/Model/PreacherModel.php similarity index 79% rename from admin/models/preacher.php rename to admin/src/Model/PreacherModel.php index 9c8a0c23..fa80729b 100644 --- a/admin/models/preacher.php +++ b/admin/src/Model/PreacherModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage preacher.php + @subpackage PreacherModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,24 +21,48 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Form\Form; +use Joomla\CMS\Filter\InputFilter; +use Joomla\CMS\Filter\OutputFilter; use Joomla\CMS\MVC\Model\AdminModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Table\Table; +use Joomla\CMS\UCM\UCMType; +use Joomla\CMS\Versioning\VersionableModelTrait; +use Joomla\CMS\User\User; use Joomla\Registry\Registry; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper as UtilitiesStringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermondistributor Preacher Admin Model + * + * @since 1.6 */ -class SermondistributorModelPreacher extends AdminModel +class PreacherModel extends AdminModel { + use VersionableModelTrait; + /** * The tab layout fields array. * - * @var array + * @var array + * @since 3.0.0 */ protected $tabLayoutFields = array( 'details' => array( @@ -60,7 +84,29 @@ class SermondistributorModelPreacher extends AdminModel ); /** - * @var string The prefix to use with controller messages. + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/preacher.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js', + 'media/com_sermondistributor/js/preacher.js' + ]; + + /** + * @var string The prefix to use with controller messages. * @since 1.6 */ protected $text_prefix = 'COM_SERMONDISTRIBUTOR'; @@ -80,25 +126,22 @@ class SermondistributorModelPreacher extends AdminModel * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * - * @return JTable A database object - * - * @since 1.6 + * @return Table A database object + * @since 3.0 + * @throws \Exception */ - public function getTable($type = 'preacher', $prefix = 'SermondistributorTable', $config = array()) + public function getTable($type = 'preacher', $prefix = 'Administrator', $config = []) { - // add table path for when model gets used from other component - $this->addTablePath(JPATH_ADMINISTRATOR . '/components/com_sermondistributor/tables'); // get instance of the table - return JTable::getInstance($type, $prefix, $config); + return parent::getTable($type, $prefix, $config); } - + /** * 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) @@ -134,9 +177,9 @@ class SermondistributorModelPreacher extends AdminModel public function getVvvsermons() { // Get the user object. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -179,7 +222,7 @@ class SermondistributorModelPreacher extends AdminModel { $query->where('a.access = ' . (int) $_access); } - elseif (SermondistributorHelper::checkArray($_access)) + elseif (UtilitiesArrayHelper::check($_access)) { // Secure the array for the query $_access = ArrayHelper::toInteger($_access); @@ -205,12 +248,12 @@ class SermondistributorModelPreacher extends AdminModel $items = $db->loadObjectList(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -223,7 +266,7 @@ class SermondistributorModelPreacher extends AdminModel } // Add the tags - $item->tags = new JHelperTags; + $item->tags = new TagsHelper; $item->tags->getTagIds( $item->id, 'com_sermondistributor.sermon' ); @@ -243,7 +286,7 @@ class SermondistributorModelPreacher extends AdminModel } // set selection value to a translatable value - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -262,7 +305,7 @@ class SermondistributorModelPreacher extends AdminModel /** * Method to convert selection values to translatable string. * - * @return translatable string + * @return string The translatable string. */ public function selectionTranslationVvvsermons($value,$name) { @@ -274,7 +317,7 @@ class SermondistributorModelPreacher extends AdminModel 2 => 'COM_SERMONDISTRIBUTOR_SERMON_DIRECT' ); // Now check if value is found in this array - if (isset($link_typeArray[$value]) && SermondistributorHelper::checkString($link_typeArray[$value])) + if (isset($link_typeArray[$value]) && UtilitiesStringHelper::check($link_typeArray[$value])) { return $link_typeArray[$value]; } @@ -289,7 +332,7 @@ class SermondistributorModelPreacher extends AdminModel 3 => 'COM_SERMONDISTRIBUTOR_SERMON_URL' ); // Now check if value is found in this array - if (isset($sourceArray[$value]) && SermondistributorHelper::checkString($sourceArray[$value])) + if (isset($sourceArray[$value]) && UtilitiesStringHelper::check($sourceArray[$value])) { return $sourceArray[$value]; } @@ -304,11 +347,10 @@ class SermondistributorModelPreacher extends AdminModel * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @param array $options Optional array of options for the form creation. * - * @return mixed A JForm object on success, false on failure - * + * @return Form|boolean A Form object on success, false on failure * @since 1.6 */ - public function getForm($data = array(), $loadData = true, $options = array('control' => 'jform')) + public function getForm($data = [], $loadData = true, $options = ['control' => 'jform']) { // set load data option $options['load_data'] = $loadData; @@ -335,7 +377,7 @@ class SermondistributorModelPreacher extends AdminModel return false; } - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first. if ($jinput->get('a_id')) @@ -348,7 +390,7 @@ class SermondistributorModelPreacher extends AdminModel $id = $jinput->get('id', 0, 'INT'); } - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Check for existing item. // Modify the form based on Edit State access controls. @@ -409,38 +451,66 @@ class SermondistributorModelPreacher extends AdminModel } /** - * Method to get the script that have to be included on the form + * Method to get the styles that have to be included on the view * - * @return string script files + * @return array styles files + * @since 4.3 */ - public function getScript() + public function getStyles(): array { - return 'media/com_sermondistributor/js/preacher.js'; + return $this->styles; } - + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * 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 set in the component. - * * @since 1.6 */ protected function canDelete($record) { - if (!empty($record->id)) + if (empty($record->id) || ($record->published != -2)) { - if ($record->published != -2) - { - return; - } - - $user = JFactory::getUser(); - // The record has been set. Check the record permissions. - return $user->authorise('preacher.delete', 'com_sermondistributor.preacher.' . (int) $record->id); + return false; } - return false; + + // The record has been set. Check the record permissions. + return $this->getCurrentUser()->authorise('preacher.delete', 'com_sermondistributor.preacher.' . (int) $record->id); } /** @@ -449,13 +519,12 @@ class SermondistributorModelPreacher extends AdminModel * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. - * * @since 1.6 */ protected function canEditState($record) { - $user = JFactory::getUser(); - $recordId = (!empty($record->id)) ? $record->id : 0; + $user = $this->getCurrentUser(); + $recordId = $record->id ?? 0; if ($recordId) { @@ -466,51 +535,50 @@ class SermondistributorModelPreacher extends AdminModel return false; } } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('preacher.edit.state', 'com_sermondistributor'); } - + /** * Method override to check if you can edit an existing record. * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key. + * @param array $data An array of input data. + * @param string $key The name of the key for the primary key. * - * @return boolean - * @since 2.5 + * @return boolean + * @since 2.5 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // Check specific edit permission then general edit permission. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); return $user->authorise('preacher.edit', 'com_sermondistributor.preacher.'. ((int) isset($data[$key]) ? $data[$key] : 0)) or $user->authorise('preacher.edit', 'com_sermondistributor'); } - + /** * Prepare and sanitise the table data prior to saving. * - * @param JTable $table A JTable object. + * @param Table $table A Table object. * * @return void - * * @since 1.6 */ protected function prepareTable($table) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); - + $date = Factory::getDate(); + $user = $this->getCurrentUser(); + if (isset($table->name)) { - $table->name = htmlspecialchars_decode($table->name, ENT_QUOTES); + $table->name = \htmlspecialchars_decode($table->name, ENT_QUOTES); } - + if (isset($table->alias) && empty($table->alias)) { $table->generateAlias(); } - + if (empty($table->id)) { $table->created = $date->toSql(); @@ -522,7 +590,7 @@ class SermondistributorModelPreacher extends AdminModel // Set ordering to the last item if not set if (empty($table->ordering)) { - $db = JFactory::getDbo(); + $db = $this->getDatabase(); $query = $db->getQuery(true) ->select('MAX(ordering)') ->from($db->quoteName('#__sermondistributor_preacher')); @@ -537,7 +605,7 @@ class SermondistributorModelPreacher extends AdminModel $table->modified = $date->toSql(); $table->modified_by = $user->id; } - + if (!empty($table->id)) { // Increment the items version number. @@ -549,21 +617,21 @@ class SermondistributorModelPreacher extends AdminModel * Method to get the data that should be injected in the form. * * @return mixed The data for the form. - * * @since 1.6 */ - protected function loadFormData() + protected function loadFormData() { // Check the session for previously entered form data. - $data = JFactory::getApplication()->getUserState('com_sermondistributor.edit.preacher.data', array()); + $data = Factory::getApplication()->getUserState('com_sermondistributor.edit.preacher.data', []); if (empty($data)) { $data = $this->getItem(); - // run the perprocess of the data - $this->preprocessData('com_sermondistributor.preacher', $data); } + // run the perprocess of the data + $this->preprocessData('com_sermondistributor.preacher', $data); + return $data; } @@ -578,14 +646,13 @@ class SermondistributorModelPreacher extends AdminModel { return false; } - + /** * Method to delete one or more records. * * @param array &$pks An array of record primary keys. * - * @return boolean True if successful, false if an error occurs. - * + * @return boolean True if successful, false if an error occurs * @since 12.2 */ public function delete(&$pks) @@ -594,7 +661,7 @@ class SermondistributorModelPreacher extends AdminModel { return false; } - + return true; } @@ -605,7 +672,6 @@ class SermondistributorModelPreacher extends AdminModel * @param integer $value The value of the published state. * * @return boolean True on success. - * * @since 12.2 */ public function publish(&$pks, $value = 1) @@ -614,10 +680,10 @@ class SermondistributorModelPreacher extends AdminModel { return false; } - + return true; - } - + } + /** * Method to perform batch operations on an item or a set of items. * @@ -626,7 +692,6 @@ class SermondistributorModelPreacher extends AdminModel * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. - * * @since 12.2 */ public function batch($commands, $pks, $contexts) @@ -643,30 +708,30 @@ class SermondistributorModelPreacher extends AdminModel if (empty($pks)) { - $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); + $this->setError(Text::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; // Set some needed variables. - $this->user = JFactory::getUser(); - $this->table = $this->getTable(); - $this->tableClassName = get_class($this->table); - $this->contentType = new JUcmType; - $this->type = $this->contentType->getTypeByTable($this->tableClassName); - $this->canDo = SermondistributorHelper::getActions('preacher'); - $this->batchSet = true; + $this->user ??= $this->getCurrentUser(); + $this->table = $this->getTable(); + $this->tableClassName = get_class($this->table); + $this->contentType = new UCMType; + $this->type = $this->contentType->getTypeByTable($this->tableClassName); + $this->canDo = SermondistributorHelper::getActions('preacher'); + $this->batchSet = true; if (!$this->canDo->get('core.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } - + if ($this->type == false) { - $type = new JUcmType; + $type = new UCMType; $this->type = $type->getTypeByAlias($this->typeAlias); } @@ -703,8 +768,7 @@ class SermondistributorModelPreacher extends AdminModel if (!$done) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); - + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } @@ -730,7 +794,7 @@ class SermondistributorModelPreacher extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('preacher'); @@ -756,7 +820,7 @@ class SermondistributorModelPreacher extends AdminModel $values['published'] = 0; } - $newIds = array(); + $newIds = []; // Parent exists so let's proceed while (!empty($pks)) { @@ -769,7 +833,7 @@ class SermondistributorModelPreacher extends AdminModel if (!$this->user->authorise('preacher.edit', $contexts[$pk])) { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } @@ -785,14 +849,14 @@ class SermondistributorModelPreacher extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } list($this->table->name, $this->table->alias) = $this->_generateNewTitle($this->table->alias, $this->table->name); // insert all set values - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -804,7 +868,7 @@ class SermondistributorModelPreacher extends AdminModel } // update all unique fields - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -868,7 +932,7 @@ class SermondistributorModelPreacher extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('preacher'); @@ -876,7 +940,7 @@ class SermondistributorModelPreacher extends AdminModel if (!$this->canDo->get('preacher.edit') && !$this->canDo->get('preacher.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -893,7 +957,7 @@ class SermondistributorModelPreacher extends AdminModel { if (!$this->user->authorise('preacher.edit', $contexts[$pk])) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -909,13 +973,13 @@ class SermondistributorModelPreacher extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // insert all set values. - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -959,35 +1023,34 @@ class SermondistributorModelPreacher extends AdminModel return true; } - + /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. - * * @since 1.6 */ public function save($data) { - $input = JFactory::getApplication()->input; - $filter = JFilterInput::getInstance(); - + $input = Factory::getApplication()->getInput(); + $filter = InputFilter::getInstance(); + // set the metadata to the Item Data if (isset($data['metadata']) && isset($data['metadata']['author'])) { $data['metadata']['author'] = $filter->clean($data['metadata']['author'], 'TRIM'); - - $metadata = new JRegistry; + + $metadata = new Registry; $metadata->loadArray($data['metadata']); $data['metadata'] = (string) $metadata; } - + // Set the Params Items to data if (isset($data['params']) && is_array($data['params'])) { - $params = new JRegistry; + $params = new Registry; $params->loadArray($data['params']); $data['params'] = (string) $params; } @@ -1020,27 +1083,27 @@ class SermondistributorModelPreacher extends AdminModel { if ($data['alias'] == null || empty($data['alias'])) { - if (JFactory::getConfig()->get('unicodeslugs') == 1) + if (Factory::getConfig()->get('unicodeslugs') == 1) { - $data['alias'] = JFilterOutput::stringURLUnicodeSlug($data['name']); + $data['alias'] = OutputFilter::stringURLUnicodeSlug($data['name']); } else { - $data['alias'] = JFilterOutput::stringURLSafe($data['name']); + $data['alias'] = OutputFilter::stringURLSafe($data['name']); } - $table = JTable::getInstance('preacher', 'sermondistributorTable'); + $table = clone $this->getTable(); if ($table->load(array('alias' => $data['alias'])) && ($table->id != $data['id'] || $data['id'] == 0)) { - $msg = JText::_('COM_SERMONDISTRIBUTOR_PREACHER_SAVE_WARNING'); + $msg = Text::_('COM_SERMONDISTRIBUTOR_PREACHER_SAVE_WARNING'); } $data['alias'] = $this->_generateNewTitle($data['alias']); if (isset($msg)) { - JFactory::getApplication()->enqueueMessage($msg, 'warning'); + Factory::getApplication()->enqueueMessage($msg, 'warning'); } } } @@ -1050,7 +1113,7 @@ class SermondistributorModelPreacher extends AdminModel { // Automatic handling of other unique fields $uniqueFields = $this->getUniqueFields(); - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -1058,14 +1121,14 @@ class SermondistributorModelPreacher extends AdminModel } } } - + if (parent::save($data)) { return true; } return false; } - + /** * Method to generate a unique value. * @@ -1073,16 +1136,14 @@ class SermondistributorModelPreacher extends AdminModel * @param string $value data. * * @return string New value. - * * @since 3.0 */ - protected function generateUnique($field,$value) + protected function generateUnique($field, $value) { - // set field value unique $table = $this->getTable(); - while ($table->load(array($field => $value))) + while ($table->load([$field => $value])) { $value = StringHelper::increment($value); } @@ -1105,10 +1166,10 @@ class SermondistributorModelPreacher extends AdminModel // Alter the title/s & alias $table = $this->getTable(); - while ($table->load(array('alias' => $alias))) + while ($table->load(['alias' => $alias])) { // Check if this is an array of titles - if (SermondistributorHelper::checkArray($title)) + if (UtilitiesArrayHelper::check($title)) { foreach($title as $nr => &$_title) { @@ -1123,7 +1184,7 @@ class SermondistributorModelPreacher extends AdminModel $alias = StringHelper::increment($alias, 'dash'); } // Check if this is an array of titles - if (SermondistributorHelper::checkArray($title)) + if (UtilitiesArrayHelper::check($title)) { $title[] = $alias; return $title; diff --git a/admin/models/preachers.php b/admin/src/Model/PreachersModel.php similarity index 74% rename from admin/models/preachers.php rename to admin/src/Model/PreachersModel.php index b584c48e..08b30318 100644 --- a/admin/models/preachers.php +++ b/admin/src/Model/PreachersModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage preachers.php + @subpackage PreachersModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,22 +21,77 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Preachers List Model + * + * @since 1.6 */ -class SermondistributorModelPreachers extends ListModel +class PreachersModel extends ListModel { - public function __construct($config = array()) + /** + * The application object. + * + * @var CMSApplicationInterface The application instance. + * @since 3.2.0 + */ + protected CMSApplicationInterface $app; + + /** + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/preachers.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js' + ]; + + /** + * Constructor + * + * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). + * @param ?MVCFactoryInterface $factory The factory. + * + * @since 1.6 + * @throws \Exception + */ + public function __construct($config = [], MVCFactoryInterface $factory = null) { if (empty($config['filter_fields'])) - { + { $config['filter_fields'] = array( 'a.id','id', 'a.published','published', @@ -49,7 +104,9 @@ class SermondistributorModelPreachers extends ListModel ); } - parent::__construct($config); + parent::__construct($config, $factory); + + $this->app ??= Factory::getApplication(); } /** @@ -61,11 +118,11 @@ class SermondistributorModelPreachers extends ListModel * @param string $direction An optional direction (asc|desc). * * @return void - * + * @since 1.7.0 */ protected function populateState($ordering = null, $direction = null) { - $app = JFactory::getApplication(); + $app = $this->app; // Adjust the context to support modal layouts. if ($layout = $app->input->get('layout')) @@ -115,11 +172,12 @@ class SermondistributorModelPreachers extends ListModel // List state information. parent::populateState($ordering, $direction); } - + /** * Method to get an array of data items. * * @return mixed An array of data items on success, false on failure. + * @since 1.6 */ public function getItems() { @@ -130,12 +188,12 @@ class SermondistributorModelPreachers extends ListModel $items = parent::getItems(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -149,22 +207,23 @@ class SermondistributorModelPreachers extends ListModel } } - + // return items return $items; } - + /** * Method to build an SQL query to load the list data. * - * @return string An SQL query + * @return string An SQL query + * @since 1.6 */ protected function getListQuery() { // Get the user object. - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -193,7 +252,7 @@ class SermondistributorModelPreachers extends ListModel { $query->where('a.access = ' . (int) $_access); } - elseif (SermondistributorHelper::checkArray($_access)) + elseif (UtilitiesArrayHelper::check($_access)) { // Secure the array for the query $_access = ArrayHelper::toInteger($_access); @@ -223,10 +282,12 @@ class SermondistributorModelPreachers extends ListModel // Add the list ordering clause. - $orderCol = $this->state->get('list.ordering', 'a.id'); - $orderDirn = $this->state->get('list.direction', 'desc'); + $orderCol = $this->getState('list.ordering', 'a.id'); + $orderDirn = $this->getState('list.direction', 'desc'); if ($orderCol != '') { + // Check that the order direction is valid encase we have a field called direction as part of filers. + $orderDirn = (is_string($orderDirn) && in_array(strtolower($orderDirn), ['asc', 'desc'])) ? $orderDirn : 'desc'; $query->order($db->escape($orderCol . ' ' . $orderDirn)); } @@ -244,17 +305,17 @@ class SermondistributorModelPreachers extends ListModel public function getExportData($pks, $user = null) { // setup the query - if (($pks_size = SermondistributorHelper::checkArray($pks)) !== false || 'bulk' === $pks) + if (($pks_size = UtilitiesArrayHelper::check($pks)) !== false || 'bulk' === $pks) { // Set a value to know this is export method. (USE IN CUSTOM CODE TO ALTER OUTCOME) $_export = true; // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -298,7 +359,7 @@ class SermondistributorModelPreachers extends ListModel $items = $db->loadObjectList(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -318,7 +379,7 @@ class SermondistributorModelPreachers extends ListModel } // Add headers to items array. $headers = $this->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { array_unshift($items,$headers); } @@ -336,16 +397,16 @@ class SermondistributorModelPreachers extends ListModel public function getExImPortHeaders() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getDbo(); // get the columns $columns = $db->getTableColumns("#__sermondistributor_preacher"); - if (SermondistributorHelper::checkArray($columns)) + if (UtilitiesArrayHelper::check($columns)) { // remove the headers you don't import/export. unset($columns['asset_id']); unset($columns['checked_out']); unset($columns['checked_out_time']); - $headers = new stdClass(); + $headers = new \stdClass(); foreach ($columns as $column => $type) { $headers->{$column} = $column; @@ -354,12 +415,12 @@ class SermondistributorModelPreachers extends ListModel } return false; } - + /** * Method to get a store id based on model configuration state. * * @return string A store id. - * + * @since 1.6 */ protected function getStoreId($id = '') { @@ -369,13 +430,13 @@ class SermondistributorModelPreachers extends ListModel $id .= ':' . $this->getState('filter.published'); // Check if the value is an array $_access = $this->getState('filter.access'); - if (SermondistributorHelper::checkArray($_access)) + if (UtilitiesArrayHelper::check($_access)) { $id .= ':' . implode(':', $_access); } // Check if this is only an number or string elseif (is_numeric($_access) - || SermondistributorHelper::checkString($_access)) + || StringHelper::check($_access)) { $id .= ':' . $_access; } @@ -388,22 +449,65 @@ class SermondistributorModelPreachers extends ListModel return parent::getStoreId($id); } + /** + * Method to get the styles that have to be included on the view + * + * @return array styles files + * @since 4.3 + */ + public function getStyles(): array + { + return $this->styles; + } + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * Build an SQL query to checkin all items left checked out longer then a set time. * - * @return a bool - * + * @return bool + * @since 3.2.0 */ - protected function checkInNow() + protected function checkInNow(): bool { // Get set check in time - $time = JComponentHelper::getParams('com_sermondistributor')->get('check_in'); + $time = ComponentHelper::getParams('com_sermondistributor')->get('check_in'); if ($time) { - // Get a db connection. - $db = JFactory::getDbo(); + $db = $this->getDatabase(); // Reset query. $query = $db->getQuery(true); $query->select('*'); @@ -415,7 +519,7 @@ class SermondistributorModelPreachers extends ListModel if ($db->getNumRows()) { // Get Yesterdays date. - $date = JFactory::getDate()->modify($time)->toSql(); + $date = Factory::getDate()->modify($time)->toSql(); // Reset query. $query = $db->getQuery(true); @@ -436,7 +540,7 @@ class SermondistributorModelPreachers extends ListModel $db->setQuery($query); - $db->execute(); + return $db->execute(); } } diff --git a/admin/models/series.php b/admin/src/Model/SeriesModel.php similarity index 79% rename from admin/models/series.php rename to admin/src/Model/SeriesModel.php index 7fdca8d4..48cf6f0c 100644 --- a/admin/models/series.php +++ b/admin/src/Model/SeriesModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage series.php + @subpackage SeriesModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,24 +21,48 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Form\Form; +use Joomla\CMS\Filter\InputFilter; +use Joomla\CMS\Filter\OutputFilter; use Joomla\CMS\MVC\Model\AdminModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Table\Table; +use Joomla\CMS\UCM\UCMType; +use Joomla\CMS\Versioning\VersionableModelTrait; +use Joomla\CMS\User\User; use Joomla\Registry\Registry; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper as UtilitiesStringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermondistributor Series Admin Model + * + * @since 1.6 */ -class SermondistributorModelSeries extends AdminModel +class SeriesModel extends AdminModel { + use VersionableModelTrait; + /** * The tab layout fields array. * - * @var array + * @var array + * @since 3.0.0 */ protected $tabLayoutFields = array( 'details' => array( @@ -59,7 +83,29 @@ class SermondistributorModelSeries extends AdminModel ); /** - * @var string The prefix to use with controller messages. + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/series.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js', + 'media/com_sermondistributor/js/series.js' + ]; + + /** + * @var string The prefix to use with controller messages. * @since 1.6 */ protected $text_prefix = 'COM_SERMONDISTRIBUTOR'; @@ -79,25 +125,22 @@ class SermondistributorModelSeries extends AdminModel * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * - * @return JTable A database object - * - * @since 1.6 + * @return Table A database object + * @since 3.0 + * @throws \Exception */ - public function getTable($type = 'series', $prefix = 'SermondistributorTable', $config = array()) + public function getTable($type = 'series', $prefix = 'Administrator', $config = []) { - // add table path for when model gets used from other component - $this->addTablePath(JPATH_ADMINISTRATOR . '/components/com_sermondistributor/tables'); // get instance of the table - return JTable::getInstance($type, $prefix, $config); + return parent::getTable($type, $prefix, $config); } - + /** * 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) @@ -133,9 +176,9 @@ class SermondistributorModelSeries extends AdminModel public function getVwcsermons() { // Get the user object. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -178,7 +221,7 @@ class SermondistributorModelSeries extends AdminModel { $query->where('a.access = ' . (int) $_access); } - elseif (SermondistributorHelper::checkArray($_access)) + elseif (UtilitiesArrayHelper::check($_access)) { // Secure the array for the query $_access = ArrayHelper::toInteger($_access); @@ -204,12 +247,12 @@ class SermondistributorModelSeries extends AdminModel $items = $db->loadObjectList(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -222,7 +265,7 @@ class SermondistributorModelSeries extends AdminModel } // Add the tags - $item->tags = new JHelperTags; + $item->tags = new TagsHelper; $item->tags->getTagIds( $item->id, 'com_sermondistributor.sermon' ); @@ -242,7 +285,7 @@ class SermondistributorModelSeries extends AdminModel } // set selection value to a translatable value - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -261,7 +304,7 @@ class SermondistributorModelSeries extends AdminModel /** * Method to convert selection values to translatable string. * - * @return translatable string + * @return string The translatable string. */ public function selectionTranslationVwcsermons($value,$name) { @@ -273,7 +316,7 @@ class SermondistributorModelSeries extends AdminModel 2 => 'COM_SERMONDISTRIBUTOR_SERMON_DIRECT' ); // Now check if value is found in this array - if (isset($link_typeArray[$value]) && SermondistributorHelper::checkString($link_typeArray[$value])) + if (isset($link_typeArray[$value]) && UtilitiesStringHelper::check($link_typeArray[$value])) { return $link_typeArray[$value]; } @@ -288,7 +331,7 @@ class SermondistributorModelSeries extends AdminModel 3 => 'COM_SERMONDISTRIBUTOR_SERMON_URL' ); // Now check if value is found in this array - if (isset($sourceArray[$value]) && SermondistributorHelper::checkString($sourceArray[$value])) + if (isset($sourceArray[$value]) && UtilitiesStringHelper::check($sourceArray[$value])) { return $sourceArray[$value]; } @@ -303,11 +346,10 @@ class SermondistributorModelSeries extends AdminModel * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @param array $options Optional array of options for the form creation. * - * @return mixed A JForm object on success, false on failure - * + * @return Form|boolean A Form object on success, false on failure * @since 1.6 */ - public function getForm($data = array(), $loadData = true, $options = array('control' => 'jform')) + public function getForm($data = [], $loadData = true, $options = ['control' => 'jform']) { // set load data option $options['load_data'] = $loadData; @@ -334,7 +376,7 @@ class SermondistributorModelSeries extends AdminModel return false; } - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first. if ($jinput->get('a_id')) @@ -347,7 +389,7 @@ class SermondistributorModelSeries extends AdminModel $id = $jinput->get('id', 0, 'INT'); } - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Check for existing item. // Modify the form based on Edit State access controls. @@ -408,38 +450,66 @@ class SermondistributorModelSeries extends AdminModel } /** - * Method to get the script that have to be included on the form + * Method to get the styles that have to be included on the view * - * @return string script files + * @return array styles files + * @since 4.3 */ - public function getScript() + public function getStyles(): array { - return 'media/com_sermondistributor/js/series.js'; + return $this->styles; } - + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * 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 set in the component. - * * @since 1.6 */ protected function canDelete($record) { - if (!empty($record->id)) + if (empty($record->id) || ($record->published != -2)) { - if ($record->published != -2) - { - return; - } - - $user = JFactory::getUser(); - // The record has been set. Check the record permissions. - return $user->authorise('series.delete', 'com_sermondistributor.series.' . (int) $record->id); + return false; } - return false; + + // The record has been set. Check the record permissions. + return $this->getCurrentUser()->authorise('series.delete', 'com_sermondistributor.series.' . (int) $record->id); } /** @@ -448,13 +518,12 @@ class SermondistributorModelSeries extends AdminModel * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. - * * @since 1.6 */ protected function canEditState($record) { - $user = JFactory::getUser(); - $recordId = (!empty($record->id)) ? $record->id : 0; + $user = $this->getCurrentUser(); + $recordId = $record->id ?? 0; if ($recordId) { @@ -465,51 +534,50 @@ class SermondistributorModelSeries extends AdminModel return false; } } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('series.edit.state', 'com_sermondistributor'); } - + /** * Method override to check if you can edit an existing record. * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key. + * @param array $data An array of input data. + * @param string $key The name of the key for the primary key. * - * @return boolean - * @since 2.5 + * @return boolean + * @since 2.5 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // Check specific edit permission then general edit permission. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); return $user->authorise('series.edit', 'com_sermondistributor.series.'. ((int) isset($data[$key]) ? $data[$key] : 0)) or $user->authorise('series.edit', 'com_sermondistributor'); } - + /** * Prepare and sanitise the table data prior to saving. * - * @param JTable $table A JTable object. + * @param Table $table A Table object. * * @return void - * * @since 1.6 */ protected function prepareTable($table) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); - + $date = Factory::getDate(); + $user = $this->getCurrentUser(); + if (isset($table->name)) { - $table->name = htmlspecialchars_decode($table->name, ENT_QUOTES); + $table->name = \htmlspecialchars_decode($table->name, ENT_QUOTES); } - + if (isset($table->alias) && empty($table->alias)) { $table->generateAlias(); } - + if (empty($table->id)) { $table->created = $date->toSql(); @@ -521,7 +589,7 @@ class SermondistributorModelSeries extends AdminModel // Set ordering to the last item if not set if (empty($table->ordering)) { - $db = JFactory::getDbo(); + $db = $this->getDatabase(); $query = $db->getQuery(true) ->select('MAX(ordering)') ->from($db->quoteName('#__sermondistributor_series')); @@ -536,7 +604,7 @@ class SermondistributorModelSeries extends AdminModel $table->modified = $date->toSql(); $table->modified_by = $user->id; } - + if (!empty($table->id)) { // Increment the items version number. @@ -548,21 +616,21 @@ class SermondistributorModelSeries extends AdminModel * Method to get the data that should be injected in the form. * * @return mixed The data for the form. - * * @since 1.6 */ - protected function loadFormData() + protected function loadFormData() { // Check the session for previously entered form data. - $data = JFactory::getApplication()->getUserState('com_sermondistributor.edit.series.data', array()); + $data = Factory::getApplication()->getUserState('com_sermondistributor.edit.series.data', []); if (empty($data)) { $data = $this->getItem(); - // run the perprocess of the data - $this->preprocessData('com_sermondistributor.series', $data); } + // run the perprocess of the data + $this->preprocessData('com_sermondistributor.series', $data); + return $data; } @@ -577,14 +645,13 @@ class SermondistributorModelSeries extends AdminModel { return false; } - + /** * Method to delete one or more records. * * @param array &$pks An array of record primary keys. * - * @return boolean True if successful, false if an error occurs. - * + * @return boolean True if successful, false if an error occurs * @since 12.2 */ public function delete(&$pks) @@ -593,7 +660,7 @@ class SermondistributorModelSeries extends AdminModel { return false; } - + return true; } @@ -604,7 +671,6 @@ class SermondistributorModelSeries extends AdminModel * @param integer $value The value of the published state. * * @return boolean True on success. - * * @since 12.2 */ public function publish(&$pks, $value = 1) @@ -613,10 +679,10 @@ class SermondistributorModelSeries extends AdminModel { return false; } - + return true; - } - + } + /** * Method to perform batch operations on an item or a set of items. * @@ -625,7 +691,6 @@ class SermondistributorModelSeries extends AdminModel * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. - * * @since 12.2 */ public function batch($commands, $pks, $contexts) @@ -642,30 +707,30 @@ class SermondistributorModelSeries extends AdminModel if (empty($pks)) { - $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); + $this->setError(Text::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; // Set some needed variables. - $this->user = JFactory::getUser(); - $this->table = $this->getTable(); - $this->tableClassName = get_class($this->table); - $this->contentType = new JUcmType; - $this->type = $this->contentType->getTypeByTable($this->tableClassName); - $this->canDo = SermondistributorHelper::getActions('series'); - $this->batchSet = true; + $this->user ??= $this->getCurrentUser(); + $this->table = $this->getTable(); + $this->tableClassName = get_class($this->table); + $this->contentType = new UCMType; + $this->type = $this->contentType->getTypeByTable($this->tableClassName); + $this->canDo = SermondistributorHelper::getActions('series'); + $this->batchSet = true; if (!$this->canDo->get('core.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } - + if ($this->type == false) { - $type = new JUcmType; + $type = new UCMType; $this->type = $type->getTypeByAlias($this->typeAlias); } @@ -702,8 +767,7 @@ class SermondistributorModelSeries extends AdminModel if (!$done) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); - + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } @@ -729,7 +793,7 @@ class SermondistributorModelSeries extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('series'); @@ -755,7 +819,7 @@ class SermondistributorModelSeries extends AdminModel $values['published'] = 0; } - $newIds = array(); + $newIds = []; // Parent exists so let's proceed while (!empty($pks)) { @@ -768,7 +832,7 @@ class SermondistributorModelSeries extends AdminModel if (!$this->user->authorise('series.edit', $contexts[$pk])) { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } @@ -784,14 +848,14 @@ class SermondistributorModelSeries extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } list($this->table->name, $this->table->alias) = $this->_generateNewTitle($this->table->alias, $this->table->name); // insert all set values - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -803,7 +867,7 @@ class SermondistributorModelSeries extends AdminModel } // update all unique fields - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -867,7 +931,7 @@ class SermondistributorModelSeries extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('series'); @@ -875,7 +939,7 @@ class SermondistributorModelSeries extends AdminModel if (!$this->canDo->get('series.edit') && !$this->canDo->get('series.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -892,7 +956,7 @@ class SermondistributorModelSeries extends AdminModel { if (!$this->user->authorise('series.edit', $contexts[$pk])) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -908,13 +972,13 @@ class SermondistributorModelSeries extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // insert all set values. - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -958,35 +1022,34 @@ class SermondistributorModelSeries extends AdminModel return true; } - + /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. - * * @since 1.6 */ public function save($data) { - $input = JFactory::getApplication()->input; - $filter = JFilterInput::getInstance(); - + $input = Factory::getApplication()->getInput(); + $filter = InputFilter::getInstance(); + // set the metadata to the Item Data if (isset($data['metadata']) && isset($data['metadata']['author'])) { $data['metadata']['author'] = $filter->clean($data['metadata']['author'], 'TRIM'); - - $metadata = new JRegistry; + + $metadata = new Registry; $metadata->loadArray($data['metadata']); $data['metadata'] = (string) $metadata; } - + // Set the Params Items to data if (isset($data['params']) && is_array($data['params'])) { - $params = new JRegistry; + $params = new Registry; $params->loadArray($data['params']); $data['params'] = (string) $params; } @@ -1019,27 +1082,27 @@ class SermondistributorModelSeries extends AdminModel { if ($data['alias'] == null || empty($data['alias'])) { - if (JFactory::getConfig()->get('unicodeslugs') == 1) + if (Factory::getConfig()->get('unicodeslugs') == 1) { - $data['alias'] = JFilterOutput::stringURLUnicodeSlug($data['name']); + $data['alias'] = OutputFilter::stringURLUnicodeSlug($data['name']); } else { - $data['alias'] = JFilterOutput::stringURLSafe($data['name']); + $data['alias'] = OutputFilter::stringURLSafe($data['name']); } - $table = JTable::getInstance('series', 'sermondistributorTable'); + $table = clone $this->getTable(); if ($table->load(array('alias' => $data['alias'])) && ($table->id != $data['id'] || $data['id'] == 0)) { - $msg = JText::_('COM_SERMONDISTRIBUTOR_SERIES_SAVE_WARNING'); + $msg = Text::_('COM_SERMONDISTRIBUTOR_SERIES_SAVE_WARNING'); } $data['alias'] = $this->_generateNewTitle($data['alias']); if (isset($msg)) { - JFactory::getApplication()->enqueueMessage($msg, 'warning'); + Factory::getApplication()->enqueueMessage($msg, 'warning'); } } } @@ -1049,7 +1112,7 @@ class SermondistributorModelSeries extends AdminModel { // Automatic handling of other unique fields $uniqueFields = $this->getUniqueFields(); - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -1057,14 +1120,14 @@ class SermondistributorModelSeries extends AdminModel } } } - + if (parent::save($data)) { return true; } return false; } - + /** * Method to generate a unique value. * @@ -1072,16 +1135,14 @@ class SermondistributorModelSeries extends AdminModel * @param string $value data. * * @return string New value. - * * @since 3.0 */ - protected function generateUnique($field,$value) + protected function generateUnique($field, $value) { - // set field value unique $table = $this->getTable(); - while ($table->load(array($field => $value))) + while ($table->load([$field => $value])) { $value = StringHelper::increment($value); } @@ -1104,10 +1165,10 @@ class SermondistributorModelSeries extends AdminModel // Alter the title/s & alias $table = $this->getTable(); - while ($table->load(array('alias' => $alias))) + while ($table->load(['alias' => $alias])) { // Check if this is an array of titles - if (SermondistributorHelper::checkArray($title)) + if (UtilitiesArrayHelper::check($title)) { foreach($title as $nr => &$_title) { @@ -1122,7 +1183,7 @@ class SermondistributorModelSeries extends AdminModel $alias = StringHelper::increment($alias, 'dash'); } // Check if this is an array of titles - if (SermondistributorHelper::checkArray($title)) + if (UtilitiesArrayHelper::check($title)) { $title[] = $alias; return $title; diff --git a/admin/models/series_list.php b/admin/src/Model/Series_listModel.php similarity index 73% rename from admin/models/series_list.php rename to admin/src/Model/Series_listModel.php index 4bc50497..8bc695a4 100644 --- a/admin/models/series_list.php +++ b/admin/src/Model/Series_listModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage series_list.php + @subpackage Series_listModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,22 +21,77 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Series_list List Model + * + * @since 1.6 */ -class SermondistributorModelSeries_list extends ListModel +class Series_listModel extends ListModel { - public function __construct($config = array()) + /** + * The application object. + * + * @var CMSApplicationInterface The application instance. + * @since 3.2.0 + */ + protected CMSApplicationInterface $app; + + /** + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/series_list.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js' + ]; + + /** + * Constructor + * + * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). + * @param ?MVCFactoryInterface $factory The factory. + * + * @since 1.6 + * @throws \Exception + */ + public function __construct($config = [], MVCFactoryInterface $factory = null) { if (empty($config['filter_fields'])) - { + { $config['filter_fields'] = array( 'a.id','id', 'a.published','published', @@ -48,7 +103,9 @@ class SermondistributorModelSeries_list extends ListModel ); } - parent::__construct($config); + parent::__construct($config, $factory); + + $this->app ??= Factory::getApplication(); } /** @@ -60,11 +117,11 @@ class SermondistributorModelSeries_list extends ListModel * @param string $direction An optional direction (asc|desc). * * @return void - * + * @since 1.7.0 */ protected function populateState($ordering = null, $direction = null) { - $app = JFactory::getApplication(); + $app = $this->app; // Adjust the context to support modal layouts. if ($layout = $app->input->get('layout')) @@ -107,11 +164,12 @@ class SermondistributorModelSeries_list extends ListModel // List state information. parent::populateState($ordering, $direction); } - + /** * Method to get an array of data items. * * @return mixed An array of data items on success, false on failure. + * @since 1.6 */ public function getItems() { @@ -122,12 +180,12 @@ class SermondistributorModelSeries_list extends ListModel $items = parent::getItems(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -141,22 +199,23 @@ class SermondistributorModelSeries_list extends ListModel } } - + // return items return $items; } - + /** * Method to build an SQL query to load the list data. * - * @return string An SQL query + * @return string An SQL query + * @since 1.6 */ protected function getListQuery() { // Get the user object. - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -185,7 +244,7 @@ class SermondistributorModelSeries_list extends ListModel { $query->where('a.access = ' . (int) $_access); } - elseif (SermondistributorHelper::checkArray($_access)) + elseif (UtilitiesArrayHelper::check($_access)) { // Secure the array for the query $_access = ArrayHelper::toInteger($_access); @@ -215,10 +274,12 @@ class SermondistributorModelSeries_list extends ListModel // Add the list ordering clause. - $orderCol = $this->state->get('list.ordering', 'a.id'); - $orderDirn = $this->state->get('list.direction', 'desc'); + $orderCol = $this->getState('list.ordering', 'a.id'); + $orderDirn = $this->getState('list.direction', 'desc'); if ($orderCol != '') { + // Check that the order direction is valid encase we have a field called direction as part of filers. + $orderDirn = (is_string($orderDirn) && in_array(strtolower($orderDirn), ['asc', 'desc'])) ? $orderDirn : 'desc'; $query->order($db->escape($orderCol . ' ' . $orderDirn)); } @@ -236,17 +297,17 @@ class SermondistributorModelSeries_list extends ListModel public function getExportData($pks, $user = null) { // setup the query - if (($pks_size = SermondistributorHelper::checkArray($pks)) !== false || 'bulk' === $pks) + if (($pks_size = UtilitiesArrayHelper::check($pks)) !== false || 'bulk' === $pks) { // Set a value to know this is export method. (USE IN CUSTOM CODE TO ALTER OUTCOME) $_export = true; // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -290,7 +351,7 @@ class SermondistributorModelSeries_list extends ListModel $items = $db->loadObjectList(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -310,7 +371,7 @@ class SermondistributorModelSeries_list extends ListModel } // Add headers to items array. $headers = $this->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { array_unshift($items,$headers); } @@ -328,16 +389,16 @@ class SermondistributorModelSeries_list extends ListModel public function getExImPortHeaders() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getDbo(); // get the columns $columns = $db->getTableColumns("#__sermondistributor_series"); - if (SermondistributorHelper::checkArray($columns)) + if (UtilitiesArrayHelper::check($columns)) { // remove the headers you don't import/export. unset($columns['asset_id']); unset($columns['checked_out']); unset($columns['checked_out_time']); - $headers = new stdClass(); + $headers = new \stdClass(); foreach ($columns as $column => $type) { $headers->{$column} = $column; @@ -346,12 +407,12 @@ class SermondistributorModelSeries_list extends ListModel } return false; } - + /** * Method to get a store id based on model configuration state. * * @return string A store id. - * + * @since 1.6 */ protected function getStoreId($id = '') { @@ -361,13 +422,13 @@ class SermondistributorModelSeries_list extends ListModel $id .= ':' . $this->getState('filter.published'); // Check if the value is an array $_access = $this->getState('filter.access'); - if (SermondistributorHelper::checkArray($_access)) + if (UtilitiesArrayHelper::check($_access)) { $id .= ':' . implode(':', $_access); } // Check if this is only an number or string elseif (is_numeric($_access) - || SermondistributorHelper::checkString($_access)) + || StringHelper::check($_access)) { $id .= ':' . $_access; } @@ -379,22 +440,65 @@ class SermondistributorModelSeries_list extends ListModel return parent::getStoreId($id); } + /** + * Method to get the styles that have to be included on the view + * + * @return array styles files + * @since 4.3 + */ + public function getStyles(): array + { + return $this->styles; + } + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * Build an SQL query to checkin all items left checked out longer then a set time. * - * @return a bool - * + * @return bool + * @since 3.2.0 */ - protected function checkInNow() + protected function checkInNow(): bool { // Get set check in time - $time = JComponentHelper::getParams('com_sermondistributor')->get('check_in'); + $time = ComponentHelper::getParams('com_sermondistributor')->get('check_in'); if ($time) { - // Get a db connection. - $db = JFactory::getDbo(); + $db = $this->getDatabase(); // Reset query. $query = $db->getQuery(true); $query->select('*'); @@ -406,7 +510,7 @@ class SermondistributorModelSeries_list extends ListModel if ($db->getNumRows()) { // Get Yesterdays date. - $date = JFactory::getDate()->modify($time)->toSql(); + $date = Factory::getDate()->modify($time)->toSql(); // Reset query. $query = $db->getQuery(true); @@ -427,7 +531,7 @@ class SermondistributorModelSeries_list extends ListModel $db->setQuery($query); - $db->execute(); + return $db->execute(); } } diff --git a/admin/models/sermon.php b/admin/src/Model/SermonModel.php similarity index 80% rename from admin/models/sermon.php rename to admin/src/Model/SermonModel.php index e65876b5..f52f17bb 100644 --- a/admin/models/sermon.php +++ b/admin/src/Model/SermonModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage sermon.php + @subpackage SermonModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,24 +21,48 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Form\Form; +use Joomla\CMS\Filter\InputFilter; +use Joomla\CMS\Filter\OutputFilter; use Joomla\CMS\MVC\Model\AdminModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Table\Table; +use Joomla\CMS\UCM\UCMType; +use Joomla\CMS\Versioning\VersionableModelTrait; +use Joomla\CMS\User\User; use Joomla\Registry\Registry; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper as UtilitiesStringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermondistributor Sermon Admin Model + * + * @since 1.6 */ -class SermondistributorModelSermon extends AdminModel +class SermonModel extends AdminModel { + use VersionableModelTrait; + /** * The tab layout fields array. * - * @var array + * @var array + * @since 3.0.0 */ protected $tabLayoutFields = array( 'details' => array( @@ -82,7 +106,29 @@ class SermondistributorModelSermon extends AdminModel ); /** - * @var string The prefix to use with controller messages. + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/sermon.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js', + 'media/com_sermondistributor/js/sermon.js' + ]; + + /** + * @var string The prefix to use with controller messages. * @since 1.6 */ protected $text_prefix = 'COM_SERMONDISTRIBUTOR'; @@ -102,25 +148,22 @@ class SermondistributorModelSermon extends AdminModel * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * - * @return JTable A database object - * - * @since 1.6 + * @return Table A database object + * @since 3.0 + * @throws \Exception */ - public function getTable($type = 'sermon', $prefix = 'SermondistributorTable', $config = array()) + public function getTable($type = 'sermon', $prefix = 'Administrator', $config = []) { - // add table path for when model gets used from other component - $this->addTablePath(JPATH_ADMINISTRATOR . '/components/com_sermondistributor/tables'); // get instance of the table - return JTable::getInstance($type, $prefix, $config); + return parent::getTable($type, $prefix, $config); } - + /** * 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) @@ -158,7 +201,7 @@ class SermondistributorModelSermon extends AdminModel if (!empty($item->id)) { // Get Tag IDs. - $item->tags = new JHelperTags; + $item->tags = new TagsHelper; $item->tags->getTagIds($item->id, 'com_sermondistributor.sermon'); } } @@ -175,9 +218,9 @@ class SermondistributorModelSermon extends AdminModel public function getVwbstastics() { // Get the user object. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -222,7 +265,7 @@ class SermondistributorModelSermon extends AdminModel { $query->where('a.access = ' . (int) $_access); } - elseif (SermondistributorHelper::checkArray($_access)) + elseif (UtilitiesArrayHelper::check($_access)) { // Secure the array for the query $_access = ArrayHelper::toInteger($_access); @@ -248,12 +291,12 @@ class SermondistributorModelSermon extends AdminModel $items = $db->loadObjectList(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -279,11 +322,10 @@ class SermondistributorModelSermon extends AdminModel * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @param array $options Optional array of options for the form creation. * - * @return mixed A JForm object on success, false on failure - * + * @return Form|boolean A Form object on success, false on failure * @since 1.6 */ - public function getForm($data = array(), $loadData = true, $options = array('control' => 'jform')) + public function getForm($data = [], $loadData = true, $options = ['control' => 'jform']) { // set load data option $options['load_data'] = $loadData; @@ -310,7 +352,7 @@ class SermondistributorModelSermon extends AdminModel return false; } - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first. if ($jinput->get('a_id')) @@ -323,7 +365,7 @@ class SermondistributorModelSermon extends AdminModel $id = $jinput->get('id', 0, 'INT'); } - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Check for existing item. // Modify the form based on Edit State access controls. @@ -384,38 +426,66 @@ class SermondistributorModelSermon extends AdminModel } /** - * Method to get the script that have to be included on the form + * Method to get the styles that have to be included on the view * - * @return string script files + * @return array styles files + * @since 4.3 */ - public function getScript() + public function getStyles(): array { - return 'media/com_sermondistributor/js/sermon.js'; + return $this->styles; } - + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * 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 set in the component. - * * @since 1.6 */ protected function canDelete($record) { - if (!empty($record->id)) + if (empty($record->id) || ($record->published != -2)) { - if ($record->published != -2) - { - return; - } - - $user = JFactory::getUser(); - // The record has been set. Check the record permissions. - return $user->authorise('sermon.delete', 'com_sermondistributor.sermon.' . (int) $record->id); + return false; } - return false; + + // The record has been set. Check the record permissions. + return $this->getCurrentUser()->authorise('sermon.delete', 'com_sermondistributor.sermon.' . (int) $record->id); } /** @@ -424,13 +494,12 @@ class SermondistributorModelSermon extends AdminModel * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. - * * @since 1.6 */ protected function canEditState($record) { - $user = JFactory::getUser(); - $recordId = (!empty($record->id)) ? $record->id : 0; + $user = $this->getCurrentUser(); + $recordId = $record->id ?? 0; if ($recordId) { @@ -441,51 +510,50 @@ class SermondistributorModelSermon extends AdminModel return false; } } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('sermon.edit.state', 'com_sermondistributor'); } - + /** * Method override to check if you can edit an existing record. * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key. + * @param array $data An array of input data. + * @param string $key The name of the key for the primary key. * - * @return boolean - * @since 2.5 + * @return boolean + * @since 2.5 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // Check specific edit permission then general edit permission. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); return $user->authorise('sermon.edit', 'com_sermondistributor.sermon.'. ((int) isset($data[$key]) ? $data[$key] : 0)) or $user->authorise('sermon.edit', 'com_sermondistributor'); } - + /** * Prepare and sanitise the table data prior to saving. * - * @param JTable $table A JTable object. + * @param Table $table A Table object. * * @return void - * * @since 1.6 */ protected function prepareTable($table) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); - + $date = Factory::getDate(); + $user = $this->getCurrentUser(); + if (isset($table->name)) { - $table->name = htmlspecialchars_decode($table->name, ENT_QUOTES); + $table->name = \htmlspecialchars_decode($table->name, ENT_QUOTES); } - + if (isset($table->alias) && empty($table->alias)) { $table->generateAlias(); } - + if (empty($table->id)) { $table->created = $date->toSql(); @@ -497,7 +565,7 @@ class SermondistributorModelSermon extends AdminModel // Set ordering to the last item if not set if (empty($table->ordering)) { - $db = JFactory::getDbo(); + $db = $this->getDatabase(); $query = $db->getQuery(true) ->select('MAX(ordering)') ->from($db->quoteName('#__sermondistributor_sermon')); @@ -512,7 +580,7 @@ class SermondistributorModelSermon extends AdminModel $table->modified = $date->toSql(); $table->modified_by = $user->id; } - + if (!empty($table->id)) { // Increment the items version number. @@ -524,21 +592,21 @@ class SermondistributorModelSermon extends AdminModel * Method to get the data that should be injected in the form. * * @return mixed The data for the form. - * * @since 1.6 */ - protected function loadFormData() + protected function loadFormData() { // Check the session for previously entered form data. - $data = JFactory::getApplication()->getUserState('com_sermondistributor.edit.sermon.data', array()); + $data = Factory::getApplication()->getUserState('com_sermondistributor.edit.sermon.data', []); if (empty($data)) { $data = $this->getItem(); - // run the perprocess of the data - $this->preprocessData('com_sermondistributor.sermon', $data); } + // run the perprocess of the data + $this->preprocessData('com_sermondistributor.sermon', $data); + return $data; } @@ -558,7 +626,7 @@ class SermondistributorModelSermon extends AdminModel public function validate($form, $data, $group = null) { // check if the not_required field is set - if (isset($data['not_required']) && SermondistributorHelper::checkString($data['not_required'])) + if (isset($data['not_required']) && UtilitiesStringHelper::check($data['not_required'])) { $requiredFields = (array) explode(',',(string) $data['not_required']); $requiredFields = array_unique($requiredFields); @@ -566,7 +634,7 @@ class SermondistributorModelSermon extends AdminModel foreach ($requiredFields as $requiredField) { // make sure there is a string value - if (SermondistributorHelper::checkString($requiredField)) + if (UtilitiesStringHelper::check($requiredField)) { // change to false $form->setFieldAttribute($requiredField, 'required', 'false'); @@ -589,14 +657,13 @@ class SermondistributorModelSermon extends AdminModel { return false; } - + /** * Method to delete one or more records. * * @param array &$pks An array of record primary keys. * - * @return boolean True if successful, false if an error occurs. - * + * @return boolean True if successful, false if an error occurs * @since 12.2 */ public function delete(&$pks) @@ -605,7 +672,7 @@ class SermondistributorModelSermon extends AdminModel { return false; } - + return true; } @@ -616,7 +683,6 @@ class SermondistributorModelSermon extends AdminModel * @param integer $value The value of the published state. * * @return boolean True on success. - * * @since 12.2 */ public function publish(&$pks, $value = 1) @@ -625,10 +691,10 @@ class SermondistributorModelSermon extends AdminModel { return false; } - + return true; - } - + } + /** * Method to perform batch operations on an item or a set of items. * @@ -637,7 +703,6 @@ class SermondistributorModelSermon extends AdminModel * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. - * * @since 12.2 */ public function batch($commands, $pks, $contexts) @@ -654,30 +719,30 @@ class SermondistributorModelSermon extends AdminModel if (empty($pks)) { - $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); + $this->setError(Text::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; // Set some needed variables. - $this->user = JFactory::getUser(); - $this->table = $this->getTable(); - $this->tableClassName = get_class($this->table); - $this->contentType = new JUcmType; - $this->type = $this->contentType->getTypeByTable($this->tableClassName); - $this->canDo = SermondistributorHelper::getActions('sermon'); - $this->batchSet = true; + $this->user ??= $this->getCurrentUser(); + $this->table = $this->getTable(); + $this->tableClassName = get_class($this->table); + $this->contentType = new UCMType; + $this->type = $this->contentType->getTypeByTable($this->tableClassName); + $this->canDo = SermondistributorHelper::getActions('sermon'); + $this->batchSet = true; if (!$this->canDo->get('core.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } - + if ($this->type == false) { - $type = new JUcmType; + $type = new UCMType; $this->type = $type->getTypeByAlias($this->typeAlias); } @@ -714,8 +779,7 @@ class SermondistributorModelSermon extends AdminModel if (!$done) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); - + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } @@ -741,7 +805,7 @@ class SermondistributorModelSermon extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('sermon'); @@ -782,7 +846,7 @@ class SermondistributorModelSermon extends AdminModel unset($values['category']); } - $newIds = array(); + $newIds = []; // Parent exists so let's proceed while (!empty($pks)) { @@ -795,7 +859,7 @@ class SermondistributorModelSermon extends AdminModel if (!$this->user->authorise('sermon.edit', $contexts[$pk])) { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } @@ -811,7 +875,7 @@ class SermondistributorModelSermon extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } @@ -826,7 +890,7 @@ class SermondistributorModelSermon extends AdminModel } // insert all set values - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -838,7 +902,7 @@ class SermondistributorModelSermon extends AdminModel } // update all unique fields - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -902,7 +966,7 @@ class SermondistributorModelSermon extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('sermon'); @@ -910,7 +974,7 @@ class SermondistributorModelSermon extends AdminModel if (!$this->canDo->get('sermon.edit') && !$this->canDo->get('sermon.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -943,7 +1007,7 @@ class SermondistributorModelSermon extends AdminModel { if (!$this->user->authorise('sermon.edit', $contexts[$pk])) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -959,13 +1023,13 @@ class SermondistributorModelSermon extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // insert all set values. - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -1009,27 +1073,26 @@ class SermondistributorModelSermon extends AdminModel return true; } - + /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. - * * @since 1.6 */ public function save($data) { - $input = JFactory::getApplication()->input; - $filter = JFilterInput::getInstance(); - + $input = Factory::getApplication()->getInput(); + $filter = InputFilter::getInstance(); + // set the metadata to the Item Data if (isset($data['metadata']) && isset($data['metadata']['author'])) { $data['metadata']['author'] = $filter->clean($data['metadata']['author'], 'TRIM'); - - $metadata = new JRegistry; + + $metadata = new Registry; $metadata->loadArray($data['metadata']); $data['metadata'] = (string) $metadata; } @@ -1045,11 +1108,11 @@ class SermondistributorModelSermon extends AdminModel { $data['manual_files'] = (string) json_encode($data['manual_files']); } - + // Set the Params Items to data if (isset($data['params']) && is_array($data['params'])) { - $params = new JRegistry; + $params = new Registry; $params->loadArray($data['params']); $data['params'] = (string) $params; } @@ -1082,20 +1145,20 @@ class SermondistributorModelSermon extends AdminModel { if ($data['alias'] == null || empty($data['alias'])) { - if (JFactory::getConfig()->get('unicodeslugs') == 1) + if (Factory::getConfig()->get('unicodeslugs') == 1) { - $data['alias'] = JFilterOutput::stringURLUnicodeSlug($data['name']); + $data['alias'] = OutputFilter::stringURLUnicodeSlug($data['name']); } else { - $data['alias'] = JFilterOutput::stringURLSafe($data['name']); + $data['alias'] = OutputFilter::stringURLSafe($data['name']); } - $table = JTable::getInstance('sermon', 'sermondistributorTable'); + $table = clone $this->getTable(); - if ($table->load(array('alias' => $data['alias'], 'catid' => $data['catid'])) && ($table->id != $data['id'] || $data['id'] == 0)) + if ($table->load(['alias' => $data['alias'], 'catid' => $data['catid']]) && ($table->id != $data['id'] || $data['id'] == 0)) { - $msg = JText::_('COM_SERMONDISTRIBUTOR_SERMON_SAVE_WARNING'); + $msg = Text::_('COM_SERMONDISTRIBUTOR_SERMON_SAVE_WARNING'); } list($name, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['name']); @@ -1103,7 +1166,7 @@ class SermondistributorModelSermon extends AdminModel if (isset($msg)) { - JFactory::getApplication()->enqueueMessage($msg, 'warning'); + Factory::getApplication()->enqueueMessage($msg, 'warning'); } } } @@ -1113,7 +1176,7 @@ class SermondistributorModelSermon extends AdminModel { // Automatic handling of other unique fields $uniqueFields = $this->getUniqueFields(); - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -1121,14 +1184,14 @@ class SermondistributorModelSermon extends AdminModel } } } - + if (parent::save($data)) { return true; } return false; } - + /** * Method to generate a unique value. * @@ -1136,16 +1199,14 @@ class SermondistributorModelSermon extends AdminModel * @param string $value data. * * @return string New value. - * * @since 3.0 */ - protected function generateUnique($field,$value) + protected function generateUnique($field, $value) { - // set field value unique $table = $this->getTable(); - while ($table->load(array($field => $value))) + while ($table->load([$field => $value])) { $value = StringHelper::increment($value); } @@ -1168,10 +1229,10 @@ class SermondistributorModelSermon extends AdminModel // Alter the title/s & alias $table = $this->getTable(); - while ($table->load(array('alias' => $alias))) + while ($table->load(['alias' => $alias])) { // Check if this is an array of titles - if (SermondistributorHelper::checkArray($title)) + if (UtilitiesArrayHelper::check($title)) { foreach($title as $nr => &$_title) { @@ -1186,7 +1247,7 @@ class SermondistributorModelSermon extends AdminModel $alias = StringHelper::increment($alias, 'dash'); } // Check if this is an array of titles - if (SermondistributorHelper::checkArray($title)) + if (UtilitiesArrayHelper::check($title)) { $title[] = $alias; return $title; diff --git a/admin/src/Model/SermondistributorModel.php b/admin/src/Model/SermondistributorModel.php new file mode 100644 index 00000000..ab59be37 --- /dev/null +++ b/admin/src/Model/SermondistributorModel.php @@ -0,0 +1,438 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor List Model + * + * @since 1.6 + */ +class SermondistributorModel extends ListModel +{ + public function getIcons() + { + // load user for access menus + $user = Factory::getApplication()->getIdentity(); + // reset icon array + $icons = []; + // view groups array + $viewGroups = array( + 'main' => array('png.preacher.add', 'png.preachers', 'png.sermon.add', 'png.sermons', 'png.sermons.catid_qpo0O0oqp_com_sermondistributor_po0O0oq_sermon', 'png.series.add', 'png.series_list', 'png.statistics', 'png.external_source.add', 'png.external_sources', 'png.manual_updater', 'png.local_listings', 'png.help_documents') + ); + // view access array + $viewAccess = [ + 'manual_updater.access' => 'manual_updater.access', + 'manual_updater.submenu' => 'manual_updater.submenu', + 'manual_updater.dashboard_list' => 'manual_updater.dashboard_list', + 'preacher.create' => 'preacher.create', + 'preachers.access' => 'preacher.access', + 'preacher.access' => 'preacher.access', + 'preachers.submenu' => 'preacher.submenu', + 'preachers.dashboard_list' => 'preacher.dashboard_list', + 'preacher.dashboard_add' => 'preacher.dashboard_add', + 'sermon.create' => 'sermon.create', + 'sermons.access' => 'sermon.access', + 'sermon.access' => 'sermon.access', + 'sermons.submenu' => 'sermon.submenu', + 'sermons.dashboard_list' => 'sermon.dashboard_list', + 'sermon.dashboard_add' => 'sermon.dashboard_add', + 'series.create' => 'series.create', + 'series_list.access' => 'series.access', + 'series.access' => 'series.access', + 'series_list.submenu' => 'series.submenu', + 'series_list.dashboard_list' => 'series.dashboard_list', + 'series.dashboard_add' => 'series.dashboard_add', + 'statistic.create' => 'statistic.create', + 'statistics.access' => 'statistic.access', + 'statistic.access' => 'statistic.access', + 'statistics.submenu' => 'statistic.submenu', + 'statistics.dashboard_list' => 'statistic.dashboard_list', + 'external_source.create' => 'external_source.create', + 'external_sources.access' => 'external_source.access', + 'external_source.access' => 'external_source.access', + 'external_sources.submenu' => 'external_source.submenu', + 'external_sources.dashboard_list' => 'external_source.dashboard_list', + 'external_source.dashboard_add' => 'external_source.dashboard_add', + 'local_listing.create' => 'local_listing.create', + 'local_listings.access' => 'local_listing.access', + 'local_listing.access' => 'local_listing.access', + 'local_listings.submenu' => 'local_listing.submenu', + 'local_listings.dashboard_list' => 'local_listing.dashboard_list', + 'help_document.create' => 'help_document.create', + 'help_documents.access' => 'help_document.access', + 'help_document.access' => 'help_document.access', + 'help_documents.submenu' => 'help_document.submenu', + 'help_documents.dashboard_list' => 'help_document.dashboard_list', + ]; + // loop over the $views + foreach($viewGroups as $group => $views) + { + $i = 0; + if (UtilitiesArrayHelper::check($views)) + { + foreach($views as $view) + { + $add = false; + // external views (links) + if (strpos($view,'||') !== false) + { + $dwd = explode('||', $view); + if (count($dwd) == 3) + { + list($type, $name, $url) = $dwd; + $viewName = $name; + $alt = $name; + $url = $url; + $image = $name . '.' . $type; + $name = 'COM_SERMONDISTRIBUTOR_DASHBOARD_' . StringHelper::safe($name,'U'); + } + } + // internal views + elseif (strpos($view,'.') !== false) + { + $dwd = explode('.', $view); + if (count($dwd) == 3) + { + list($type, $name, $action) = $dwd; + } + elseif (count($dwd) == 2) + { + list($type, $name) = $dwd; + $action = false; + } + if ($action) + { + $viewName = $name; + switch($action) + { + case 'add': + $url = 'index.php?option=com_sermondistributor&view=' . $name . '&layout=edit'; + $image = $name . '_' . $action. '.' . $type; + $alt = $name . ' ' . $action; + $name = 'COM_SERMONDISTRIBUTOR_DASHBOARD_'.StringHelper::safe($name,'U').'_ADD'; + $add = true; + break; + default: + // check for new convention (more stable) + if (strpos($action, '_qpo0O0oqp_') !== false) + { + list($action, $extension) = (array) explode('_qpo0O0oqp_', $action); + $extension = str_replace('_po0O0oq_', '.', $extension); + } + else + { + $extension = 'com_sermondistributor.' . $name; + } + $url = 'index.php?option=com_categories&view=categories&extension=' . $extension; + $image = $name . '_' . $action . '.' . $type; + $alt = $viewName . ' ' . $action; + $name = 'COM_SERMONDISTRIBUTOR_DASHBOARD_' . StringHelper::safe($name,'U') . '_' . StringHelper::safe($action,'U'); + break; + } + } + else + { + $viewName = $name; + $alt = $name; + $url = 'index.php?option=com_sermondistributor&view=' . $name; + $image = $name . '.' . $type; + $name = 'COM_SERMONDISTRIBUTOR_DASHBOARD_' . StringHelper::safe($name,'U'); + $hover = false; + } + } + else + { + $viewName = $view; + $alt = $view; + $url = 'index.php?option=com_sermondistributor&view=' . $view; + $image = $view . '.png'; + $name = ucwords($view).'

'; + $hover = false; + } + // first make sure the view access is set + if (UtilitiesArrayHelper::check($viewAccess)) + { + // setup some defaults + $dashboard_add = false; + $dashboard_list = false; + $accessTo = ''; + $accessAdd = ''; + // access checking start + $accessCreate = (isset($viewAccess[$viewName.'.create'])) ? StringHelper::check($viewAccess[$viewName.'.create']):false; + $accessAccess = (isset($viewAccess[$viewName.'.access'])) ? StringHelper::check($viewAccess[$viewName.'.access']):false; + // set main controllers + $accessDashboard_add = (isset($viewAccess[$viewName.'.dashboard_add'])) ? StringHelper::check($viewAccess[$viewName.'.dashboard_add']):false; + $accessDashboard_list = (isset($viewAccess[$viewName.'.dashboard_list'])) ? StringHelper::check($viewAccess[$viewName.'.dashboard_list']):false; + // check for adding access + if ($add && $accessCreate) + { + $accessAdd = $viewAccess[$viewName.'.create']; + } + elseif ($add) + { + $accessAdd = 'core.create'; + } + // check if access to view is set + if ($accessAccess) + { + $accessTo = $viewAccess[$viewName.'.access']; + } + // set main access controllers + if ($accessDashboard_add) + { + $dashboard_add = $user->authorise($viewAccess[$viewName.'.dashboard_add'], 'com_sermondistributor'); + } + if ($accessDashboard_list) + { + $dashboard_list = $user->authorise($viewAccess[$viewName.'.dashboard_list'], 'com_sermondistributor'); + } + if (StringHelper::check($accessAdd) && StringHelper::check($accessTo)) + { + // check access + if($user->authorise($accessAdd, 'com_sermondistributor') && $user->authorise($accessTo, 'com_sermondistributor') && $dashboard_add) + { + $icons[$group][$i] = new \StdClass; + $icons[$group][$i]->url = $url; + $icons[$group][$i]->name = $name; + $icons[$group][$i]->image = $image; + $icons[$group][$i]->alt = $alt; + } + } + elseif (StringHelper::check($accessTo)) + { + // check access + if($user->authorise($accessTo, 'com_sermondistributor') && $dashboard_list) + { + $icons[$group][$i] = new \StdClass; + $icons[$group][$i]->url = $url; + $icons[$group][$i]->name = $name; + $icons[$group][$i]->image = $image; + $icons[$group][$i]->alt = $alt; + } + } + elseif (StringHelper::check($accessAdd)) + { + // check access + if($user->authorise($accessAdd, 'com_sermondistributor') && $dashboard_add) + { + $icons[$group][$i] = new \StdClass; + $icons[$group][$i]->url = $url; + $icons[$group][$i]->name = $name; + $icons[$group][$i]->image = $image; + $icons[$group][$i]->alt = $alt; + } + } + else + { + $icons[$group][$i] = new \StdClass; + $icons[$group][$i]->url = $url; + $icons[$group][$i]->name = $name; + $icons[$group][$i]->image = $image; + $icons[$group][$i]->alt = $alt; + } + } + else + { + $icons[$group][$i] = new \StdClass; + $icons[$group][$i]->url = $url; + $icons[$group][$i]->name = $name; + $icons[$group][$i]->image = $image; + $icons[$group][$i]->alt = $alt; + } + $i++; + } + } + else + { + $icons[$group][$i] = false; + } + } + return $icons; + } + + + public function getWiki() + { + $document = Factory::getDocument(); + $document->addScriptDeclaration(' + var gewiki = "https://raw.githubusercontent.com/wiki/Llewellynvdm/Joomla-Sermon-Distributor/Home.md"; + document.addEventListener("DOMContentLoaded", function () { + fetch(gewiki) + .then(response => { + if (!response.ok) { + throw new Error("Network response was not ok"); + } + return response.text(); + }) + .then(wiki => { + document.getElementById("wiki-md").innerHTML = marked.parse(wiki); + }) + .catch(error => { + console.error("There has been a problem with your fetch operation:", error); + document.getElementById("wiki-md").innerHTML = "'.Text::_('COM_SERMONDISTRIBUTOR_PLEASE_CHECK_AGAIN_LATTER').'"; + }); + });'); + + return '
'.Text::_('COM_SERMONDISTRIBUTOR_THE_WIKI_IS_LOADING').'..
'; + } + + + + public function getNoticeboard() + { + // get the document to load the scripts + $document = Factory::getDocument(); + Html::_('script', "media/com_sermondistributor/js/marked.js", ['version' => 'auto']); + $document->addScriptDeclaration(' + var token = "' . Session::getFormToken() . '"; + var noticeboard = "https://vdm.bz/sermondistributor-noticeboard-md"; + document.addEventListener("DOMContentLoaded", function() { + fetch(noticeboard) + .then(response => { + if (!response.ok) { + throw new Error("Network response was not ok"); + } + return response.text(); + }) + .then(board => { + if (board.length > 5) { + document.getElementById("noticeboard-md").innerHTML = marked.parse(board); + getIS(1, board) + .then(result => { + if (result) { + document.querySelectorAll("#cpanel_tabTabs a").forEach(link => { + if (link.href.includes("#vast_development_method") || link.href.includes("#notice_board")) { + var textVDM = link.textContent; + link.innerHTML = "1 " + textVDM; + link.id = "vdm-new-notice"; + document.getElementById("vdm-new-notice").addEventListener("click", () => { + getIS(2, board) + .then(result => { + if (result) { + document.querySelectorAll(".vdm-new-notice").forEach(element => { + element.style.opacity = 0; + }); + } + }); + }); + } + }); + } + }); + } else { + document.getElementById("noticeboard-md").innerHTML = "'.Text::_('COM_SERMONDISTRIBUTOR_ALL_IS_GOOD_PLEASE_CHECK_AGAIN_LATER').'."; + } + }) + .catch(error => { + console.error("There was an error!", error); + document.getElementById("noticeboard-md").innerHTML = "'.Text::_('COM_SERMONDISTRIBUTOR_ALL_IS_GOOD_PLEASE_CHECK_AGAIN_LATER').'."; + }); + }); + + // to check is READ/NEW + function getIS(type, notice) { + let getUrl = ""; + if (type === 1) { + getUrl = "index.php?option=com_sermondistributor&task=ajax.isNew&format=json&raw=true"; + } else if (type === 2) { + getUrl = "index.php?option=com_sermondistributor&task=ajax.isRead&format=json&raw=true"; + } + let request = new URLSearchParams(); + if (token.length > 0 && notice.length) { + request.append(token, "1"); + request.append("notice", notice); + } + return fetch(getUrl, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" + }, + body: request + }).then(response => response.json()); + } + +document.addEventListener("DOMContentLoaded", function() { + document.querySelectorAll(".loading-dots").forEach(function(loading_dots) { + let x = 0; + let intervalId = setInterval(function() { + if (!loading_dots.classList.contains("loading-dots")) { + clearInterval(intervalId); + return; + } + let dots = ".".repeat(x % 8); + loading_dots.textContent = dots; + x++; + }, 500); + }); +});'); + + return '
'.Text::_('COM_SERMONDISTRIBUTOR_THE_NOTICE_BOARD_IS_LOADING').'..
'; + } + + public function getReadme() + { + $document = Factory::getDocument(); + $document->addScriptDeclaration(' + var getreadme = "'. Uri::root() . 'administrator/components/com_sermondistributor/README.txt"; + document.addEventListener("DOMContentLoaded", function () { + fetch(getreadme) + .then(response => { + if (!response.ok) { + throw new Error("Network response was not ok"); + } + return response.text(); + }) + .then(readme => { + document.getElementById("readme-md").innerHTML = marked.parse(readme); + }) + .catch(error => { + console.error("There has been a problem with your fetch operation:", error); + document.getElementById("readme-md").innerHTML = "'.Text::_('COM_SERMONDISTRIBUTOR_PLEASE_CHECK_AGAIN_LATER').'."; + }); + });'); + + return '
'.Text::_('COM_SERMONDISTRIBUTOR_THE_README_IS_LOADING').'..
'; + } +} diff --git a/admin/models/sermons.php b/admin/src/Model/SermonsModel.php similarity index 79% rename from admin/models/sermons.php rename to admin/src/Model/SermonsModel.php index 06b6f70c..cae7cd31 100644 --- a/admin/models/sermons.php +++ b/admin/src/Model/SermonsModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage sermons.php + @subpackage SermonsModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,22 +21,77 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Sermons List Model + * + * @since 1.6 */ -class SermondistributorModelSermons extends ListModel +class SermonsModel extends ListModel { - public function __construct($config = array()) + /** + * The application object. + * + * @var CMSApplicationInterface The application instance. + * @since 3.2.0 + */ + protected CMSApplicationInterface $app; + + /** + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/sermons.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js' + ]; + + /** + * Constructor + * + * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). + * @param ?MVCFactoryInterface $factory The factory. + * + * @since 1.6 + * @throws \Exception + */ + public function __construct($config = [], MVCFactoryInterface $factory = null) { if (empty($config['filter_fields'])) - { + { $config['filter_fields'] = array( 'a.id','id', 'a.published','published', @@ -56,7 +111,9 @@ class SermondistributorModelSermons extends ListModel ); } - parent::__construct($config); + parent::__construct($config, $factory); + + $this->app ??= Factory::getApplication(); } /** @@ -68,11 +125,11 @@ class SermondistributorModelSermons extends ListModel * @param string $direction An optional direction (asc|desc). * * @return void - * + * @since 1.7.0 */ protected function populateState($ordering = null, $direction = null) { - $app = JFactory::getApplication(); + $app = $this->app; // Adjust the context to support modal layouts. if ($layout = $app->input->get('layout')) @@ -163,11 +220,12 @@ class SermondistributorModelSermons extends ListModel // List state information. parent::populateState($ordering, $direction); } - + /** * Method to get an array of data items. * * @return mixed An array of data items on success, false on failure. + * @since 1.6 */ public function getItems() { @@ -178,12 +236,12 @@ class SermondistributorModelSermons extends ListModel $items = parent::getItems(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -196,7 +254,7 @@ class SermondistributorModelSermons extends ListModel } // Add the tags - $item->tags = new JHelperTags; + $item->tags = new TagsHelper; $item->tags->getTagIds( $item->id, 'com_sermondistributor.sermon' ); @@ -216,7 +274,7 @@ class SermondistributorModelSermons extends ListModel } // set selection value to a translatable value - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -227,7 +285,7 @@ class SermondistributorModelSermons extends ListModel } } - + // return items return $items; } @@ -235,7 +293,7 @@ class SermondistributorModelSermons extends ListModel /** * Method to convert selection values to translatable string. * - * @return translatable string + * @return string The translatable string. */ public function selectionTranslation($value,$name) { @@ -247,7 +305,7 @@ class SermondistributorModelSermons extends ListModel 2 => 'COM_SERMONDISTRIBUTOR_SERMON_DIRECT' ); // Now check if value is found in this array - if (isset($link_typeArray[$value]) && SermondistributorHelper::checkString($link_typeArray[$value])) + if (isset($link_typeArray[$value]) && StringHelper::check($link_typeArray[$value])) { return $link_typeArray[$value]; } @@ -262,25 +320,26 @@ class SermondistributorModelSermons extends ListModel 3 => 'COM_SERMONDISTRIBUTOR_SERMON_URL' ); // Now check if value is found in this array - if (isset($sourceArray[$value]) && SermondistributorHelper::checkString($sourceArray[$value])) + if (isset($sourceArray[$value]) && StringHelper::check($sourceArray[$value])) { return $sourceArray[$value]; } } return $value; } - + /** * Method to build an SQL query to load the list data. * - * @return string An SQL query + * @return string An SQL query + * @since 1.6 */ protected function getListQuery() { // Get the user object. - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -319,7 +378,7 @@ class SermondistributorModelSermons extends ListModel { $query->where('a.access = ' . (int) $_access); } - elseif (SermondistributorHelper::checkArray($_access)) + elseif (UtilitiesArrayHelper::check($_access)) { // Secure the array for the query $_access = ArrayHelper::toInteger($_access); @@ -360,11 +419,11 @@ class SermondistributorModelSermons extends ListModel $query->where('a.preacher = ' . (int) $_preacher); } } - elseif (SermondistributorHelper::checkString($_preacher)) + elseif (StringHelper::check($_preacher)) { $query->where('a.preacher = ' . $db->quote($db->escape($_preacher))); } - elseif (SermondistributorHelper::checkArray($_preacher)) + elseif (UtilitiesArrayHelper::check($_preacher)) { // Secure the array for the query $_preacher = array_map( function ($val) use(&$db) { @@ -379,7 +438,7 @@ class SermondistributorModelSermons extends ListModel return (int) $val; } } - elseif (SermondistributorHelper::checkString($val)) + elseif (StringHelper::check($val)) { return $db->quote($db->escape($val)); } @@ -400,11 +459,11 @@ class SermondistributorModelSermons extends ListModel $query->where('a.series = ' . (int) $_series); } } - elseif (SermondistributorHelper::checkString($_series)) + elseif (StringHelper::check($_series)) { $query->where('a.series = ' . $db->quote($db->escape($_series))); } - elseif (SermondistributorHelper::checkArray($_series)) + elseif (UtilitiesArrayHelper::check($_series)) { // Secure the array for the query $_series = array_map( function ($val) use(&$db) { @@ -419,7 +478,7 @@ class SermondistributorModelSermons extends ListModel return (int) $val; } } - elseif (SermondistributorHelper::checkString($val)) + elseif (StringHelper::check($val)) { return $db->quote($db->escape($val)); } @@ -440,7 +499,7 @@ class SermondistributorModelSermons extends ListModel $query->where('a.link_type = ' . (int) $_link_type); } } - elseif (SermondistributorHelper::checkString($_link_type)) + elseif (StringHelper::check($_link_type)) { $query->where('a.link_type = ' . $db->quote($db->escape($_link_type))); } @@ -457,7 +516,7 @@ class SermondistributorModelSermons extends ListModel $query->where('a.source = ' . (int) $_source); } } - elseif (SermondistributorHelper::checkString($_source)) + elseif (StringHelper::check($_source)) { $query->where('a.source = ' . $db->quote($db->escape($_source))); } @@ -468,7 +527,7 @@ class SermondistributorModelSermons extends ListModel if (is_numeric($categoryId)) { - $cat_tbl = JTable::getInstance('Category', 'JTable'); + $cat_tbl = Table::getInstance('Category', 'JTable'); $cat_tbl->load($categoryId); $rgt = $cat_tbl->rgt; $lft = $cat_tbl->lft; @@ -485,10 +544,12 @@ class SermondistributorModelSermons extends ListModel // Add the list ordering clause. - $orderCol = $this->state->get('list.ordering', 'a.id'); - $orderDirn = $this->state->get('list.direction', 'desc'); + $orderCol = $this->getState('list.ordering', 'a.id'); + $orderDirn = $this->getState('list.direction', 'desc'); if ($orderCol != '') { + // Check that the order direction is valid encase we have a field called direction as part of filers. + $orderDirn = (is_string($orderDirn) && in_array(strtolower($orderDirn), ['asc', 'desc'])) ? $orderDirn : 'desc'; $query->order($db->escape($orderCol . ' ' . $orderDirn)); } @@ -506,17 +567,17 @@ class SermondistributorModelSermons extends ListModel public function getExportData($pks, $user = null) { // setup the query - if (($pks_size = SermondistributorHelper::checkArray($pks)) !== false || 'bulk' === $pks) + if (($pks_size = UtilitiesArrayHelper::check($pks)) !== false || 'bulk' === $pks) { // Set a value to know this is export method. (USE IN CUSTOM CODE TO ALTER OUTCOME) $_export = true; // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -560,7 +621,7 @@ class SermondistributorModelSermons extends ListModel $items = $db->loadObjectList(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -573,7 +634,7 @@ class SermondistributorModelSermons extends ListModel } // Add the tags - $item->tags = new JHelperTags; + $item->tags = new TagsHelper; $item->tags->getTagIds( $item->id, 'com_sermondistributor.sermon' ); @@ -597,7 +658,7 @@ class SermondistributorModelSermons extends ListModel } // Add headers to items array. $headers = $this->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { array_unshift($items,$headers); } @@ -615,16 +676,16 @@ class SermondistributorModelSermons extends ListModel public function getExImPortHeaders() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getDbo(); // get the columns $columns = $db->getTableColumns("#__sermondistributor_sermon"); - if (SermondistributorHelper::checkArray($columns)) + if (UtilitiesArrayHelper::check($columns)) { // remove the headers you don't import/export. unset($columns['asset_id']); unset($columns['checked_out']); unset($columns['checked_out_time']); - $headers = new stdClass(); + $headers = new \stdClass(); foreach ($columns as $column => $type) { $headers->{$column} = $column; @@ -633,12 +694,12 @@ class SermondistributorModelSermons extends ListModel } return false; } - + /** * Method to get a store id based on model configuration state. * * @return string A store id. - * + * @since 1.6 */ protected function getStoreId($id = '') { @@ -648,13 +709,13 @@ class SermondistributorModelSermons extends ListModel $id .= ':' . $this->getState('filter.published'); // Check if the value is an array $_access = $this->getState('filter.access'); - if (SermondistributorHelper::checkArray($_access)) + if (UtilitiesArrayHelper::check($_access)) { $id .= ':' . implode(':', $_access); } // Check if this is only an number or string elseif (is_numeric($_access) - || SermondistributorHelper::checkString($_access)) + || StringHelper::check($_access)) { $id .= ':' . $_access; } @@ -663,61 +724,61 @@ class SermondistributorModelSermons extends ListModel $id .= ':' . $this->getState('filter.modified_by'); // Check if the value is an array $_preacher = $this->getState('filter.preacher'); - if (SermondistributorHelper::checkArray($_preacher)) + if (UtilitiesArrayHelper::check($_preacher)) { $id .= ':' . implode(':', $_preacher); } // Check if this is only an number or string elseif (is_numeric($_preacher) - || SermondistributorHelper::checkString($_preacher)) + || StringHelper::check($_preacher)) { $id .= ':' . $_preacher; } // Check if the value is an array $_series = $this->getState('filter.series'); - if (SermondistributorHelper::checkArray($_series)) + if (UtilitiesArrayHelper::check($_series)) { $id .= ':' . implode(':', $_series); } // Check if this is only an number or string elseif (is_numeric($_series) - || SermondistributorHelper::checkString($_series)) + || StringHelper::check($_series)) { $id .= ':' . $_series; } // Check if the value is an array $_category = $this->getState('filter.category'); - if (SermondistributorHelper::checkArray($_category)) + if (UtilitiesArrayHelper::check($_category)) { $id .= ':' . implode(':', $_category); } // Check if this is only an number or string elseif (is_numeric($_category) - || SermondistributorHelper::checkString($_category)) + || StringHelper::check($_category)) { $id .= ':' . $_category; } // Check if the value is an array $_category_id = $this->getState('filter.category_id'); - if (SermondistributorHelper::checkArray($_category_id)) + if (UtilitiesArrayHelper::check($_category_id)) { $id .= ':' . implode(':', $_category_id); } // Check if this is only an number or string elseif (is_numeric($_category_id) - || SermondistributorHelper::checkString($_category_id)) + || StringHelper::check($_category_id)) { $id .= ':' . $_category_id; } // Check if the value is an array $_catid = $this->getState('filter.catid'); - if (SermondistributorHelper::checkArray($_catid)) + if (UtilitiesArrayHelper::check($_catid)) { $id .= ':' . implode(':', $_catid); } // Check if this is only an number or string elseif (is_numeric($_catid) - || SermondistributorHelper::checkString($_catid)) + || StringHelper::check($_catid)) { $id .= ':' . $_catid; } @@ -729,22 +790,65 @@ class SermondistributorModelSermons extends ListModel return parent::getStoreId($id); } + /** + * Method to get the styles that have to be included on the view + * + * @return array styles files + * @since 4.3 + */ + public function getStyles(): array + { + return $this->styles; + } + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * Build an SQL query to checkin all items left checked out longer then a set time. * - * @return a bool - * + * @return bool + * @since 3.2.0 */ - protected function checkInNow() + protected function checkInNow(): bool { // Get set check in time - $time = JComponentHelper::getParams('com_sermondistributor')->get('check_in'); + $time = ComponentHelper::getParams('com_sermondistributor')->get('check_in'); if ($time) { - // Get a db connection. - $db = JFactory::getDbo(); + $db = $this->getDatabase(); // Reset query. $query = $db->getQuery(true); $query->select('*'); @@ -756,7 +860,7 @@ class SermondistributorModelSermons extends ListModel if ($db->getNumRows()) { // Get Yesterdays date. - $date = JFactory::getDate()->modify($time)->toSql(); + $date = Factory::getDate()->modify($time)->toSql(); // Reset query. $query = $db->getQuery(true); @@ -777,7 +881,7 @@ class SermondistributorModelSermons extends ListModel $db->setQuery($query); - $db->execute(); + return $db->execute(); } } diff --git a/admin/models/statistic.php b/admin/src/Model/StatisticModel.php similarity index 77% rename from admin/models/statistic.php rename to admin/src/Model/StatisticModel.php index 338fc141..ffd4f69f 100644 --- a/admin/models/statistic.php +++ b/admin/src/Model/StatisticModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage statistic.php + @subpackage StatisticModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,24 +21,47 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Form\Form; +use Joomla\CMS\Filter\InputFilter; +use Joomla\CMS\Filter\OutputFilter; use Joomla\CMS\MVC\Model\AdminModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Table\Table; +use Joomla\CMS\UCM\UCMType; +use Joomla\CMS\Versioning\VersionableModelTrait; +use Joomla\CMS\User\User; use Joomla\Registry\Registry; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\StringHelper as UtilitiesStringHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermondistributor Statistic Admin Model + * + * @since 1.6 */ -class SermondistributorModelStatistic extends AdminModel +class StatisticModel extends AdminModel { + use VersionableModelTrait; + /** * The tab layout fields array. * - * @var array + * @var array + * @since 3.0.0 */ protected $tabLayoutFields = array( 'details' => array( @@ -57,7 +80,29 @@ class SermondistributorModelStatistic extends AdminModel ); /** - * @var string The prefix to use with controller messages. + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/statistic.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js', + 'media/com_sermondistributor/js/statistic.js' + ]; + + /** + * @var string The prefix to use with controller messages. * @since 1.6 */ protected $text_prefix = 'COM_SERMONDISTRIBUTOR'; @@ -77,25 +122,22 @@ class SermondistributorModelStatistic extends AdminModel * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * - * @return JTable A database object - * - * @since 1.6 + * @return Table A database object + * @since 3.0 + * @throws \Exception */ - public function getTable($type = 'statistic', $prefix = 'SermondistributorTable', $config = array()) + public function getTable($type = 'statistic', $prefix = 'Administrator', $config = []) { - // add table path for when model gets used from other component - $this->addTablePath(JPATH_ADMINISTRATOR . '/components/com_sermondistributor/tables'); // get instance of the table - return JTable::getInstance($type, $prefix, $config); + return parent::getTable($type, $prefix, $config); } - + /** * 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) @@ -129,11 +171,10 @@ class SermondistributorModelStatistic extends AdminModel * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @param array $options Optional array of options for the form creation. * - * @return mixed A JForm object on success, false on failure - * + * @return Form|boolean A Form object on success, false on failure * @since 1.6 */ - public function getForm($data = array(), $loadData = true, $options = array('control' => 'jform')) + public function getForm($data = [], $loadData = true, $options = ['control' => 'jform']) { // set load data option $options['load_data'] = $loadData; @@ -160,7 +201,7 @@ class SermondistributorModelStatistic extends AdminModel return false; } - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first. if ($jinput->get('a_id')) @@ -173,7 +214,7 @@ class SermondistributorModelStatistic extends AdminModel $id = $jinput->get('id', 0, 'INT'); } - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); // Check for existing item. // Modify the form based on Edit State access controls. @@ -234,38 +275,66 @@ class SermondistributorModelStatistic extends AdminModel } /** - * Method to get the script that have to be included on the form + * Method to get the styles that have to be included on the view * - * @return string script files + * @return array styles files + * @since 4.3 */ - public function getScript() + public function getStyles(): array { - return 'media/com_sermondistributor/js/statistic.js'; + return $this->styles; } - + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * 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 set in the component. - * * @since 1.6 */ protected function canDelete($record) { - if (!empty($record->id)) + if (empty($record->id) || ($record->published != -2)) { - if ($record->published != -2) - { - return; - } - - $user = JFactory::getUser(); - // The record has been set. Check the record permissions. - return $user->authorise('statistic.delete', 'com_sermondistributor.statistic.' . (int) $record->id); + return false; } - return false; + + // The record has been set. Check the record permissions. + return $this->getCurrentUser()->authorise('statistic.delete', 'com_sermondistributor.statistic.' . (int) $record->id); } /** @@ -274,13 +343,12 @@ class SermondistributorModelStatistic extends AdminModel * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. - * * @since 1.6 */ protected function canEditState($record) { - $user = JFactory::getUser(); - $recordId = (!empty($record->id)) ? $record->id : 0; + $user = $this->getCurrentUser(); + $recordId = $record->id ?? 0; if ($recordId) { @@ -291,51 +359,50 @@ class SermondistributorModelStatistic extends AdminModel return false; } } - // In the absense of better information, revert to the component permissions. + // In the absence of better information, revert to the component permissions. return $user->authorise('statistic.edit.state', 'com_sermondistributor'); } - + /** * Method override to check if you can edit an existing record. * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key. + * @param array $data An array of input data. + * @param string $key The name of the key for the primary key. * - * @return boolean - * @since 2.5 + * @return boolean + * @since 2.5 */ - protected function allowEdit($data = array(), $key = 'id') + protected function allowEdit($data = [], $key = 'id') { // Check specific edit permission then general edit permission. - $user = JFactory::getUser(); + $user = Factory::getApplication()->getIdentity(); return $user->authorise('statistic.edit', 'com_sermondistributor.statistic.'. ((int) isset($data[$key]) ? $data[$key] : 0)) or $user->authorise('statistic.edit', 'com_sermondistributor'); } - + /** * Prepare and sanitise the table data prior to saving. * - * @param JTable $table A JTable object. + * @param Table $table A Table object. * * @return void - * * @since 1.6 */ protected function prepareTable($table) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); - + $date = Factory::getDate(); + $user = $this->getCurrentUser(); + if (isset($table->name)) { - $table->name = htmlspecialchars_decode($table->name, ENT_QUOTES); + $table->name = \htmlspecialchars_decode($table->name, ENT_QUOTES); } - + if (isset($table->alias) && empty($table->alias)) { $table->generateAlias(); } - + if (empty($table->id)) { $table->created = $date->toSql(); @@ -347,7 +414,7 @@ class SermondistributorModelStatistic extends AdminModel // Set ordering to the last item if not set if (empty($table->ordering)) { - $db = JFactory::getDbo(); + $db = $this->getDatabase(); $query = $db->getQuery(true) ->select('MAX(ordering)') ->from($db->quoteName('#__sermondistributor_statistic')); @@ -362,7 +429,7 @@ class SermondistributorModelStatistic extends AdminModel $table->modified = $date->toSql(); $table->modified_by = $user->id; } - + if (!empty($table->id)) { // Increment the items version number. @@ -374,21 +441,21 @@ class SermondistributorModelStatistic extends AdminModel * Method to get the data that should be injected in the form. * * @return mixed The data for the form. - * * @since 1.6 */ - protected function loadFormData() + protected function loadFormData() { // Check the session for previously entered form data. - $data = JFactory::getApplication()->getUserState('com_sermondistributor.edit.statistic.data', array()); + $data = Factory::getApplication()->getUserState('com_sermondistributor.edit.statistic.data', []); if (empty($data)) { $data = $this->getItem(); - // run the perprocess of the data - $this->preprocessData('com_sermondistributor.statistic', $data); } + // run the perprocess of the data + $this->preprocessData('com_sermondistributor.statistic', $data); + return $data; } @@ -403,14 +470,13 @@ class SermondistributorModelStatistic extends AdminModel { return false; } - + /** * Method to delete one or more records. * * @param array &$pks An array of record primary keys. * - * @return boolean True if successful, false if an error occurs. - * + * @return boolean True if successful, false if an error occurs * @since 12.2 */ public function delete(&$pks) @@ -419,7 +485,7 @@ class SermondistributorModelStatistic extends AdminModel { return false; } - + return true; } @@ -430,7 +496,6 @@ class SermondistributorModelStatistic extends AdminModel * @param integer $value The value of the published state. * * @return boolean True on success. - * * @since 12.2 */ public function publish(&$pks, $value = 1) @@ -439,10 +504,10 @@ class SermondistributorModelStatistic extends AdminModel { return false; } - + return true; - } - + } + /** * Method to perform batch operations on an item or a set of items. * @@ -451,7 +516,6 @@ class SermondistributorModelStatistic extends AdminModel * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. - * * @since 12.2 */ public function batch($commands, $pks, $contexts) @@ -468,30 +532,30 @@ class SermondistributorModelStatistic extends AdminModel if (empty($pks)) { - $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); + $this->setError(Text::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; // Set some needed variables. - $this->user = JFactory::getUser(); - $this->table = $this->getTable(); - $this->tableClassName = get_class($this->table); - $this->contentType = new JUcmType; - $this->type = $this->contentType->getTypeByTable($this->tableClassName); - $this->canDo = SermondistributorHelper::getActions('statistic'); - $this->batchSet = true; + $this->user ??= $this->getCurrentUser(); + $this->table = $this->getTable(); + $this->tableClassName = get_class($this->table); + $this->contentType = new UCMType; + $this->type = $this->contentType->getTypeByTable($this->tableClassName); + $this->canDo = SermondistributorHelper::getActions('statistic'); + $this->batchSet = true; if (!$this->canDo->get('core.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } - + if ($this->type == false) { - $type = new JUcmType; + $type = new UCMType; $this->type = $type->getTypeByAlias($this->typeAlias); } @@ -528,8 +592,7 @@ class SermondistributorModelStatistic extends AdminModel if (!$done) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); - + $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } @@ -555,7 +618,7 @@ class SermondistributorModelStatistic extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('statistic'); @@ -581,7 +644,7 @@ class SermondistributorModelStatistic extends AdminModel $values['published'] = 0; } - $newIds = array(); + $newIds = []; // Parent exists so let's proceed while (!empty($pks)) { @@ -594,7 +657,7 @@ class SermondistributorModelStatistic extends AdminModel if (!$this->user->authorise('statistic.edit', $contexts[$pk])) { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } @@ -610,19 +673,19 @@ class SermondistributorModelStatistic extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // Only for strings - if (SermondistributorHelper::checkString($this->table->filename) && !is_numeric($this->table->filename)) + if (UtilitiesStringHelper::check($this->table->filename) && !is_numeric($this->table->filename)) { $this->table->filename = $this->generateUnique('filename',$this->table->filename); } // insert all set values - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -634,7 +697,7 @@ class SermondistributorModelStatistic extends AdminModel } // update all unique fields - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -698,7 +761,7 @@ class SermondistributorModelStatistic extends AdminModel if (empty($this->batchSet)) { // Set some needed variables. - $this->user = JFactory::getUser(); + $this->user = Factory::getApplication()->getIdentity(); $this->table = $this->getTable(); $this->tableClassName = get_class($this->table); $this->canDo = SermondistributorHelper::getActions('statistic'); @@ -706,7 +769,7 @@ class SermondistributorModelStatistic extends AdminModel if (!$this->canDo->get('statistic.edit') && !$this->canDo->get('statistic.batch')) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -723,7 +786,7 @@ class SermondistributorModelStatistic extends AdminModel { if (!$this->user->authorise('statistic.edit', $contexts[$pk])) { - $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); + $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } @@ -739,13 +802,13 @@ class SermondistributorModelStatistic extends AdminModel else { // Not fatal error - $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); + $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // insert all set values. - if (SermondistributorHelper::checkArray($values)) + if (UtilitiesArrayHelper::check($values)) { foreach ($values as $key => $value) { @@ -789,35 +852,34 @@ class SermondistributorModelStatistic extends AdminModel return true; } - + /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. - * * @since 1.6 */ public function save($data) { - $input = JFactory::getApplication()->input; - $filter = JFilterInput::getInstance(); - + $input = Factory::getApplication()->getInput(); + $filter = InputFilter::getInstance(); + // set the metadata to the Item Data if (isset($data['metadata']) && isset($data['metadata']['author'])) { $data['metadata']['author'] = $filter->clean($data['metadata']['author'], 'TRIM'); - - $metadata = new JRegistry; + + $metadata = new Registry; $metadata->loadArray($data['metadata']); $data['metadata'] = (string) $metadata; } - + // Set the Params Items to data if (isset($data['params']) && is_array($data['params'])) { - $params = new JRegistry; + $params = new Registry; $params->loadArray($data['params']); $data['params'] = (string) $params; } @@ -827,7 +889,7 @@ class SermondistributorModelStatistic extends AdminModel { // Automatic handling of other unique fields $uniqueFields = $this->getUniqueFields(); - if (SermondistributorHelper::checkArray($uniqueFields)) + if (UtilitiesArrayHelper::check($uniqueFields)) { foreach ($uniqueFields as $uniqueField) { @@ -835,14 +897,14 @@ class SermondistributorModelStatistic extends AdminModel } } } - + if (parent::save($data)) { return true; } return false; } - + /** * Method to generate a unique value. * @@ -850,16 +912,14 @@ class SermondistributorModelStatistic extends AdminModel * @param string $value data. * * @return string New value. - * * @since 3.0 */ - protected function generateUnique($field,$value) + protected function generateUnique($field, $value) { - // set field value unique $table = $this->getTable(); - while ($table->load(array($field => $value))) + while ($table->load([$field => $value])) { $value = StringHelper::increment($value); } @@ -881,7 +941,7 @@ class SermondistributorModelStatistic extends AdminModel // Alter the title $table = $this->getTable(); - while ($table->load(array('title' => $title))) + while ($table->load(['title' => $title])) { $title = StringHelper::increment($title); } diff --git a/admin/models/statistics.php b/admin/src/Model/StatisticsModel.php similarity index 77% rename from admin/models/statistics.php rename to admin/src/Model/StatisticsModel.php index d92abfbc..fa88b63f 100644 --- a/admin/models/statistics.php +++ b/admin/src/Model/StatisticsModel.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage statistics.php + @subpackage StatisticsModel.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,22 +21,77 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Model; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Application\CMSApplicationInterface; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\ListModel; +use Joomla\CMS\MVC\Factory\MVCFactoryInterface; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Router\Route; +use Joomla\CMS\User\User; +use Joomla\Utilities\ArrayHelper; +use Joomla\Input\Input; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use Joomla\CMS\Helper\TagsHelper; +use VDM\Joomla\Utilities\ArrayHelper as UtilitiesArrayHelper; +use VDM\Joomla\Utilities\ObjectHelper; +use VDM\Joomla\Utilities\StringHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\Model\ListModel; -use Joomla\Utilities\ArrayHelper; +\defined('_JEXEC') or die; /** * Statistics List Model + * + * @since 1.6 */ -class SermondistributorModelStatistics extends ListModel +class StatisticsModel extends ListModel { - public function __construct($config = array()) + /** + * The application object. + * + * @var CMSApplicationInterface The application instance. + * @since 3.2.0 + */ + protected CMSApplicationInterface $app; + + /** + * The styles array. + * + * @var array + * @since 4.3 + */ + protected array $styles = [ + 'administrator/components/com_sermondistributor/assets/css/admin.css', + 'administrator/components/com_sermondistributor/assets/css/statistics.css' + ]; + + /** + * The scripts array. + * + * @var array + * @since 4.3 + */ + protected array $scripts = [ + 'administrator/components/com_sermondistributor/assets/js/admin.js' + ]; + + /** + * Constructor + * + * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). + * @param ?MVCFactoryInterface $factory The factory. + * + * @since 1.6 + * @throws \Exception + */ + public function __construct($config = [], MVCFactoryInterface $factory = null) { if (empty($config['filter_fields'])) - { + { $config['filter_fields'] = array( 'a.id','id', 'a.published','published', @@ -52,7 +107,9 @@ class SermondistributorModelStatistics extends ListModel ); } - parent::__construct($config); + parent::__construct($config, $factory); + + $this->app ??= Factory::getApplication(); } /** @@ -64,11 +121,11 @@ class SermondistributorModelStatistics extends ListModel * @param string $direction An optional direction (asc|desc). * * @return void - * + * @since 1.7.0 */ protected function populateState($ordering = null, $direction = null) { - $app = JFactory::getApplication(); + $app = $this->app; // Adjust the context to support modal layouts. if ($layout = $app->input->get('layout')) @@ -139,11 +196,12 @@ class SermondistributorModelStatistics extends ListModel // List state information. parent::populateState($ordering, $direction); } - + /** * Method to get an array of data items. * * @return mixed An array of data items on success, false on failure. + * @since 1.6 */ public function getItems() { @@ -154,12 +212,12 @@ class SermondistributorModelStatistics extends ListModel $items = parent::getItems(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } foreach ($items as $nr => &$item) { @@ -173,22 +231,23 @@ class SermondistributorModelStatistics extends ListModel } } - + // return items return $items; } - + /** * Method to build an SQL query to load the list data. * - * @return string An SQL query + * @return string An SQL query + * @since 1.6 */ protected function getListQuery() { // Get the user object. - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -229,7 +288,7 @@ class SermondistributorModelStatistics extends ListModel { $query->where('a.access = ' . (int) $_access); } - elseif (SermondistributorHelper::checkArray($_access)) + elseif (UtilitiesArrayHelper::check($_access)) { // Secure the array for the query $_access = ArrayHelper::toInteger($_access); @@ -270,7 +329,7 @@ class SermondistributorModelStatistics extends ListModel $query->where('a.sermon = ' . (int) $_sermon); } } - elseif (SermondistributorHelper::checkString($_sermon)) + elseif (StringHelper::check($_sermon)) { $query->where('a.sermon = ' . $db->quote($db->escape($_sermon))); } @@ -287,7 +346,7 @@ class SermondistributorModelStatistics extends ListModel $query->where('a.preacher = ' . (int) $_preacher); } } - elseif (SermondistributorHelper::checkString($_preacher)) + elseif (StringHelper::check($_preacher)) { $query->where('a.preacher = ' . $db->quote($db->escape($_preacher))); } @@ -304,16 +363,18 @@ class SermondistributorModelStatistics extends ListModel $query->where('a.series = ' . (int) $_series); } } - elseif (SermondistributorHelper::checkString($_series)) + elseif (StringHelper::check($_series)) { $query->where('a.series = ' . $db->quote($db->escape($_series))); } // Add the list ordering clause. - $orderCol = $this->state->get('list.ordering', 'a.id'); - $orderDirn = $this->state->get('list.direction', 'desc'); + $orderCol = $this->getState('list.ordering', 'a.id'); + $orderDirn = $this->getState('list.direction', 'desc'); if ($orderCol != '') { + // Check that the order direction is valid encase we have a field called direction as part of filers. + $orderDirn = (is_string($orderDirn) && in_array(strtolower($orderDirn), ['asc', 'desc'])) ? $orderDirn : 'desc'; $query->order($db->escape($orderCol . ' ' . $orderDirn)); } @@ -331,17 +392,17 @@ class SermondistributorModelStatistics extends ListModel public function getExportData($pks, $user = null) { // setup the query - if (($pks_size = SermondistributorHelper::checkArray($pks)) !== false || 'bulk' === $pks) + if (($pks_size = UtilitiesArrayHelper::check($pks)) !== false || 'bulk' === $pks) { // Set a value to know this is export method. (USE IN CUSTOM CODE TO ALTER OUTCOME) $_export = true; // Get the user object if not set. - if (!isset($user) || !SermondistributorHelper::checkObject($user)) + if (!isset($user) || !ObjectHelper::check($user)) { - $user = JFactory::getUser(); + $user = $this->getCurrentUser(); } // Create a new query object. - $db = JFactory::getDBO(); + $db = $this->getDatabase(); $query = $db->getQuery(true); // Select some fields @@ -385,7 +446,7 @@ class SermondistributorModelStatistics extends ListModel $items = $db->loadObjectList(); // Set values to display correctly. - if (SermondistributorHelper::checkArray($items)) + if (UtilitiesArrayHelper::check($items)) { foreach ($items as $nr => &$item) { @@ -405,7 +466,7 @@ class SermondistributorModelStatistics extends ListModel } // Add headers to items array. $headers = $this->getExImPortHeaders(); - if (SermondistributorHelper::checkObject($headers)) + if (ObjectHelper::check($headers)) { array_unshift($items,$headers); } @@ -423,16 +484,16 @@ class SermondistributorModelStatistics extends ListModel public function getExImPortHeaders() { // Get a db connection. - $db = JFactory::getDbo(); + $db = Factory::getDbo(); // get the columns $columns = $db->getTableColumns("#__sermondistributor_statistic"); - if (SermondistributorHelper::checkArray($columns)) + if (UtilitiesArrayHelper::check($columns)) { // remove the headers you don't import/export. unset($columns['asset_id']); unset($columns['checked_out']); unset($columns['checked_out_time']); - $headers = new stdClass(); + $headers = new \stdClass(); foreach ($columns as $column => $type) { $headers->{$column} = $column; @@ -441,12 +502,12 @@ class SermondistributorModelStatistics extends ListModel } return false; } - + /** * Method to get a store id based on model configuration state. * * @return string A store id. - * + * @since 1.6 */ protected function getStoreId($id = '') { @@ -456,13 +517,13 @@ class SermondistributorModelStatistics extends ListModel $id .= ':' . $this->getState('filter.published'); // Check if the value is an array $_access = $this->getState('filter.access'); - if (SermondistributorHelper::checkArray($_access)) + if (UtilitiesArrayHelper::check($_access)) { $id .= ':' . implode(':', $_access); } // Check if this is only an number or string elseif (is_numeric($_access) - || SermondistributorHelper::checkString($_access)) + || StringHelper::check($_access)) { $id .= ':' . $_access; } @@ -478,22 +539,65 @@ class SermondistributorModelStatistics extends ListModel return parent::getStoreId($id); } + /** + * Method to get the styles that have to be included on the view + * + * @return array styles files + * @since 4.3 + */ + public function getStyles(): array + { + return $this->styles; + } + + /** + * Method to set the styles that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setStyles(string $path): void + { + $this->styles[] = $path; + } + + /** + * Method to get the script that have to be included on the view + * + * @return array script files + * @since 4.3 + */ + public function getScripts(): array + { + return $this->scripts; + } + + /** + * Method to set the script that have to be included on the view + * + * @return void + * @since 4.3 + */ + public function setScript(string $path): void + { + $this->scripts[] = $path; + } + /** * Build an SQL query to checkin all items left checked out longer then a set time. * - * @return a bool - * + * @return bool + * @since 3.2.0 */ - protected function checkInNow() + protected function checkInNow(): bool { // Get set check in time - $time = JComponentHelper::getParams('com_sermondistributor')->get('check_in'); + $time = ComponentHelper::getParams('com_sermondistributor')->get('check_in'); if ($time) { - // Get a db connection. - $db = JFactory::getDbo(); + $db = $this->getDatabase(); // Reset query. $query = $db->getQuery(true); $query->select('*'); @@ -505,7 +609,7 @@ class SermondistributorModelStatistics extends ListModel if ($db->getNumRows()) { // Get Yesterdays date. - $date = JFactory::getDate()->modify($time)->toSql(); + $date = Factory::getDate()->modify($time)->toSql(); // Reset query. $query = $db->getQuery(true); @@ -526,7 +630,7 @@ class SermondistributorModelStatistics extends ListModel $db->setQuery($query); - $db->execute(); + return $db->execute(); } } diff --git a/admin/tables/index.html b/admin/src/Model/index.html similarity index 100% rename from admin/tables/index.html rename to admin/src/Model/index.html diff --git a/admin/views/external_source/tmpl/index.html b/admin/src/Rule/index.html similarity index 100% rename from admin/views/external_source/tmpl/index.html rename to admin/src/Rule/index.html diff --git a/admin/views/external_sources/index.html b/admin/src/Service/index.html similarity index 100% rename from admin/views/external_sources/index.html rename to admin/src/Service/index.html diff --git a/admin/tables/external_source.php b/admin/src/Table/External_sourceTable.php similarity index 54% rename from admin/tables/external_source.php rename to admin/src/Table/External_sourceTable.php index 648193f7..b38e2465 100644 --- a/admin/tables/external_source.php +++ b/admin/src/Table/External_sourceTable.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage external_source.php + @subpackage External_sourceTable.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,84 +21,108 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Table; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; use Joomla\CMS\Table\Table; +use Joomla\CMS\Language\Text; +use Joomla\CMS\String\PunycodeHelper; +use Joomla\CMS\Access\Access as AccessRules; +use Joomla\CMS\Access\Rules; +use Joomla\CMS\Tag\TaggableTableInterface; +use Joomla\CMS\Tag\TaggableTableTrait; +use Joomla\CMS\User\CurrentUserInterface; +use Joomla\CMS\User\CurrentUserTrait; +use Joomla\CMS\Versioning\VersionableTableInterface; +use Joomla\CMS\Application\ApplicationHelper; +use Joomla\Database\DatabaseInterface; use Joomla\Registry\Registry; +use Joomla\Database\DatabaseDriver; +use Joomla\Event\DispatcherInterface; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * External_sources Table class + * + * @since 1.6 */ -class SermondistributorTableExternal_source extends Table +class External_sourceTable extends Table implements VersionableTableInterface, TaggableTableInterface, CurrentUserInterface { - /** - * Ensure the params and metadata in json encoded in the bind method - * - * @var array - * @since 3.3 - */ - protected $_jsonEncode = array('params', 'metadata'); - + use TaggableTableTrait; + use CurrentUserTrait; + /** * Constructor * + * @param DatabaseDriver $db Database connector object + * @param ?DispatcherInterface $dispatcher Event dispatcher for this table + * * @param object Database connector object + * @since 4.0 */ - function __construct(&$db) + function __construct(DatabaseDriver $db, ?DispatcherInterface $dispatcher = null) { - parent::__construct('#__sermondistributor_external_source', 'id', $db); + // The type alias generally is the internal component name with the + // content type. Ex.: com_content.article + $this->typeAlias = 'com_sermondistributor.external_source'; - // Adding History Options - JTableObserverContenthistory::createObserver($this, array('typeAlias' => 'com_sermondistributor.external_source')); - } - + // Ensure the params and metadata in json encoded in the bind method + $this->_jsonEncode = ['params', 'metadata']; + + // Indicates that columns fully support the NULL value in the database + // $this->_supportNullValue = true; // hmmm will keep an eye on this ;) + + parent::__construct('#__sermondistributor_external_source', 'id', $db, $dispatcher); + } + + /** + * Method to bind an associative array or object to the Table instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param array|object $src An associative array or object to bind to the Table instance. + * @param array|string $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @since 1.7.0 + * @throws \InvalidArgumentException + */ public function bind($array, $ignore = '') { - - if (isset($array['params']) && is_array($array['params'])) + // Bind the rules. + if (isset($array['rules']) && is_array($array['rules'])) { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = (string) $registry; + $rules = new AccessRules($array['rules']); + $this->setRules($rules); } - if (isset($array['metadata']) && is_array($array['metadata'])) - { - $registry = new JRegistry; - $registry->loadArray($array['metadata']); - $array['metadata'] = (string) $registry; - } - - // Bind the rules. - if (isset($array['rules']) && is_array($array['rules'])) - { - $rules = new JAccessRules($array['rules']); - $this->setRules($rules); - } return parent::bind($array, $ignore); } - + /** * Overload the store method for the External_source table. * - * @param boolean Toggle whether null values should be updated. + * @param boolean Toggle whether null values should be updated. + * * @return boolean True on success, false on failure. * @since 1.6 */ public function store($updateNulls = false) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); + $date = Factory::getDate()->toSql(); + $userId = $this->getCurrentUser()->id; if ($this->id) { // Existing item - $this->modified = $date->toSql(); - $this->modified_by = $user->get('id'); + $this->modified = $date; + $this->modified_by = $userId; } else { @@ -106,65 +130,82 @@ class SermondistributorTableExternal_source extends Table // so we don't touch either of these if they are set. if (!(int) $this->created) { - $this->created = $date->toSql(); + $this->created = $date; } if (empty($this->created_by)) { - $this->created_by = $user->get('id'); + $this->created_by = $userId; } } - + if (isset($this->alias)) { // Verify that the alias is unique - $table = JTable::getInstance('external_source', 'SermondistributorTable'); + $table = new self($this->getDbo(), $this->getDispatcher()); - if ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + if ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { - $this->setError(JText::_('COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_ERROR_UNIQUE_ALIAS')); + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_ERROR_UNIQUE_ALIAS')); + + if ($table->published === -2) + { + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_ERROR_UNIQUE_ALIAS_TRASHED')); + } + return false; } } - + if (isset($this->url)) { // Convert IDN urls to punycode - $this->url = JStringPunycode::urlToPunycode($this->url); + $this->url = PunycodeHelper::urlToPunycode($this->url); } + if (isset($this->website)) { // Convert IDN urls to punycode - $this->website = JStringPunycode::urlToPunycode($this->website); + $this->website = PunycodeHelper::urlToPunycode($this->website); } return parent::store($updateNulls); } - + /** * Overloaded check method to ensure data integrity. * * @return boolean True on success. + * + * @see \Joomla\CMS\Table\Table::check + * @since 1.5 */ public function check() { + try { + parent::check(); + } catch (\Exception $e) { + $this->setError($e->getMessage()); + return false; + } + if (isset($this->alias)) { // Generate a valid alias $this->generateAlias(); - - $table = JTable::getInstance('external_source', 'sermondistributorTable'); - while ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + $table = new self($this->getDbo(), $this->getDispatcher()); + + while ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { $this->alias = StringHelper::increment($this->alias, 'dash'); } } - + /* * Clean up keywords -- eliminate extra spaces between phrases * and cr (\r) and lf (\n) characters from string. * Only process if not empty. - */ + */ if (!empty($this->metakey)) { // Array of characters to remove. @@ -175,7 +216,7 @@ class SermondistributorTableExternal_source extends Table // Create array using commas as delimiter. $keys = explode(',', $after_clean); - $clean_keys = array(); + $clean_keys = []; foreach ($keys as $key) { @@ -198,13 +239,13 @@ class SermondistributorTableExternal_source extends Table $this->metadesc = StringHelper::str_ireplace($bad_characters, "", $this->metadesc); } - // If we don't have any access rules set at this point just use an empty JAccessRules class + // If we don't have any access rules set at this point just use an empty AccessRules class if (!$this->getRules()) { $rules = $this->getDefaultAssetValues('com_sermondistributor.external_source.'.$this->id); $this->setRules($rules); } - + // Set ordering if ($this->published < 0) { @@ -220,12 +261,12 @@ class SermondistributorTableExternal_source extends Table * * @param $string $component The component asset name to search for * - * @return JAccessRules The JAccessRules object for the asset + * @return AccessRules The AccessRules object for the asset */ protected function getDefaultAssetValues($component, $try = true) { // Need to find the asset id by the name of the component. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(DatabaseInterface::class); $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__assets')) @@ -236,14 +277,14 @@ class SermondistributorTableExternal_source extends Table { // asset already set so use saved rules $assetId = (int) $db->loadResult(); - return JAccess::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. + return AccessRules::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. } // try again elseif ($try) { $try = explode('.',$component); $result = $this->getDefaultAssetValues($try[0], false); - if ($result instanceof JAccessRules) + if ($result instanceof AccessRules) { if (isset($try[1])) { @@ -260,7 +301,7 @@ class SermondistributorTableExternal_source extends Table else { // clear the value since we inherit - $rule = array(); + $rule = []; } } // check if there are any view values remaining @@ -268,8 +309,8 @@ class SermondistributorTableExternal_source extends Table { $_result = json_encode($_result); $_result = array($_result); - // Instantiate and return the JAccessRules object for the asset rules. - $rules = new JAccessRules; + // Instantiate and return the AccessRules object for the asset rules. + $rules = new AccessRules; $rules->mergeCollection($_result); return $rules; @@ -278,50 +319,63 @@ class SermondistributorTableExternal_source extends Table return $result; } } - return JAccess::getAssetRules(0); + return AccessRules::getAssetRules(0); + } + + /** + * Get the type alias for the history table + * + * The type alias generally is the internal component name with the + * content type. Ex.: com_content.article + * + * @return string The alias as described above + * + * @since 3.10.0 + */ + public function getTypeAlias() + { + return $this->typeAlias; } /** * Method to compute the default name of the asset. - * The default name is in the form 'table_name.id' + * The default name is in the form table_name.id * where id is the value of the primary key of the table. * - * @return string - * @since 2.5 + * @return string + * + * @since 1.7.0 */ protected function _getAssetName() { $k = $this->_tbl_key; - return 'com_sermondistributor.external_source.'.(int) $this->$k; + + return $this->getTypeAlias() . '.' . (int) $this->$k; } /** - * Method to return the title to use for the asset table. + * Method to get the parent asset under which to register this one. * - * @return string - * @since 2.5 - */ - protected function _getAssetTitle() - { - if (isset($this->title)) - { - return $this->title; - } - return ''; - } - - /** - * Get the parent asset id for the record + * By default, all assets are registered to the ROOT node with ID, which will default to 1 if none exists. + * An extended class can define a table and ID to lookup. If the asset does not exist it will be created. * - * @return int - * @since 2.5 + * @param Table $table A Table object for the asset parent. + * @param integer $id Id to look up + * + * @return integer + * + * @since 1.7.0 */ - protected function _getAssetParentId(JTable $table = NULL, $id = NULL) + protected function _getAssetParentId(Table $table = null, $id = null) { - $asset = JTable::getInstance('Asset'); - $asset->loadByName('com_sermondistributor'); + /** @var Asset $assets */ + $assets = self::getInstance('Asset', 'JTable', ['dbo' => $this->getDbo()]); + $rootId = $assets->getRootId(); - return $asset->id; + // load the sermondistributor asset + $assets->loadByName('com_sermondistributor'); + + return $assets->id ?? $rootId ?? 1; } /** @@ -333,5 +387,4 @@ class SermondistributorTableExternal_source extends Table { return false; } - } diff --git a/admin/tables/help_document.php b/admin/src/Table/Help_documentTable.php similarity index 55% rename from admin/tables/help_document.php rename to admin/src/Table/Help_documentTable.php index 949509a6..f65759ca 100644 --- a/admin/tables/help_document.php +++ b/admin/src/Table/Help_documentTable.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage help_document.php + @subpackage Help_documentTable.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,84 +21,108 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Table; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; use Joomla\CMS\Table\Table; +use Joomla\CMS\Language\Text; +use Joomla\CMS\String\PunycodeHelper; +use Joomla\CMS\Access\Access as AccessRules; +use Joomla\CMS\Access\Rules; +use Joomla\CMS\Tag\TaggableTableInterface; +use Joomla\CMS\Tag\TaggableTableTrait; +use Joomla\CMS\User\CurrentUserInterface; +use Joomla\CMS\User\CurrentUserTrait; +use Joomla\CMS\Versioning\VersionableTableInterface; +use Joomla\CMS\Application\ApplicationHelper; +use Joomla\Database\DatabaseInterface; use Joomla\Registry\Registry; +use Joomla\Database\DatabaseDriver; +use Joomla\Event\DispatcherInterface; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Help_documents Table class + * + * @since 1.6 */ -class SermondistributorTableHelp_document extends Table +class Help_documentTable extends Table implements VersionableTableInterface, TaggableTableInterface, CurrentUserInterface { - /** - * Ensure the params and metadata in json encoded in the bind method - * - * @var array - * @since 3.3 - */ - protected $_jsonEncode = array('params', 'metadata'); - + use TaggableTableTrait; + use CurrentUserTrait; + /** * Constructor * + * @param DatabaseDriver $db Database connector object + * @param ?DispatcherInterface $dispatcher Event dispatcher for this table + * * @param object Database connector object + * @since 4.0 */ - function __construct(&$db) + function __construct(DatabaseDriver $db, ?DispatcherInterface $dispatcher = null) { - parent::__construct('#__sermondistributor_help_document', 'id', $db); + // The type alias generally is the internal component name with the + // content type. Ex.: com_content.article + $this->typeAlias = 'com_sermondistributor.help_document'; - // Adding History Options - JTableObserverContenthistory::createObserver($this, array('typeAlias' => 'com_sermondistributor.help_document')); - } - + // Ensure the params and metadata in json encoded in the bind method + $this->_jsonEncode = ['params', 'metadata']; + + // Indicates that columns fully support the NULL value in the database + // $this->_supportNullValue = true; // hmmm will keep an eye on this ;) + + parent::__construct('#__sermondistributor_help_document', 'id', $db, $dispatcher); + } + + /** + * Method to bind an associative array or object to the Table instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param array|object $src An associative array or object to bind to the Table instance. + * @param array|string $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @since 1.7.0 + * @throws \InvalidArgumentException + */ public function bind($array, $ignore = '') { - - if (isset($array['params']) && is_array($array['params'])) + // Bind the rules. + if (isset($array['rules']) && is_array($array['rules'])) { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = (string) $registry; + $rules = new AccessRules($array['rules']); + $this->setRules($rules); } - if (isset($array['metadata']) && is_array($array['metadata'])) - { - $registry = new JRegistry; - $registry->loadArray($array['metadata']); - $array['metadata'] = (string) $registry; - } - - // Bind the rules. - if (isset($array['rules']) && is_array($array['rules'])) - { - $rules = new JAccessRules($array['rules']); - $this->setRules($rules); - } return parent::bind($array, $ignore); } - + /** * Overload the store method for the Help_document table. * - * @param boolean Toggle whether null values should be updated. + * @param boolean Toggle whether null values should be updated. + * * @return boolean True on success, false on failure. * @since 1.6 */ public function store($updateNulls = false) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); + $date = Factory::getDate()->toSql(); + $userId = $this->getCurrentUser()->id; if ($this->id) { // Existing item - $this->modified = $date->toSql(); - $this->modified_by = $user->get('id'); + $this->modified = $date; + $this->modified_by = $userId; } else { @@ -106,65 +130,82 @@ class SermondistributorTableHelp_document extends Table // so we don't touch either of these if they are set. if (!(int) $this->created) { - $this->created = $date->toSql(); + $this->created = $date; } if (empty($this->created_by)) { - $this->created_by = $user->get('id'); + $this->created_by = $userId; } } - + if (isset($this->alias)) { // Verify that the alias is unique - $table = JTable::getInstance('help_document', 'SermondistributorTable'); + $table = new self($this->getDbo(), $this->getDispatcher()); - if ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + if ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { - $this->setError(JText::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_ERROR_UNIQUE_ALIAS')); + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_ERROR_UNIQUE_ALIAS')); + + if ($table->published === -2) + { + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_ERROR_UNIQUE_ALIAS_TRASHED')); + } + return false; } } - + if (isset($this->url)) { // Convert IDN urls to punycode - $this->url = JStringPunycode::urlToPunycode($this->url); + $this->url = PunycodeHelper::urlToPunycode($this->url); } + if (isset($this->website)) { // Convert IDN urls to punycode - $this->website = JStringPunycode::urlToPunycode($this->website); + $this->website = PunycodeHelper::urlToPunycode($this->website); } return parent::store($updateNulls); } - + /** * Overloaded check method to ensure data integrity. * * @return boolean True on success. + * + * @see \Joomla\CMS\Table\Table::check + * @since 1.5 */ public function check() { + try { + parent::check(); + } catch (\Exception $e) { + $this->setError($e->getMessage()); + return false; + } + if (isset($this->alias)) { // Generate a valid alias $this->generateAlias(); - - $table = JTable::getInstance('help_document', 'sermondistributorTable'); - while ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + $table = new self($this->getDbo(), $this->getDispatcher()); + + while ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { $this->alias = StringHelper::increment($this->alias, 'dash'); } } - + /* * Clean up keywords -- eliminate extra spaces between phrases * and cr (\r) and lf (\n) characters from string. * Only process if not empty. - */ + */ if (!empty($this->metakey)) { // Array of characters to remove. @@ -175,7 +216,7 @@ class SermondistributorTableHelp_document extends Table // Create array using commas as delimiter. $keys = explode(',', $after_clean); - $clean_keys = array(); + $clean_keys = []; foreach ($keys as $key) { @@ -198,13 +239,13 @@ class SermondistributorTableHelp_document extends Table $this->metadesc = StringHelper::str_ireplace($bad_characters, "", $this->metadesc); } - // If we don't have any access rules set at this point just use an empty JAccessRules class + // If we don't have any access rules set at this point just use an empty AccessRules class if (!$this->getRules()) { $rules = $this->getDefaultAssetValues('com_sermondistributor.help_document.'.$this->id); $this->setRules($rules); } - + // Set ordering if ($this->published < 0) { @@ -220,12 +261,12 @@ class SermondistributorTableHelp_document extends Table * * @param $string $component The component asset name to search for * - * @return JAccessRules The JAccessRules object for the asset + * @return AccessRules The AccessRules object for the asset */ protected function getDefaultAssetValues($component, $try = true) { // Need to find the asset id by the name of the component. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(DatabaseInterface::class); $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__assets')) @@ -236,14 +277,14 @@ class SermondistributorTableHelp_document extends Table { // asset already set so use saved rules $assetId = (int) $db->loadResult(); - return JAccess::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. + return AccessRules::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. } // try again elseif ($try) { $try = explode('.',$component); $result = $this->getDefaultAssetValues($try[0], false); - if ($result instanceof JAccessRules) + if ($result instanceof AccessRules) { if (isset($try[1])) { @@ -260,7 +301,7 @@ class SermondistributorTableHelp_document extends Table else { // clear the value since we inherit - $rule = array(); + $rule = []; } } // check if there are any view values remaining @@ -268,8 +309,8 @@ class SermondistributorTableHelp_document extends Table { $_result = json_encode($_result); $_result = array($_result); - // Instantiate and return the JAccessRules object for the asset rules. - $rules = new JAccessRules; + // Instantiate and return the AccessRules object for the asset rules. + $rules = new AccessRules; $rules->mergeCollection($_result); return $rules; @@ -278,50 +319,63 @@ class SermondistributorTableHelp_document extends Table return $result; } } - return JAccess::getAssetRules(0); + return AccessRules::getAssetRules(0); + } + + /** + * Get the type alias for the history table + * + * The type alias generally is the internal component name with the + * content type. Ex.: com_content.article + * + * @return string The alias as described above + * + * @since 3.10.0 + */ + public function getTypeAlias() + { + return $this->typeAlias; } /** * Method to compute the default name of the asset. - * The default name is in the form 'table_name.id' + * The default name is in the form table_name.id * where id is the value of the primary key of the table. * - * @return string - * @since 2.5 + * @return string + * + * @since 1.7.0 */ protected function _getAssetName() { $k = $this->_tbl_key; - return 'com_sermondistributor.help_document.'.(int) $this->$k; + + return $this->getTypeAlias() . '.' . (int) $this->$k; } /** - * Method to return the title to use for the asset table. + * Method to get the parent asset under which to register this one. * - * @return string - * @since 2.5 - */ - protected function _getAssetTitle() - { - if (isset($this->title)) - { - return $this->title; - } - return ''; - } - - /** - * Get the parent asset id for the record + * By default, all assets are registered to the ROOT node with ID, which will default to 1 if none exists. + * An extended class can define a table and ID to lookup. If the asset does not exist it will be created. * - * @return int - * @since 2.5 + * @param Table $table A Table object for the asset parent. + * @param integer $id Id to look up + * + * @return integer + * + * @since 1.7.0 */ - protected function _getAssetParentId(JTable $table = NULL, $id = NULL) + protected function _getAssetParentId(Table $table = null, $id = null) { - $asset = JTable::getInstance('Asset'); - $asset->loadByName('com_sermondistributor'); + /** @var Asset $assets */ + $assets = self::getInstance('Asset', 'JTable', ['dbo' => $this->getDbo()]); + $rootId = $assets->getRootId(); - return $asset->id; + // load the sermondistributor asset + $assets->loadByName('com_sermondistributor'); + + return $assets->id ?? $rootId ?? 1; } /** @@ -337,14 +391,13 @@ class SermondistributorTableHelp_document extends Table $this->alias = $this->title; } - $this->alias = JApplicationHelper::stringURLSafe($this->alias); + $this->alias = ApplicationHelper::stringURLSafe($this->alias); if (trim(str_replace('-', '', $this->alias)) == '') { - $this->alias = JFactory::getDate()->format('Y-m-d-H-i-s'); + $this->alias = Factory::getDate()->format('Y-m-d-H-i-s'); } return $this->alias; } - } diff --git a/admin/tables/local_listing.php b/admin/src/Table/Local_listingTable.php similarity index 54% rename from admin/tables/local_listing.php rename to admin/src/Table/Local_listingTable.php index f8c731e9..638a7c24 100644 --- a/admin/tables/local_listing.php +++ b/admin/src/Table/Local_listingTable.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage local_listing.php + @subpackage Local_listingTable.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,84 +21,108 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Table; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; use Joomla\CMS\Table\Table; +use Joomla\CMS\Language\Text; +use Joomla\CMS\String\PunycodeHelper; +use Joomla\CMS\Access\Access as AccessRules; +use Joomla\CMS\Access\Rules; +use Joomla\CMS\Tag\TaggableTableInterface; +use Joomla\CMS\Tag\TaggableTableTrait; +use Joomla\CMS\User\CurrentUserInterface; +use Joomla\CMS\User\CurrentUserTrait; +use Joomla\CMS\Versioning\VersionableTableInterface; +use Joomla\CMS\Application\ApplicationHelper; +use Joomla\Database\DatabaseInterface; use Joomla\Registry\Registry; +use Joomla\Database\DatabaseDriver; +use Joomla\Event\DispatcherInterface; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Local_listings Table class + * + * @since 1.6 */ -class SermondistributorTableLocal_listing extends Table +class Local_listingTable extends Table implements VersionableTableInterface, TaggableTableInterface, CurrentUserInterface { - /** - * Ensure the params and metadata in json encoded in the bind method - * - * @var array - * @since 3.3 - */ - protected $_jsonEncode = array('params', 'metadata'); - + use TaggableTableTrait; + use CurrentUserTrait; + /** * Constructor * + * @param DatabaseDriver $db Database connector object + * @param ?DispatcherInterface $dispatcher Event dispatcher for this table + * * @param object Database connector object + * @since 4.0 */ - function __construct(&$db) + function __construct(DatabaseDriver $db, ?DispatcherInterface $dispatcher = null) { - parent::__construct('#__sermondistributor_local_listing', 'id', $db); + // The type alias generally is the internal component name with the + // content type. Ex.: com_content.article + $this->typeAlias = 'com_sermondistributor.local_listing'; - // Adding History Options - JTableObserverContenthistory::createObserver($this, array('typeAlias' => 'com_sermondistributor.local_listing')); - } - + // Ensure the params and metadata in json encoded in the bind method + $this->_jsonEncode = ['params', 'metadata']; + + // Indicates that columns fully support the NULL value in the database + // $this->_supportNullValue = true; // hmmm will keep an eye on this ;) + + parent::__construct('#__sermondistributor_local_listing', 'id', $db, $dispatcher); + } + + /** + * Method to bind an associative array or object to the Table instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param array|object $src An associative array or object to bind to the Table instance. + * @param array|string $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @since 1.7.0 + * @throws \InvalidArgumentException + */ public function bind($array, $ignore = '') { - - if (isset($array['params']) && is_array($array['params'])) + // Bind the rules. + if (isset($array['rules']) && is_array($array['rules'])) { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = (string) $registry; + $rules = new AccessRules($array['rules']); + $this->setRules($rules); } - if (isset($array['metadata']) && is_array($array['metadata'])) - { - $registry = new JRegistry; - $registry->loadArray($array['metadata']); - $array['metadata'] = (string) $registry; - } - - // Bind the rules. - if (isset($array['rules']) && is_array($array['rules'])) - { - $rules = new JAccessRules($array['rules']); - $this->setRules($rules); - } return parent::bind($array, $ignore); } - + /** * Overload the store method for the Local_listing table. * - * @param boolean Toggle whether null values should be updated. + * @param boolean Toggle whether null values should be updated. + * * @return boolean True on success, false on failure. * @since 1.6 */ public function store($updateNulls = false) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); + $date = Factory::getDate()->toSql(); + $userId = $this->getCurrentUser()->id; if ($this->id) { // Existing item - $this->modified = $date->toSql(); - $this->modified_by = $user->get('id'); + $this->modified = $date; + $this->modified_by = $userId; } else { @@ -106,65 +130,82 @@ class SermondistributorTableLocal_listing extends Table // so we don't touch either of these if they are set. if (!(int) $this->created) { - $this->created = $date->toSql(); + $this->created = $date; } if (empty($this->created_by)) { - $this->created_by = $user->get('id'); + $this->created_by = $userId; } } - + if (isset($this->alias)) { // Verify that the alias is unique - $table = JTable::getInstance('local_listing', 'SermondistributorTable'); + $table = new self($this->getDbo(), $this->getDispatcher()); - if ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + if ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { - $this->setError(JText::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_ERROR_UNIQUE_ALIAS')); + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_ERROR_UNIQUE_ALIAS')); + + if ($table->published === -2) + { + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_ERROR_UNIQUE_ALIAS_TRASHED')); + } + return false; } } - + if (isset($this->url)) { // Convert IDN urls to punycode - $this->url = JStringPunycode::urlToPunycode($this->url); + $this->url = PunycodeHelper::urlToPunycode($this->url); } + if (isset($this->website)) { // Convert IDN urls to punycode - $this->website = JStringPunycode::urlToPunycode($this->website); + $this->website = PunycodeHelper::urlToPunycode($this->website); } return parent::store($updateNulls); } - + /** * Overloaded check method to ensure data integrity. * * @return boolean True on success. + * + * @see \Joomla\CMS\Table\Table::check + * @since 1.5 */ public function check() { + try { + parent::check(); + } catch (\Exception $e) { + $this->setError($e->getMessage()); + return false; + } + if (isset($this->alias)) { // Generate a valid alias $this->generateAlias(); - - $table = JTable::getInstance('local_listing', 'sermondistributorTable'); - while ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + $table = new self($this->getDbo(), $this->getDispatcher()); + + while ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { $this->alias = StringHelper::increment($this->alias, 'dash'); } } - + /* * Clean up keywords -- eliminate extra spaces between phrases * and cr (\r) and lf (\n) characters from string. * Only process if not empty. - */ + */ if (!empty($this->metakey)) { // Array of characters to remove. @@ -175,7 +216,7 @@ class SermondistributorTableLocal_listing extends Table // Create array using commas as delimiter. $keys = explode(',', $after_clean); - $clean_keys = array(); + $clean_keys = []; foreach ($keys as $key) { @@ -198,13 +239,13 @@ class SermondistributorTableLocal_listing extends Table $this->metadesc = StringHelper::str_ireplace($bad_characters, "", $this->metadesc); } - // If we don't have any access rules set at this point just use an empty JAccessRules class + // If we don't have any access rules set at this point just use an empty AccessRules class if (!$this->getRules()) { $rules = $this->getDefaultAssetValues('com_sermondistributor.local_listing.'.$this->id); $this->setRules($rules); } - + // Set ordering if ($this->published < 0) { @@ -220,12 +261,12 @@ class SermondistributorTableLocal_listing extends Table * * @param $string $component The component asset name to search for * - * @return JAccessRules The JAccessRules object for the asset + * @return AccessRules The AccessRules object for the asset */ protected function getDefaultAssetValues($component, $try = true) { // Need to find the asset id by the name of the component. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(DatabaseInterface::class); $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__assets')) @@ -236,14 +277,14 @@ class SermondistributorTableLocal_listing extends Table { // asset already set so use saved rules $assetId = (int) $db->loadResult(); - return JAccess::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. + return AccessRules::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. } // try again elseif ($try) { $try = explode('.',$component); $result = $this->getDefaultAssetValues($try[0], false); - if ($result instanceof JAccessRules) + if ($result instanceof AccessRules) { if (isset($try[1])) { @@ -260,7 +301,7 @@ class SermondistributorTableLocal_listing extends Table else { // clear the value since we inherit - $rule = array(); + $rule = []; } } // check if there are any view values remaining @@ -268,8 +309,8 @@ class SermondistributorTableLocal_listing extends Table { $_result = json_encode($_result); $_result = array($_result); - // Instantiate and return the JAccessRules object for the asset rules. - $rules = new JAccessRules; + // Instantiate and return the AccessRules object for the asset rules. + $rules = new AccessRules; $rules->mergeCollection($_result); return $rules; @@ -278,50 +319,63 @@ class SermondistributorTableLocal_listing extends Table return $result; } } - return JAccess::getAssetRules(0); + return AccessRules::getAssetRules(0); + } + + /** + * Get the type alias for the history table + * + * The type alias generally is the internal component name with the + * content type. Ex.: com_content.article + * + * @return string The alias as described above + * + * @since 3.10.0 + */ + public function getTypeAlias() + { + return $this->typeAlias; } /** * Method to compute the default name of the asset. - * The default name is in the form 'table_name.id' + * The default name is in the form table_name.id * where id is the value of the primary key of the table. * - * @return string - * @since 2.5 + * @return string + * + * @since 1.7.0 */ protected function _getAssetName() { $k = $this->_tbl_key; - return 'com_sermondistributor.local_listing.'.(int) $this->$k; + + return $this->getTypeAlias() . '.' . (int) $this->$k; } /** - * Method to return the title to use for the asset table. + * Method to get the parent asset under which to register this one. * - * @return string - * @since 2.5 - */ - protected function _getAssetTitle() - { - if (isset($this->title)) - { - return $this->title; - } - return ''; - } - - /** - * Get the parent asset id for the record + * By default, all assets are registered to the ROOT node with ID, which will default to 1 if none exists. + * An extended class can define a table and ID to lookup. If the asset does not exist it will be created. * - * @return int - * @since 2.5 + * @param Table $table A Table object for the asset parent. + * @param integer $id Id to look up + * + * @return integer + * + * @since 1.7.0 */ - protected function _getAssetParentId(JTable $table = NULL, $id = NULL) + protected function _getAssetParentId(Table $table = null, $id = null) { - $asset = JTable::getInstance('Asset'); - $asset->loadByName('com_sermondistributor'); + /** @var Asset $assets */ + $assets = self::getInstance('Asset', 'JTable', ['dbo' => $this->getDbo()]); + $rootId = $assets->getRootId(); - return $asset->id; + // load the sermondistributor asset + $assets->loadByName('com_sermondistributor'); + + return $assets->id ?? $rootId ?? 1; } /** @@ -333,5 +387,4 @@ class SermondistributorTableLocal_listing extends Table { return false; } - } diff --git a/admin/tables/preacher.php b/admin/src/Table/PreacherTable.php similarity index 55% rename from admin/tables/preacher.php rename to admin/src/Table/PreacherTable.php index 2dbb4e9d..951bf156 100644 --- a/admin/tables/preacher.php +++ b/admin/src/Table/PreacherTable.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage preacher.php + @subpackage PreacherTable.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,84 +21,108 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Table; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; use Joomla\CMS\Table\Table; +use Joomla\CMS\Language\Text; +use Joomla\CMS\String\PunycodeHelper; +use Joomla\CMS\Access\Access as AccessRules; +use Joomla\CMS\Access\Rules; +use Joomla\CMS\Tag\TaggableTableInterface; +use Joomla\CMS\Tag\TaggableTableTrait; +use Joomla\CMS\User\CurrentUserInterface; +use Joomla\CMS\User\CurrentUserTrait; +use Joomla\CMS\Versioning\VersionableTableInterface; +use Joomla\CMS\Application\ApplicationHelper; +use Joomla\Database\DatabaseInterface; use Joomla\Registry\Registry; +use Joomla\Database\DatabaseDriver; +use Joomla\Event\DispatcherInterface; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Preachers Table class + * + * @since 1.6 */ -class SermondistributorTablePreacher extends Table +class PreacherTable extends Table implements VersionableTableInterface, TaggableTableInterface, CurrentUserInterface { - /** - * Ensure the params and metadata in json encoded in the bind method - * - * @var array - * @since 3.3 - */ - protected $_jsonEncode = array('params', 'metadata'); - + use TaggableTableTrait; + use CurrentUserTrait; + /** * Constructor * + * @param DatabaseDriver $db Database connector object + * @param ?DispatcherInterface $dispatcher Event dispatcher for this table + * * @param object Database connector object + * @since 4.0 */ - function __construct(&$db) + function __construct(DatabaseDriver $db, ?DispatcherInterface $dispatcher = null) { - parent::__construct('#__sermondistributor_preacher', 'id', $db); + // The type alias generally is the internal component name with the + // content type. Ex.: com_content.article + $this->typeAlias = 'com_sermondistributor.preacher'; - // Adding History Options - JTableObserverContenthistory::createObserver($this, array('typeAlias' => 'com_sermondistributor.preacher')); - } - + // Ensure the params and metadata in json encoded in the bind method + $this->_jsonEncode = ['params', 'metadata']; + + // Indicates that columns fully support the NULL value in the database + // $this->_supportNullValue = true; // hmmm will keep an eye on this ;) + + parent::__construct('#__sermondistributor_preacher', 'id', $db, $dispatcher); + } + + /** + * Method to bind an associative array or object to the Table instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param array|object $src An associative array or object to bind to the Table instance. + * @param array|string $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @since 1.7.0 + * @throws \InvalidArgumentException + */ public function bind($array, $ignore = '') { - - if (isset($array['params']) && is_array($array['params'])) + // Bind the rules. + if (isset($array['rules']) && is_array($array['rules'])) { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = (string) $registry; + $rules = new AccessRules($array['rules']); + $this->setRules($rules); } - if (isset($array['metadata']) && is_array($array['metadata'])) - { - $registry = new JRegistry; - $registry->loadArray($array['metadata']); - $array['metadata'] = (string) $registry; - } - - // Bind the rules. - if (isset($array['rules']) && is_array($array['rules'])) - { - $rules = new JAccessRules($array['rules']); - $this->setRules($rules); - } return parent::bind($array, $ignore); } - + /** * Overload the store method for the Preacher table. * - * @param boolean Toggle whether null values should be updated. + * @param boolean Toggle whether null values should be updated. + * * @return boolean True on success, false on failure. * @since 1.6 */ public function store($updateNulls = false) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); + $date = Factory::getDate()->toSql(); + $userId = $this->getCurrentUser()->id; if ($this->id) { // Existing item - $this->modified = $date->toSql(); - $this->modified_by = $user->get('id'); + $this->modified = $date; + $this->modified_by = $userId; } else { @@ -106,65 +130,82 @@ class SermondistributorTablePreacher extends Table // so we don't touch either of these if they are set. if (!(int) $this->created) { - $this->created = $date->toSql(); + $this->created = $date; } if (empty($this->created_by)) { - $this->created_by = $user->get('id'); + $this->created_by = $userId; } } - + if (isset($this->alias)) { // Verify that the alias is unique - $table = JTable::getInstance('preacher', 'SermondistributorTable'); + $table = new self($this->getDbo(), $this->getDispatcher()); - if ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + if ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { - $this->setError(JText::_('COM_SERMONDISTRIBUTOR_PREACHER_ERROR_UNIQUE_ALIAS')); + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_PREACHER_ERROR_UNIQUE_ALIAS')); + + if ($table->published === -2) + { + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_PREACHER_ERROR_UNIQUE_ALIAS_TRASHED')); + } + return false; } } - + if (isset($this->url)) { // Convert IDN urls to punycode - $this->url = JStringPunycode::urlToPunycode($this->url); + $this->url = PunycodeHelper::urlToPunycode($this->url); } + if (isset($this->website)) { // Convert IDN urls to punycode - $this->website = JStringPunycode::urlToPunycode($this->website); + $this->website = PunycodeHelper::urlToPunycode($this->website); } return parent::store($updateNulls); } - + /** * Overloaded check method to ensure data integrity. * * @return boolean True on success. + * + * @see \Joomla\CMS\Table\Table::check + * @since 1.5 */ public function check() { + try { + parent::check(); + } catch (\Exception $e) { + $this->setError($e->getMessage()); + return false; + } + if (isset($this->alias)) { // Generate a valid alias $this->generateAlias(); - - $table = JTable::getInstance('preacher', 'sermondistributorTable'); - while ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + $table = new self($this->getDbo(), $this->getDispatcher()); + + while ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { $this->alias = StringHelper::increment($this->alias, 'dash'); } } - + /* * Clean up keywords -- eliminate extra spaces between phrases * and cr (\r) and lf (\n) characters from string. * Only process if not empty. - */ + */ if (!empty($this->metakey)) { // Array of characters to remove. @@ -175,7 +216,7 @@ class SermondistributorTablePreacher extends Table // Create array using commas as delimiter. $keys = explode(',', $after_clean); - $clean_keys = array(); + $clean_keys = []; foreach ($keys as $key) { @@ -198,13 +239,13 @@ class SermondistributorTablePreacher extends Table $this->metadesc = StringHelper::str_ireplace($bad_characters, "", $this->metadesc); } - // If we don't have any access rules set at this point just use an empty JAccessRules class + // If we don't have any access rules set at this point just use an empty AccessRules class if (!$this->getRules()) { $rules = $this->getDefaultAssetValues('com_sermondistributor.preacher.'.$this->id); $this->setRules($rules); } - + // Set ordering if ($this->published < 0) { @@ -220,12 +261,12 @@ class SermondistributorTablePreacher extends Table * * @param $string $component The component asset name to search for * - * @return JAccessRules The JAccessRules object for the asset + * @return AccessRules The AccessRules object for the asset */ protected function getDefaultAssetValues($component, $try = true) { // Need to find the asset id by the name of the component. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(DatabaseInterface::class); $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__assets')) @@ -236,14 +277,14 @@ class SermondistributorTablePreacher extends Table { // asset already set so use saved rules $assetId = (int) $db->loadResult(); - return JAccess::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. + return AccessRules::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. } // try again elseif ($try) { $try = explode('.',$component); $result = $this->getDefaultAssetValues($try[0], false); - if ($result instanceof JAccessRules) + if ($result instanceof AccessRules) { if (isset($try[1])) { @@ -260,7 +301,7 @@ class SermondistributorTablePreacher extends Table else { // clear the value since we inherit - $rule = array(); + $rule = []; } } // check if there are any view values remaining @@ -268,8 +309,8 @@ class SermondistributorTablePreacher extends Table { $_result = json_encode($_result); $_result = array($_result); - // Instantiate and return the JAccessRules object for the asset rules. - $rules = new JAccessRules; + // Instantiate and return the AccessRules object for the asset rules. + $rules = new AccessRules; $rules->mergeCollection($_result); return $rules; @@ -278,50 +319,63 @@ class SermondistributorTablePreacher extends Table return $result; } } - return JAccess::getAssetRules(0); + return AccessRules::getAssetRules(0); + } + + /** + * Get the type alias for the history table + * + * The type alias generally is the internal component name with the + * content type. Ex.: com_content.article + * + * @return string The alias as described above + * + * @since 3.10.0 + */ + public function getTypeAlias() + { + return $this->typeAlias; } /** * Method to compute the default name of the asset. - * The default name is in the form 'table_name.id' + * The default name is in the form table_name.id * where id is the value of the primary key of the table. * - * @return string - * @since 2.5 + * @return string + * + * @since 1.7.0 */ protected function _getAssetName() { $k = $this->_tbl_key; - return 'com_sermondistributor.preacher.'.(int) $this->$k; + + return $this->getTypeAlias() . '.' . (int) $this->$k; } /** - * Method to return the title to use for the asset table. + * Method to get the parent asset under which to register this one. * - * @return string - * @since 2.5 - */ - protected function _getAssetTitle() - { - if (isset($this->title)) - { - return $this->title; - } - return ''; - } - - /** - * Get the parent asset id for the record + * By default, all assets are registered to the ROOT node with ID, which will default to 1 if none exists. + * An extended class can define a table and ID to lookup. If the asset does not exist it will be created. * - * @return int - * @since 2.5 + * @param Table $table A Table object for the asset parent. + * @param integer $id Id to look up + * + * @return integer + * + * @since 1.7.0 */ - protected function _getAssetParentId(JTable $table = NULL, $id = NULL) + protected function _getAssetParentId(Table $table = null, $id = null) { - $asset = JTable::getInstance('Asset'); - $asset->loadByName('com_sermondistributor'); + /** @var Asset $assets */ + $assets = self::getInstance('Asset', 'JTable', ['dbo' => $this->getDbo()]); + $rootId = $assets->getRootId(); - return $asset->id; + // load the sermondistributor asset + $assets->loadByName('com_sermondistributor'); + + return $assets->id ?? $rootId ?? 1; } /** @@ -337,14 +391,13 @@ class SermondistributorTablePreacher extends Table $this->alias = $this->name; } - $this->alias = JApplicationHelper::stringURLSafe($this->alias); + $this->alias = ApplicationHelper::stringURLSafe($this->alias); if (trim(str_replace('-', '', $this->alias)) == '') { - $this->alias = JFactory::getDate()->format('Y-m-d-H-i-s'); + $this->alias = Factory::getDate()->format('Y-m-d-H-i-s'); } return $this->alias; } - } diff --git a/admin/tables/series.php b/admin/src/Table/SeriesTable.php similarity index 54% rename from admin/tables/series.php rename to admin/src/Table/SeriesTable.php index 1e8ac8a8..452716ae 100644 --- a/admin/tables/series.php +++ b/admin/src/Table/SeriesTable.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage series.php + @subpackage SeriesTable.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,84 +21,108 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Table; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; use Joomla\CMS\Table\Table; +use Joomla\CMS\Language\Text; +use Joomla\CMS\String\PunycodeHelper; +use Joomla\CMS\Access\Access as AccessRules; +use Joomla\CMS\Access\Rules; +use Joomla\CMS\Tag\TaggableTableInterface; +use Joomla\CMS\Tag\TaggableTableTrait; +use Joomla\CMS\User\CurrentUserInterface; +use Joomla\CMS\User\CurrentUserTrait; +use Joomla\CMS\Versioning\VersionableTableInterface; +use Joomla\CMS\Application\ApplicationHelper; +use Joomla\Database\DatabaseInterface; use Joomla\Registry\Registry; +use Joomla\Database\DatabaseDriver; +use Joomla\Event\DispatcherInterface; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Series_list Table class + * + * @since 1.6 */ -class SermondistributorTableSeries extends Table +class SeriesTable extends Table implements VersionableTableInterface, TaggableTableInterface, CurrentUserInterface { - /** - * Ensure the params and metadata in json encoded in the bind method - * - * @var array - * @since 3.3 - */ - protected $_jsonEncode = array('params', 'metadata'); - + use TaggableTableTrait; + use CurrentUserTrait; + /** * Constructor * + * @param DatabaseDriver $db Database connector object + * @param ?DispatcherInterface $dispatcher Event dispatcher for this table + * * @param object Database connector object + * @since 4.0 */ - function __construct(&$db) + function __construct(DatabaseDriver $db, ?DispatcherInterface $dispatcher = null) { - parent::__construct('#__sermondistributor_series', 'id', $db); + // The type alias generally is the internal component name with the + // content type. Ex.: com_content.article + $this->typeAlias = 'com_sermondistributor.series'; - // Adding History Options - JTableObserverContenthistory::createObserver($this, array('typeAlias' => 'com_sermondistributor.series')); - } - + // Ensure the params and metadata in json encoded in the bind method + $this->_jsonEncode = ['params', 'metadata']; + + // Indicates that columns fully support the NULL value in the database + // $this->_supportNullValue = true; // hmmm will keep an eye on this ;) + + parent::__construct('#__sermondistributor_series', 'id', $db, $dispatcher); + } + + /** + * Method to bind an associative array or object to the Table instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param array|object $src An associative array or object to bind to the Table instance. + * @param array|string $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @since 1.7.0 + * @throws \InvalidArgumentException + */ public function bind($array, $ignore = '') { - - if (isset($array['params']) && is_array($array['params'])) + // Bind the rules. + if (isset($array['rules']) && is_array($array['rules'])) { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = (string) $registry; + $rules = new AccessRules($array['rules']); + $this->setRules($rules); } - if (isset($array['metadata']) && is_array($array['metadata'])) - { - $registry = new JRegistry; - $registry->loadArray($array['metadata']); - $array['metadata'] = (string) $registry; - } - - // Bind the rules. - if (isset($array['rules']) && is_array($array['rules'])) - { - $rules = new JAccessRules($array['rules']); - $this->setRules($rules); - } return parent::bind($array, $ignore); } - + /** * Overload the store method for the Series table. * - * @param boolean Toggle whether null values should be updated. + * @param boolean Toggle whether null values should be updated. + * * @return boolean True on success, false on failure. * @since 1.6 */ public function store($updateNulls = false) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); + $date = Factory::getDate()->toSql(); + $userId = $this->getCurrentUser()->id; if ($this->id) { // Existing item - $this->modified = $date->toSql(); - $this->modified_by = $user->get('id'); + $this->modified = $date; + $this->modified_by = $userId; } else { @@ -106,65 +130,82 @@ class SermondistributorTableSeries extends Table // so we don't touch either of these if they are set. if (!(int) $this->created) { - $this->created = $date->toSql(); + $this->created = $date; } if (empty($this->created_by)) { - $this->created_by = $user->get('id'); + $this->created_by = $userId; } } - + if (isset($this->alias)) { // Verify that the alias is unique - $table = JTable::getInstance('series', 'SermondistributorTable'); + $table = new self($this->getDbo(), $this->getDispatcher()); - if ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + if ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { - $this->setError(JText::_('COM_SERMONDISTRIBUTOR_SERIES_ERROR_UNIQUE_ALIAS')); + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_SERIES_ERROR_UNIQUE_ALIAS')); + + if ($table->published === -2) + { + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_SERIES_ERROR_UNIQUE_ALIAS_TRASHED')); + } + return false; } } - + if (isset($this->url)) { // Convert IDN urls to punycode - $this->url = JStringPunycode::urlToPunycode($this->url); + $this->url = PunycodeHelper::urlToPunycode($this->url); } + if (isset($this->website)) { // Convert IDN urls to punycode - $this->website = JStringPunycode::urlToPunycode($this->website); + $this->website = PunycodeHelper::urlToPunycode($this->website); } return parent::store($updateNulls); } - + /** * Overloaded check method to ensure data integrity. * * @return boolean True on success. + * + * @see \Joomla\CMS\Table\Table::check + * @since 1.5 */ public function check() { + try { + parent::check(); + } catch (\Exception $e) { + $this->setError($e->getMessage()); + return false; + } + if (isset($this->alias)) { // Generate a valid alias $this->generateAlias(); - - $table = JTable::getInstance('series', 'sermondistributorTable'); - while ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + $table = new self($this->getDbo(), $this->getDispatcher()); + + while ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { $this->alias = StringHelper::increment($this->alias, 'dash'); } } - + /* * Clean up keywords -- eliminate extra spaces between phrases * and cr (\r) and lf (\n) characters from string. * Only process if not empty. - */ + */ if (!empty($this->metakey)) { // Array of characters to remove. @@ -175,7 +216,7 @@ class SermondistributorTableSeries extends Table // Create array using commas as delimiter. $keys = explode(',', $after_clean); - $clean_keys = array(); + $clean_keys = []; foreach ($keys as $key) { @@ -198,13 +239,13 @@ class SermondistributorTableSeries extends Table $this->metadesc = StringHelper::str_ireplace($bad_characters, "", $this->metadesc); } - // If we don't have any access rules set at this point just use an empty JAccessRules class + // If we don't have any access rules set at this point just use an empty AccessRules class if (!$this->getRules()) { $rules = $this->getDefaultAssetValues('com_sermondistributor.series.'.$this->id); $this->setRules($rules); } - + // Set ordering if ($this->published < 0) { @@ -220,12 +261,12 @@ class SermondistributorTableSeries extends Table * * @param $string $component The component asset name to search for * - * @return JAccessRules The JAccessRules object for the asset + * @return AccessRules The AccessRules object for the asset */ protected function getDefaultAssetValues($component, $try = true) { // Need to find the asset id by the name of the component. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(DatabaseInterface::class); $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__assets')) @@ -236,14 +277,14 @@ class SermondistributorTableSeries extends Table { // asset already set so use saved rules $assetId = (int) $db->loadResult(); - return JAccess::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. + return AccessRules::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. } // try again elseif ($try) { $try = explode('.',$component); $result = $this->getDefaultAssetValues($try[0], false); - if ($result instanceof JAccessRules) + if ($result instanceof AccessRules) { if (isset($try[1])) { @@ -260,7 +301,7 @@ class SermondistributorTableSeries extends Table else { // clear the value since we inherit - $rule = array(); + $rule = []; } } // check if there are any view values remaining @@ -268,8 +309,8 @@ class SermondistributorTableSeries extends Table { $_result = json_encode($_result); $_result = array($_result); - // Instantiate and return the JAccessRules object for the asset rules. - $rules = new JAccessRules; + // Instantiate and return the AccessRules object for the asset rules. + $rules = new AccessRules; $rules->mergeCollection($_result); return $rules; @@ -278,50 +319,63 @@ class SermondistributorTableSeries extends Table return $result; } } - return JAccess::getAssetRules(0); + return AccessRules::getAssetRules(0); + } + + /** + * Get the type alias for the history table + * + * The type alias generally is the internal component name with the + * content type. Ex.: com_content.article + * + * @return string The alias as described above + * + * @since 3.10.0 + */ + public function getTypeAlias() + { + return $this->typeAlias; } /** * Method to compute the default name of the asset. - * The default name is in the form 'table_name.id' + * The default name is in the form table_name.id * where id is the value of the primary key of the table. * - * @return string - * @since 2.5 + * @return string + * + * @since 1.7.0 */ protected function _getAssetName() { $k = $this->_tbl_key; - return 'com_sermondistributor.series.'.(int) $this->$k; + + return $this->getTypeAlias() . '.' . (int) $this->$k; } /** - * Method to return the title to use for the asset table. + * Method to get the parent asset under which to register this one. * - * @return string - * @since 2.5 - */ - protected function _getAssetTitle() - { - if (isset($this->title)) - { - return $this->title; - } - return ''; - } - - /** - * Get the parent asset id for the record + * By default, all assets are registered to the ROOT node with ID, which will default to 1 if none exists. + * An extended class can define a table and ID to lookup. If the asset does not exist it will be created. * - * @return int - * @since 2.5 + * @param Table $table A Table object for the asset parent. + * @param integer $id Id to look up + * + * @return integer + * + * @since 1.7.0 */ - protected function _getAssetParentId(JTable $table = NULL, $id = NULL) + protected function _getAssetParentId(Table $table = null, $id = null) { - $asset = JTable::getInstance('Asset'); - $asset->loadByName('com_sermondistributor'); + /** @var Asset $assets */ + $assets = self::getInstance('Asset', 'JTable', ['dbo' => $this->getDbo()]); + $rootId = $assets->getRootId(); - return $asset->id; + // load the sermondistributor asset + $assets->loadByName('com_sermondistributor'); + + return $assets->id ?? $rootId ?? 1; } /** @@ -337,14 +391,13 @@ class SermondistributorTableSeries extends Table $this->alias = $this->name; } - $this->alias = JApplicationHelper::stringURLSafe($this->alias); + $this->alias = ApplicationHelper::stringURLSafe($this->alias); if (trim(str_replace('-', '', $this->alias)) == '') { - $this->alias = JFactory::getDate()->format('Y-m-d-H-i-s'); + $this->alias = Factory::getDate()->format('Y-m-d-H-i-s'); } return $this->alias; } - } diff --git a/admin/tables/sermon.php b/admin/src/Table/SermonTable.php similarity index 54% rename from admin/tables/sermon.php rename to admin/src/Table/SermonTable.php index e22fcdc2..fd5c690b 100644 --- a/admin/tables/sermon.php +++ b/admin/src/Table/SermonTable.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage sermon.php + @subpackage SermonTable.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,87 +21,108 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Table; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; use Joomla\CMS\Table\Table; +use Joomla\CMS\Language\Text; +use Joomla\CMS\String\PunycodeHelper; +use Joomla\CMS\Access\Access as AccessRules; +use Joomla\CMS\Access\Rules; +use Joomla\CMS\Tag\TaggableTableInterface; +use Joomla\CMS\Tag\TaggableTableTrait; +use Joomla\CMS\User\CurrentUserInterface; +use Joomla\CMS\User\CurrentUserTrait; +use Joomla\CMS\Versioning\VersionableTableInterface; +use Joomla\CMS\Application\ApplicationHelper; +use Joomla\Database\DatabaseInterface; use Joomla\Registry\Registry; +use Joomla\Database\DatabaseDriver; +use Joomla\Event\DispatcherInterface; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Sermons Table class + * + * @since 1.6 */ -class SermondistributorTableSermon extends Table +class SermonTable extends Table implements VersionableTableInterface, TaggableTableInterface, CurrentUserInterface { - /** - * Ensure the params and metadata in json encoded in the bind method - * - * @var array - * @since 3.3 - */ - protected $_jsonEncode = array('params', 'metadata'); - + use TaggableTableTrait; + use CurrentUserTrait; + /** * Constructor * + * @param DatabaseDriver $db Database connector object + * @param ?DispatcherInterface $dispatcher Event dispatcher for this table + * * @param object Database connector object + * @since 4.0 */ - function __construct(&$db) + function __construct(DatabaseDriver $db, ?DispatcherInterface $dispatcher = null) { - parent::__construct('#__sermondistributor_sermon', 'id', $db); + // The type alias generally is the internal component name with the + // content type. Ex.: com_content.article + $this->typeAlias = 'com_sermondistributor.sermon'; - // Adding Tag Options - JTableObserverTags::createObserver($this, array('typeAlias' => 'com_sermondistributor.sermon')); + // Ensure the params and metadata in json encoded in the bind method + $this->_jsonEncode = ['params', 'metadata']; - // Adding History Options - JTableObserverContenthistory::createObserver($this, array('typeAlias' => 'com_sermondistributor.sermon')); - } - + // Indicates that columns fully support the NULL value in the database + // $this->_supportNullValue = true; // hmmm will keep an eye on this ;) + + parent::__construct('#__sermondistributor_sermon', 'id', $db, $dispatcher); + } + + /** + * Method to bind an associative array or object to the Table instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param array|object $src An associative array or object to bind to the Table instance. + * @param array|string $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @since 1.7.0 + * @throws \InvalidArgumentException + */ public function bind($array, $ignore = '') { - - if (isset($array['params']) && is_array($array['params'])) + // Bind the rules. + if (isset($array['rules']) && is_array($array['rules'])) { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = (string) $registry; + $rules = new AccessRules($array['rules']); + $this->setRules($rules); } - if (isset($array['metadata']) && is_array($array['metadata'])) - { - $registry = new JRegistry; - $registry->loadArray($array['metadata']); - $array['metadata'] = (string) $registry; - } - - // Bind the rules. - if (isset($array['rules']) && is_array($array['rules'])) - { - $rules = new JAccessRules($array['rules']); - $this->setRules($rules); - } return parent::bind($array, $ignore); } - + /** * Overload the store method for the Sermon table. * - * @param boolean Toggle whether null values should be updated. + * @param boolean Toggle whether null values should be updated. + * * @return boolean True on success, false on failure. * @since 1.6 */ public function store($updateNulls = false) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); + $date = Factory::getDate()->toSql(); + $userId = $this->getCurrentUser()->id; if ($this->id) { // Existing item - $this->modified = $date->toSql(); - $this->modified_by = $user->get('id'); + $this->modified = $date; + $this->modified_by = $userId; } else { @@ -109,65 +130,82 @@ class SermondistributorTableSermon extends Table // so we don't touch either of these if they are set. if (!(int) $this->created) { - $this->created = $date->toSql(); + $this->created = $date; } if (empty($this->created_by)) { - $this->created_by = $user->get('id'); + $this->created_by = $userId; } } - + if (isset($this->alias)) { // Verify that the alias is unique - $table = JTable::getInstance('sermon', 'SermondistributorTable'); + $table = new self($this->getDbo(), $this->getDispatcher()); - if ($table->load(array('alias' => $this->alias, 'catid' => $this->catid)) && ($table->id != $this->id || $this->id == 0)) + if ($table->load(['alias' => $this->alias, 'catid' => $this->catid]) && ($table->id != $this->id || $this->id == 0)) { - $this->setError(JText::_('COM_SERMONDISTRIBUTOR_SERMON_ERROR_UNIQUE_ALIAS')); + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_SERMON_ERROR_UNIQUE_ALIAS')); + + if ($table->published === -2) + { + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_SERMON_ERROR_UNIQUE_ALIAS_TRASHED')); + } + return false; } } - + if (isset($this->url)) { // Convert IDN urls to punycode - $this->url = JStringPunycode::urlToPunycode($this->url); + $this->url = PunycodeHelper::urlToPunycode($this->url); } + if (isset($this->website)) { // Convert IDN urls to punycode - $this->website = JStringPunycode::urlToPunycode($this->website); + $this->website = PunycodeHelper::urlToPunycode($this->website); } return parent::store($updateNulls); } - + /** * Overloaded check method to ensure data integrity. * * @return boolean True on success. + * + * @see \Joomla\CMS\Table\Table::check + * @since 1.5 */ public function check() { + try { + parent::check(); + } catch (\Exception $e) { + $this->setError($e->getMessage()); + return false; + } + if (isset($this->alias)) { // Generate a valid alias $this->generateAlias(); - - $table = JTable::getInstance('sermon', 'sermondistributorTable'); - while ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + $table = new self($this->getDbo(), $this->getDispatcher()); + + while ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { $this->alias = StringHelper::increment($this->alias, 'dash'); } } - + /* * Clean up keywords -- eliminate extra spaces between phrases * and cr (\r) and lf (\n) characters from string. * Only process if not empty. - */ + */ if (!empty($this->metakey)) { // Array of characters to remove. @@ -178,7 +216,7 @@ class SermondistributorTableSermon extends Table // Create array using commas as delimiter. $keys = explode(',', $after_clean); - $clean_keys = array(); + $clean_keys = []; foreach ($keys as $key) { @@ -201,13 +239,13 @@ class SermondistributorTableSermon extends Table $this->metadesc = StringHelper::str_ireplace($bad_characters, "", $this->metadesc); } - // If we don't have any access rules set at this point just use an empty JAccessRules class + // If we don't have any access rules set at this point just use an empty AccessRules class if (!$this->getRules()) { $rules = $this->getDefaultAssetValues('com_sermondistributor.sermon.'.$this->id); $this->setRules($rules); } - + // Set ordering if ($this->published < 0) { @@ -223,12 +261,12 @@ class SermondistributorTableSermon extends Table * * @param $string $component The component asset name to search for * - * @return JAccessRules The JAccessRules object for the asset + * @return AccessRules The AccessRules object for the asset */ protected function getDefaultAssetValues($component, $try = true) { // Need to find the asset id by the name of the component. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(DatabaseInterface::class); $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__assets')) @@ -239,14 +277,14 @@ class SermondistributorTableSermon extends Table { // asset already set so use saved rules $assetId = (int) $db->loadResult(); - return JAccess::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. + return AccessRules::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. } // try again elseif ($try) { $try = explode('.',$component); $result = $this->getDefaultAssetValues($try[0], false); - if ($result instanceof JAccessRules) + if ($result instanceof AccessRules) { if (isset($try[1])) { @@ -263,7 +301,7 @@ class SermondistributorTableSermon extends Table else { // clear the value since we inherit - $rule = array(); + $rule = []; } } // check if there are any view values remaining @@ -271,8 +309,8 @@ class SermondistributorTableSermon extends Table { $_result = json_encode($_result); $_result = array($_result); - // Instantiate and return the JAccessRules object for the asset rules. - $rules = new JAccessRules; + // Instantiate and return the AccessRules object for the asset rules. + $rules = new AccessRules; $rules->mergeCollection($_result); return $rules; @@ -281,50 +319,63 @@ class SermondistributorTableSermon extends Table return $result; } } - return JAccess::getAssetRules(0); + return AccessRules::getAssetRules(0); + } + + /** + * Get the type alias for the history table + * + * The type alias generally is the internal component name with the + * content type. Ex.: com_content.article + * + * @return string The alias as described above + * + * @since 3.10.0 + */ + public function getTypeAlias() + { + return $this->typeAlias; } /** * Method to compute the default name of the asset. - * The default name is in the form 'table_name.id' + * The default name is in the form table_name.id * where id is the value of the primary key of the table. * - * @return string - * @since 2.5 + * @return string + * + * @since 1.7.0 */ protected function _getAssetName() { $k = $this->_tbl_key; - return 'com_sermondistributor.sermon.'.(int) $this->$k; + + return $this->getTypeAlias() . '.' . (int) $this->$k; } /** - * Method to return the title to use for the asset table. + * Method to get the parent asset under which to register this one. * - * @return string - * @since 2.5 - */ - protected function _getAssetTitle() - { - if (isset($this->title)) - { - return $this->title; - } - return ''; - } - - /** - * Get the parent asset id for the record + * By default, all assets are registered to the ROOT node with ID, which will default to 1 if none exists. + * An extended class can define a table and ID to lookup. If the asset does not exist it will be created. * - * @return int - * @since 2.5 + * @param Table $table A Table object for the asset parent. + * @param integer $id Id to look up + * + * @return integer + * + * @since 1.7.0 */ - protected function _getAssetParentId(JTable $table = NULL, $id = NULL) + protected function _getAssetParentId(Table $table = null, $id = null) { - $asset = JTable::getInstance('Asset'); - $asset->loadByName('com_sermondistributor'); + /** @var Asset $assets */ + $assets = self::getInstance('Asset', 'JTable', ['dbo' => $this->getDbo()]); + $rootId = $assets->getRootId(); - return $asset->id; + // load the sermondistributor asset + $assets->loadByName('com_sermondistributor'); + + return $assets->id ?? $rootId ?? 1; } /** @@ -340,14 +391,13 @@ class SermondistributorTableSermon extends Table $this->alias = $this->name; } - $this->alias = JApplicationHelper::stringURLSafe($this->alias); + $this->alias = ApplicationHelper::stringURLSafe($this->alias); if (trim(str_replace('-', '', $this->alias)) == '') { - $this->alias = JFactory::getDate()->format('Y-m-d-H-i-s'); + $this->alias = Factory::getDate()->format('Y-m-d-H-i-s'); } return $this->alias; } - } diff --git a/admin/tables/statistic.php b/admin/src/Table/StatisticTable.php similarity index 54% rename from admin/tables/statistic.php rename to admin/src/Table/StatisticTable.php index 981cbaae..e059e126 100644 --- a/admin/tables/statistic.php +++ b/admin/src/Table/StatisticTable.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage statistic.php + @subpackage StatisticTable.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,84 +21,108 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\Table; -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); - +use Joomla\CMS\Factory; use Joomla\CMS\Table\Table; +use Joomla\CMS\Language\Text; +use Joomla\CMS\String\PunycodeHelper; +use Joomla\CMS\Access\Access as AccessRules; +use Joomla\CMS\Access\Rules; +use Joomla\CMS\Tag\TaggableTableInterface; +use Joomla\CMS\Tag\TaggableTableTrait; +use Joomla\CMS\User\CurrentUserInterface; +use Joomla\CMS\User\CurrentUserTrait; +use Joomla\CMS\Versioning\VersionableTableInterface; +use Joomla\CMS\Application\ApplicationHelper; +use Joomla\Database\DatabaseInterface; use Joomla\Registry\Registry; +use Joomla\Database\DatabaseDriver; +use Joomla\Event\DispatcherInterface; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +// No direct access to this file +\defined('_JEXEC') or die; /** * Statistics Table class + * + * @since 1.6 */ -class SermondistributorTableStatistic extends Table +class StatisticTable extends Table implements VersionableTableInterface, TaggableTableInterface, CurrentUserInterface { - /** - * Ensure the params and metadata in json encoded in the bind method - * - * @var array - * @since 3.3 - */ - protected $_jsonEncode = array('params', 'metadata'); - + use TaggableTableTrait; + use CurrentUserTrait; + /** * Constructor * + * @param DatabaseDriver $db Database connector object + * @param ?DispatcherInterface $dispatcher Event dispatcher for this table + * * @param object Database connector object + * @since 4.0 */ - function __construct(&$db) + function __construct(DatabaseDriver $db, ?DispatcherInterface $dispatcher = null) { - parent::__construct('#__sermondistributor_statistic', 'id', $db); + // The type alias generally is the internal component name with the + // content type. Ex.: com_content.article + $this->typeAlias = 'com_sermondistributor.statistic'; - // Adding History Options - JTableObserverContenthistory::createObserver($this, array('typeAlias' => 'com_sermondistributor.statistic')); - } - + // Ensure the params and metadata in json encoded in the bind method + $this->_jsonEncode = ['params', 'metadata']; + + // Indicates that columns fully support the NULL value in the database + // $this->_supportNullValue = true; // hmmm will keep an eye on this ;) + + parent::__construct('#__sermondistributor_statistic', 'id', $db, $dispatcher); + } + + /** + * Method to bind an associative array or object to the Table instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param array|object $src An associative array or object to bind to the Table instance. + * @param array|string $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @since 1.7.0 + * @throws \InvalidArgumentException + */ public function bind($array, $ignore = '') { - - if (isset($array['params']) && is_array($array['params'])) + // Bind the rules. + if (isset($array['rules']) && is_array($array['rules'])) { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = (string) $registry; + $rules = new AccessRules($array['rules']); + $this->setRules($rules); } - if (isset($array['metadata']) && is_array($array['metadata'])) - { - $registry = new JRegistry; - $registry->loadArray($array['metadata']); - $array['metadata'] = (string) $registry; - } - - // Bind the rules. - if (isset($array['rules']) && is_array($array['rules'])) - { - $rules = new JAccessRules($array['rules']); - $this->setRules($rules); - } return parent::bind($array, $ignore); } - + /** * Overload the store method for the Statistic table. * - * @param boolean Toggle whether null values should be updated. + * @param boolean Toggle whether null values should be updated. + * * @return boolean True on success, false on failure. * @since 1.6 */ public function store($updateNulls = false) { - $date = JFactory::getDate(); - $user = JFactory::getUser(); + $date = Factory::getDate()->toSql(); + $userId = $this->getCurrentUser()->id; if ($this->id) { // Existing item - $this->modified = $date->toSql(); - $this->modified_by = $user->get('id'); + $this->modified = $date; + $this->modified_by = $userId; } else { @@ -106,65 +130,82 @@ class SermondistributorTableStatistic extends Table // so we don't touch either of these if they are set. if (!(int) $this->created) { - $this->created = $date->toSql(); + $this->created = $date; } if (empty($this->created_by)) { - $this->created_by = $user->get('id'); + $this->created_by = $userId; } } - + if (isset($this->alias)) { // Verify that the alias is unique - $table = JTable::getInstance('statistic', 'SermondistributorTable'); + $table = new self($this->getDbo(), $this->getDispatcher()); - if ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + if ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { - $this->setError(JText::_('COM_SERMONDISTRIBUTOR_STATISTIC_ERROR_UNIQUE_ALIAS')); + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_STATISTIC_ERROR_UNIQUE_ALIAS')); + + if ($table->published === -2) + { + $this->setError(Text::_('COM_SERMONDISTRIBUTOR_STATISTIC_ERROR_UNIQUE_ALIAS_TRASHED')); + } + return false; } } - + if (isset($this->url)) { // Convert IDN urls to punycode - $this->url = JStringPunycode::urlToPunycode($this->url); + $this->url = PunycodeHelper::urlToPunycode($this->url); } + if (isset($this->website)) { // Convert IDN urls to punycode - $this->website = JStringPunycode::urlToPunycode($this->website); + $this->website = PunycodeHelper::urlToPunycode($this->website); } return parent::store($updateNulls); } - + /** * Overloaded check method to ensure data integrity. * * @return boolean True on success. + * + * @see \Joomla\CMS\Table\Table::check + * @since 1.5 */ public function check() { + try { + parent::check(); + } catch (\Exception $e) { + $this->setError($e->getMessage()); + return false; + } + if (isset($this->alias)) { // Generate a valid alias $this->generateAlias(); - - $table = JTable::getInstance('statistic', 'sermondistributorTable'); - while ($table->load(array('alias' => $this->alias)) && ($table->id != $this->id || $this->id == 0)) + $table = new self($this->getDbo(), $this->getDispatcher()); + + while ($table->load(['alias' => $this->alias]) && ($table->id != $this->id || $this->id == 0)) { $this->alias = StringHelper::increment($this->alias, 'dash'); } } - + /* * Clean up keywords -- eliminate extra spaces between phrases * and cr (\r) and lf (\n) characters from string. * Only process if not empty. - */ + */ if (!empty($this->metakey)) { // Array of characters to remove. @@ -175,7 +216,7 @@ class SermondistributorTableStatistic extends Table // Create array using commas as delimiter. $keys = explode(',', $after_clean); - $clean_keys = array(); + $clean_keys = []; foreach ($keys as $key) { @@ -198,13 +239,13 @@ class SermondistributorTableStatistic extends Table $this->metadesc = StringHelper::str_ireplace($bad_characters, "", $this->metadesc); } - // If we don't have any access rules set at this point just use an empty JAccessRules class + // If we don't have any access rules set at this point just use an empty AccessRules class if (!$this->getRules()) { $rules = $this->getDefaultAssetValues('com_sermondistributor.statistic.'.$this->id); $this->setRules($rules); } - + // Set ordering if ($this->published < 0) { @@ -220,12 +261,12 @@ class SermondistributorTableStatistic extends Table * * @param $string $component The component asset name to search for * - * @return JAccessRules The JAccessRules object for the asset + * @return AccessRules The AccessRules object for the asset */ protected function getDefaultAssetValues($component, $try = true) { // Need to find the asset id by the name of the component. - $db = JFactory::getDbo(); + $db = Factory::getContainer()->get(DatabaseInterface::class); $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__assets')) @@ -236,14 +277,14 @@ class SermondistributorTableStatistic extends Table { // asset already set so use saved rules $assetId = (int) $db->loadResult(); - return JAccess::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. + return AccessRules::getAssetRules($assetId); // (TODO) instead of keeping inherited Allowed it becomes Allowed. } // try again elseif ($try) { $try = explode('.',$component); $result = $this->getDefaultAssetValues($try[0], false); - if ($result instanceof JAccessRules) + if ($result instanceof AccessRules) { if (isset($try[1])) { @@ -260,7 +301,7 @@ class SermondistributorTableStatistic extends Table else { // clear the value since we inherit - $rule = array(); + $rule = []; } } // check if there are any view values remaining @@ -268,8 +309,8 @@ class SermondistributorTableStatistic extends Table { $_result = json_encode($_result); $_result = array($_result); - // Instantiate and return the JAccessRules object for the asset rules. - $rules = new JAccessRules; + // Instantiate and return the AccessRules object for the asset rules. + $rules = new AccessRules; $rules->mergeCollection($_result); return $rules; @@ -278,50 +319,63 @@ class SermondistributorTableStatistic extends Table return $result; } } - return JAccess::getAssetRules(0); + return AccessRules::getAssetRules(0); + } + + /** + * Get the type alias for the history table + * + * The type alias generally is the internal component name with the + * content type. Ex.: com_content.article + * + * @return string The alias as described above + * + * @since 3.10.0 + */ + public function getTypeAlias() + { + return $this->typeAlias; } /** * Method to compute the default name of the asset. - * The default name is in the form 'table_name.id' + * The default name is in the form table_name.id * where id is the value of the primary key of the table. * - * @return string - * @since 2.5 + * @return string + * + * @since 1.7.0 */ protected function _getAssetName() { $k = $this->_tbl_key; - return 'com_sermondistributor.statistic.'.(int) $this->$k; + + return $this->getTypeAlias() . '.' . (int) $this->$k; } /** - * Method to return the title to use for the asset table. + * Method to get the parent asset under which to register this one. * - * @return string - * @since 2.5 - */ - protected function _getAssetTitle() - { - if (isset($this->title)) - { - return $this->title; - } - return ''; - } - - /** - * Get the parent asset id for the record + * By default, all assets are registered to the ROOT node with ID, which will default to 1 if none exists. + * An extended class can define a table and ID to lookup. If the asset does not exist it will be created. * - * @return int - * @since 2.5 + * @param Table $table A Table object for the asset parent. + * @param integer $id Id to look up + * + * @return integer + * + * @since 1.7.0 */ - protected function _getAssetParentId(JTable $table = NULL, $id = NULL) + protected function _getAssetParentId(Table $table = null, $id = null) { - $asset = JTable::getInstance('Asset'); - $asset->loadByName('com_sermondistributor'); + /** @var Asset $assets */ + $assets = self::getInstance('Asset', 'JTable', ['dbo' => $this->getDbo()]); + $rootId = $assets->getRootId(); - return $asset->id; + // load the sermondistributor asset + $assets->loadByName('com_sermondistributor'); + + return $assets->id ?? $rootId ?? 1; } /** @@ -333,5 +387,4 @@ class SermondistributorTableStatistic extends Table { return false; } - } diff --git a/admin/views/external_sources/tmpl/index.html b/admin/src/Table/index.html similarity index 100% rename from admin/views/external_sources/tmpl/index.html rename to admin/src/Table/index.html diff --git a/admin/src/View/External_source/HtmlView.php b/admin/src/View/External_source/HtmlView.php new file mode 100644 index 00000000..979663a3 --- /dev/null +++ b/admin/src/View/External_source/HtmlView.php @@ -0,0 +1,253 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\External_source; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * External_source Html View class + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * External_source view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // set params + $this->params = ComponentHelper::getParams('com_sermondistributor'); + // Assign the variables + $this->form = $this->get('Form'); + $this->item = $this->get('Item'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->state = $this->get('State'); + // get action permissions + $this->canDo = SermondistributorHelper::getActions('external_source', $this->item); + // get input + $jinput = Factory::getApplication()->input; + $this->ref = $jinput->get('ref', 0, 'word'); + $this->refid = $jinput->get('refid', 0, 'int'); + $return = $jinput->get('return', null, 'base64'); + // set the referral string + $this->referral = ''; + if ($this->refid && $this->ref) + { + // return to the item that referred to this item + $this->referral = '&ref=' . (string) $this->ref . '&refid=' . (int) $this->refid; + } + elseif($this->ref) + { + // return to the list view that referred to this item + $this->referral = '&ref=' . (string) $this->ref; + } + // check return value + if (!is_null($return)) + { + // add the return value + $this->referral .= '&return=' . (string) $return; + } + + // Set the toolbar + $this->addToolBar(); + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + Factory::getApplication()->input->set('hidemainmenu', true); + $user = Factory::getApplication()->getIdentity(); + $userId = $user->id; + $isNew = $this->item->id == 0; + + ToolbarHelper::title( Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_NEW' : 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_EDIT'), 'pencil-2 article-add'); + // Built the actions for new and existing records. + if (StringHelper::check($this->referral)) + { + if ($this->canDo->get('external_source.create') && $isNew) + { + // We can create the record. + ToolbarHelper::save('external_source.save', 'JTOOLBAR_SAVE'); + } + elseif ($this->canDo->get('external_source.edit')) + { + // We can save the record. + ToolbarHelper::save('external_source.save', 'JTOOLBAR_SAVE'); + } + if ($isNew) + { + // Do not creat but cancel. + ToolbarHelper::cancel('external_source.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + // We can close it. + ToolbarHelper::cancel('external_source.cancel', 'JTOOLBAR_CLOSE'); + } + } + else + { + if ($isNew) + { + // For new records, check the create permission. + if ($this->canDo->get('external_source.create')) + { + ToolbarHelper::apply('external_source.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('external_source.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::custom('external_source.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + }; + ToolbarHelper::cancel('external_source.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + if ($this->canDo->get('external_source.edit')) + { + // We can save the new record + ToolbarHelper::apply('external_source.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('external_source.save', 'JTOOLBAR_SAVE'); + // We can save this record, but check the create permission to see + // if we can return to make a new one. + if ($this->canDo->get('external_source.create')) + { + ToolbarHelper::custom('external_source.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + } + } + $canVersion = ($this->canDo->get('core.version') && $this->canDo->get('external_source.version')); + if ($this->state->params->get('save_history', 1) && $this->canDo->get('external_source.edit') && $canVersion) + { + ToolbarHelper::versions('com_sermondistributor.external_source', $this->item->id); + } + if ($this->canDo->get('external_source.create')) + { + ToolbarHelper::custom('external_source.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); + } + if ($this->canDo->get('external_source.clear_local_listing')) + { + // add Clear Local Listing button. + ToolbarHelper::custom('external_source.clearLocalListing', 'delete custom-button-clearlocallisting', '', 'COM_SERMONDISTRIBUTOR_CLEAR_LOCAL_LISTING', false); + } + if ($this->canDo->get('external_source.reset_update_status')) + { + // add Reset Update Status button. + ToolbarHelper::custom('external_source.resetUpdateStatus', 'undo-2 custom-button-resetupdatestatus', '', 'COM_SERMONDISTRIBUTOR_RESET_UPDATE_STATUS', false); + } + ToolbarHelper::cancel('external_source.cancel', 'JTOOLBAR_CLOSE'); + } + } + ToolbarHelper::divider(); + ToolbarHelper::inlinehelp(); + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('external_source'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 30) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $isNew = ($this->item->id < 1); + $this->getDocument()->setTitle(Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_NEW' : 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_EDIT')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // Add Ajax Token + $this->getDocument()->addScriptDeclaration("var token = '" . Session::getFormToken() . "';"); + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } +} diff --git a/admin/views/help_document/tmpl/index.html b/admin/src/View/External_source/index.html similarity index 100% rename from admin/views/help_document/tmpl/index.html rename to admin/src/View/External_source/index.html diff --git a/admin/src/View/External_sources/HtmlView.php b/admin/src/View/External_sources/HtmlView.php new file mode 100644 index 00000000..a04a3141 --- /dev/null +++ b/admin/src/View/External_sources/HtmlView.php @@ -0,0 +1,231 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\External_sources; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor Html View class for the External_sources + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * External_sources view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // Assign data to the view + $this->items = $this->get('Items'); + $this->pagination = $this->get('Pagination'); + $this->state = $this->get('State'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->user ??= Factory::getApplication()->getIdentity(); + // Load the filter form from xml. + $this->filterForm = $this->get('FilterForm'); + // Load the active filters. + $this->activeFilters = $this->get('ActiveFilters'); + // Add the list ordering clause. + $this->listOrder = $this->escape($this->state->get('list.ordering', 'a.id')); + $this->listDirn = $this->escape($this->state->get('list.direction', 'DESC')); + $this->saveOrder = $this->listOrder == 'a.ordering'; + // set the return here value + $this->return_here = urlencode(base64_encode((string) Uri::getInstance())); + // get global action permissions + $this->canDo = SermondistributorHelper::getActions('external_source'); + $this->canEdit = $this->canDo->get('external_source.edit'); + $this->canState = $this->canDo->get('external_source.edit.state'); + $this->canCreate = $this->canDo->get('external_source.create'); + $this->canDelete = $this->canDo->get('external_source.delete'); + $this->canBatch = ($this->canDo->get('external_source.batch') && $this->canDo->get('core.batch')); + + // If we don't have items we load the empty state + if (is_array($this->items) && !count((array) $this->items) && $this->isEmptyState = $this->get('IsEmptyState')) + { + $this->setLayout('emptystate'); + } + + // We don't need toolbar in the modal window. + if ($this->getLayout() !== 'modal') + { + $this->addToolbar(); + } + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES'), 'puzzle'); + + if ($this->canCreate) + { + ToolbarHelper::addNew('external_source.add'); + } + + // Only load if there are items + if (ArrayHelper::check($this->items)) + { + if ($this->canEdit) + { + ToolbarHelper::editList('external_source.edit'); + } + + if ($this->canState) + { + ToolbarHelper::publishList('external_sources.publish'); + ToolbarHelper::unpublishList('external_sources.unpublish'); + ToolbarHelper::archiveList('external_sources.archive'); + + if ($this->canDo->get('core.admin')) + { + ToolbarHelper::checkin('external_sources.checkin'); + } + } + + if ($this->state->get('filter.published') == -2 && ($this->canState && $this->canDelete)) + { + ToolbarHelper::deleteList('', 'external_sources.delete', 'JTOOLBAR_EMPTY_TRASH'); + } + elseif ($this->canState && $this->canDelete) + { + ToolbarHelper::trash('external_sources.trash'); + } + } + + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('external_sources'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + + // add the options comp button + if ($this->canDo->get('core.admin') || $this->canDo->get('core.options')) + { + ToolbarHelper::preferences('com_sermondistributor'); + } + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $this->getDocument()->setTitle(Text::_('COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 50) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Returns an array of fields the table can be sorted by + * + * @return array containing the field name to sort by as the key and display text as value + * @since 1.6 + */ + protected function getSortFields() + { + return array( + 'a.ordering' => Text::_('JGRID_HEADING_ORDERING'), + 'a.published' => Text::_('JSTATUS'), + 'a.description' => Text::_('COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_DESCRIPTION_LABEL'), + 'a.externalsources' => Text::_('COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_EXTERNALSOURCES_LABEL'), + 'a.update_method' => Text::_('COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_UPDATE_METHOD_LABEL'), + 'a.build' => Text::_('COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCE_BUILD_LABEL'), + 'a.id' => Text::_('JGRID_HEADING_ID') + ); + } +} diff --git a/admin/views/help_documents/index.html b/admin/src/View/External_sources/index.html similarity index 100% rename from admin/views/help_documents/index.html rename to admin/src/View/External_sources/index.html diff --git a/admin/views/help_document/view.html.php b/admin/src/View/Help_document/HtmlView.php similarity index 50% rename from admin/views/help_document/view.html.php rename to admin/src/View/Help_document/HtmlView.php index 1d8de090..0d872107 100644 --- a/admin/views/help_document/view.html.php +++ b/admin/src/View/Help_document/HtmlView.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage view.html.php + @subpackage HtmlView.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,34 +21,56 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Help_document; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\View\HtmlView; +\defined('_JEXEC') or die; /** * Help_document Html View class + * + * @since 1.6 */ -class SermondistributorViewHelp_document extends HtmlView +class HtmlView extends BaseHtmlView { /** - * display method of View - * @return void + * Help_document view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 */ public function display($tpl = null) { // set params - $this->params = JComponentHelper::getParams('com_sermondistributor'); + $this->params = ComponentHelper::getParams('com_sermondistributor'); // Assign the variables $this->form = $this->get('Form'); $this->item = $this->get('Item'); - $this->script = $this->get('Script'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); $this->state = $this->get('State'); // get action permissions $this->canDo = SermondistributorHelper::getActions('help_document', $this->item); // get input - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; $this->ref = $jinput->get('ref', 0, 'word'); $this->refid = $jinput->get('refid', 0, 'int'); $return = $jinput->get('return', null, 'base64'); @@ -57,70 +79,73 @@ class SermondistributorViewHelp_document extends HtmlView if ($this->refid && $this->ref) { // return to the item that referred to this item - $this->referral = '&ref=' . (string)$this->ref . '&refid=' . (int)$this->refid; + $this->referral = '&ref=' . (string) $this->ref . '&refid=' . (int) $this->refid; } elseif($this->ref) { // return to the list view that referred to this item - $this->referral = '&ref=' . (string)$this->ref; + $this->referral = '&ref=' . (string) $this->ref; } // check return value if (!is_null($return)) { // add the return value - $this->referral .= '&return=' . (string)$return; + $this->referral .= '&return=' . (string) $return; } // Set the toolbar $this->addToolBar(); - + // Check for errors. if (count($errors = $this->get('Errors'))) { - throw new Exception(implode("\n", $errors), 500); + throw new \Exception(implode("\n", $errors), 500); } + // Set the html view document stuff + $this->_prepareDocument(); + // Display the template parent::display($tpl); - - // Set the document - $this->setDocument(); } /** - * Setting the toolbar + * Add the page title and toolbar. + * + * @return void + * @since 1.6 */ - protected function addToolBar() + protected function addToolbar(): void { - JFactory::getApplication()->input->set('hidemainmenu', true); - $user = JFactory::getUser(); + Factory::getApplication()->input->set('hidemainmenu', true); + $user = Factory::getApplication()->getIdentity(); $userId = $user->id; $isNew = $this->item->id == 0; - JToolbarHelper::title( JText::_($isNew ? 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_NEW' : 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_EDIT'), 'pencil-2 article-add'); + ToolbarHelper::title( Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_NEW' : 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_EDIT'), 'pencil-2 article-add'); // Built the actions for new and existing records. - if (SermondistributorHelper::checkString($this->referral)) + if (StringHelper::check($this->referral)) { if ($this->canDo->get('help_document.create') && $isNew) { // We can create the record. - JToolBarHelper::save('help_document.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::save('help_document.save', 'JTOOLBAR_SAVE'); } elseif ($this->canDo->get('help_document.edit')) { // We can save the record. - JToolBarHelper::save('help_document.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::save('help_document.save', 'JTOOLBAR_SAVE'); } if ($isNew) { // Do not creat but cancel. - JToolBarHelper::cancel('help_document.cancel', 'JTOOLBAR_CANCEL'); + ToolbarHelper::cancel('help_document.cancel', 'JTOOLBAR_CANCEL'); } else { // We can close it. - JToolBarHelper::cancel('help_document.cancel', 'JTOOLBAR_CLOSE'); + ToolbarHelper::cancel('help_document.cancel', 'JTOOLBAR_CLOSE'); } } else @@ -130,81 +155,87 @@ class SermondistributorViewHelp_document extends HtmlView // For new records, check the create permission. if ($this->canDo->get('help_document.create')) { - JToolBarHelper::apply('help_document.apply', 'JTOOLBAR_APPLY'); - JToolBarHelper::save('help_document.save', 'JTOOLBAR_SAVE'); - JToolBarHelper::custom('help_document.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + ToolbarHelper::apply('help_document.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('help_document.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::custom('help_document.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); }; - JToolBarHelper::cancel('help_document.cancel', 'JTOOLBAR_CANCEL'); + ToolbarHelper::cancel('help_document.cancel', 'JTOOLBAR_CANCEL'); } else { if ($this->canDo->get('help_document.edit')) { // We can save the new record - JToolBarHelper::apply('help_document.apply', 'JTOOLBAR_APPLY'); - JToolBarHelper::save('help_document.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::apply('help_document.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('help_document.save', 'JTOOLBAR_SAVE'); // We can save this record, but check the create permission to see // if we can return to make a new one. if ($this->canDo->get('help_document.create')) { - JToolBarHelper::custom('help_document.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + ToolbarHelper::custom('help_document.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); } } $canVersion = ($this->canDo->get('core.version') && $this->canDo->get('help_document.version')); if ($this->state->params->get('save_history', 1) && $this->canDo->get('help_document.edit') && $canVersion) { - JToolbarHelper::versions('com_sermondistributor.help_document', $this->item->id); + ToolbarHelper::versions('com_sermondistributor.help_document', $this->item->id); } if ($this->canDo->get('help_document.create')) { - JToolBarHelper::custom('help_document.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); + ToolbarHelper::custom('help_document.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); } - JToolBarHelper::cancel('help_document.cancel', 'JTOOLBAR_CLOSE'); + ToolbarHelper::cancel('help_document.cancel', 'JTOOLBAR_CLOSE'); } } - JToolbarHelper::divider(); + ToolbarHelper::divider(); + ToolbarHelper::inlinehelp(); // set help url for this view if found $this->help_url = SermondistributorHelper::getHelpUrl('help_document'); - if (SermondistributorHelper::checkString($this->help_url)) + if (StringHelper::check($this->help_url)) { - JToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); } } /** * Escapes a value for output in a view script. * - * @param mixed $var The output to escape. + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. * * @return mixed The escaped value. + * @since 1.6 */ - public function escape($var) + public function escape($var, bool $shorten = true, int $length = 30) { - if(strlen($var) > 30) + if (!is_string($var)) { - // use the helper htmlEscape method instead and shorten the string - return SermondistributorHelper::htmlEscape($var, $this->_charset, true, 30); + return $var; } - // use the helper htmlEscape method instead. - return SermondistributorHelper::htmlEscape($var, $this->_charset); + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); } /** - * Method to set up the document properties + * Prepare some document related stuff. * - * @return void + * @return void + * @since 1.6 */ - protected function setDocument() + protected function _prepareDocument(): void { $isNew = ($this->item->id < 1); - if (!isset($this->document)) + $this->getDocument()->setTitle(Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_NEW' : 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_EDIT')); + // add styles + foreach ($this->styles as $style) { - $this->document = JFactory::getDocument(); + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); } - $this->document->setTitle(JText::_($isNew ? 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_NEW' : 'COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_EDIT')); - $this->document->addStyleSheet(JURI::root() . "administrator/components/com_sermondistributor/assets/css/help_document.css", (SermondistributorHelper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css'); - $this->document->addScript(JURI::root() . $this->script, (SermondistributorHelper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/javascript'); - $this->document->addScript(JURI::root() . "administrator/components/com_sermondistributor/views/help_document/submitbutton.js", (SermondistributorHelper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/javascript'); - JText::script('view not acceptable. Error'); } } diff --git a/admin/views/help_documents/tmpl/index.html b/admin/src/View/Help_document/index.html similarity index 100% rename from admin/views/help_documents/tmpl/index.html rename to admin/src/View/Help_document/index.html diff --git a/admin/src/View/Help_documents/HtmlView.php b/admin/src/View/Help_documents/HtmlView.php new file mode 100644 index 00000000..1bd2bf78 --- /dev/null +++ b/admin/src/View/Help_documents/HtmlView.php @@ -0,0 +1,232 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Help_documents; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor Html View class for the Help_documents + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Help_documents view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // Assign data to the view + $this->items = $this->get('Items'); + $this->pagination = $this->get('Pagination'); + $this->state = $this->get('State'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->user ??= Factory::getApplication()->getIdentity(); + // Load the filter form from xml. + $this->filterForm = $this->get('FilterForm'); + // Load the active filters. + $this->activeFilters = $this->get('ActiveFilters'); + // Add the list ordering clause. + $this->listOrder = $this->escape($this->state->get('list.ordering', 'a.id')); + $this->listDirn = $this->escape($this->state->get('list.direction', 'DESC')); + $this->saveOrder = $this->listOrder == 'a.ordering'; + // set the return here value + $this->return_here = urlencode(base64_encode((string) Uri::getInstance())); + // get global action permissions + $this->canDo = SermondistributorHelper::getActions('help_document'); + $this->canEdit = $this->canDo->get('help_document.edit'); + $this->canState = $this->canDo->get('help_document.edit.state'); + $this->canCreate = $this->canDo->get('help_document.create'); + $this->canDelete = $this->canDo->get('help_document.delete'); + $this->canBatch = ($this->canDo->get('help_document.batch') && $this->canDo->get('core.batch')); + + // If we don't have items we load the empty state + if (is_array($this->items) && !count((array) $this->items) && $this->isEmptyState = $this->get('IsEmptyState')) + { + $this->setLayout('emptystate'); + } + + // We don't need toolbar in the modal window. + if ($this->getLayout() !== 'modal') + { + $this->addToolbar(); + } + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS'), 'support'); + + if ($this->canCreate) + { + ToolbarHelper::addNew('help_document.add'); + } + + // Only load if there are items + if (ArrayHelper::check($this->items)) + { + if ($this->canEdit) + { + ToolbarHelper::editList('help_document.edit'); + } + + if ($this->canState) + { + ToolbarHelper::publishList('help_documents.publish'); + ToolbarHelper::unpublishList('help_documents.unpublish'); + ToolbarHelper::archiveList('help_documents.archive'); + + if ($this->canDo->get('core.admin')) + { + ToolbarHelper::checkin('help_documents.checkin'); + } + } + + if ($this->state->get('filter.published') == -2 && ($this->canState && $this->canDelete)) + { + ToolbarHelper::deleteList('', 'help_documents.delete', 'JTOOLBAR_EMPTY_TRASH'); + } + elseif ($this->canState && $this->canDelete) + { + ToolbarHelper::trash('help_documents.trash'); + } + } + + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('help_documents'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + + // add the options comp button + if ($this->canDo->get('core.admin') || $this->canDo->get('core.options')) + { + ToolbarHelper::preferences('com_sermondistributor'); + } + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $this->getDocument()->setTitle(Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENTS')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 50) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Returns an array of fields the table can be sorted by + * + * @return array containing the field name to sort by as the key and display text as value + * @since 1.6 + */ + protected function getSortFields() + { + return array( + 'a.ordering' => Text::_('JGRID_HEADING_ORDERING'), + 'a.published' => Text::_('JSTATUS'), + 'a.title' => Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_TITLE_LABEL'), + 'a.type' => Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_TYPE_LABEL'), + 'a.location' => Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_LOCATION_LABEL'), + 'h.' => Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_ADMIN_VIEW_LABEL'), + 'i.' => Text::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_SITE_VIEW_LABEL'), + 'a.id' => Text::_('JGRID_HEADING_ID') + ); + } +} diff --git a/admin/views/import/index.html b/admin/src/View/Help_documents/index.html similarity index 100% rename from admin/views/import/index.html rename to admin/src/View/Help_documents/index.html diff --git a/admin/views/import/view.html.php b/admin/src/View/Import/HtmlView.php similarity index 63% rename from admin/views/import/view.html.php rename to admin/src/View/Import/HtmlView.php index 86ffcad7..e36f6067 100644 --- a/admin/views/import/view.html.php +++ b/admin/src/View/Import/HtmlView.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage view.html.php + @subpackage HtmlView.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,16 +21,24 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Import; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Toolbar\ToolbarHelper; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\View\HtmlView; +\defined('_JEXEC') or die; /** * Sermondistributor Import Html View + * + * @since 1.6 */ -class SermondistributorViewImport extends HtmlView +class HtmlView extends BaseHtmlView { protected $headerList; protected $hasPackage = false; @@ -38,47 +46,48 @@ class SermondistributorViewImport extends HtmlView protected $hasHeader = 0; protected $dataType; + /** + * Display the view + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ public function display($tpl = null) - { - if ($this->getLayout() !== 'modal') - { - // Include helper submenu - SermondistributorHelper::addSubmenu('import'); - } - - $paths = new stdClass; + { + $paths = new \StdClass; $paths->first = ''; $state = $this->get('state'); $this->paths = &$paths; $this->state = &$state; - // get global action permissions + // get global action permissions $this->canDo = SermondistributorHelper::getActions('import'); // We don't need toolbar in the modal window. if ($this->getLayout() !== 'modal') { $this->addToolbar(); - $this->sidebar = JHtmlSidebar::render(); } // get the session object - $session = JFactory::getSession(); + $session = Factory::getSession(); // check if it has package - $this->hasPackage = $session->get('hasPackage', false); - $this->dataType = $session->get('dataType', false); + $this->hasPackage = $session->get('hasPackage', false); + $this->dataType = $session->get('dataType', false); if($this->hasPackage && $this->dataType) { - $this->headerList = json_decode($session->get($this->dataType.'_VDM_IMPORTHEADERS', false),true); - $this->headers = SermondistributorHelper::getFileHeaders($this->dataType); + $this->headerList = json_decode($session->get($this->dataType.'_VDM_IMPORTHEADERS', false),true); + $this->headers = SermondistributorHelper::getFileHeaders($this->dataType); // clear the data type $session->clear('dataType'); } - + // Check for errors. if (count($errors = $this->get('Errors'))) { - throw new Exception(implode("\n", $errors), 500); + throw new \Exception(implode("\n", $errors), 500); } // Display the template @@ -86,23 +95,25 @@ class SermondistributorViewImport extends HtmlView } /** - * Setting the toolbar + * Add the page title and toolbar. + * + * @return void + * @since 1.6 */ - protected function addToolBar() + protected function addToolbar(): void { - JToolBarHelper::title(JText::_('COM_SERMONDISTRIBUTOR_IMPORT_TITLE'), 'upload'); - JHtmlSidebar::setAction('index.php?option=com_sermondistributor&view=import'); + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_IMPORT_TITLE'), 'upload'); if ($this->canDo->get('core.admin') || $this->canDo->get('core.options')) { - JToolBarHelper::preferences('com_sermondistributor'); + ToolbarHelper::preferences('com_sermondistributor'); } // set help url for this view if found $this->help_url = SermondistributorHelper::getHelpUrl('import'); - if (SermondistributorHelper::checkString($this->help_url)) + if (StringHelper::check($this->help_url)) { - JToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); } } } diff --git a/admin/views/import/tmpl/index.html b/admin/src/View/Import/index.html similarity index 100% rename from admin/views/import/tmpl/index.html rename to admin/src/View/Import/index.html diff --git a/admin/src/View/Local_listing/HtmlView.php b/admin/src/View/Local_listing/HtmlView.php new file mode 100644 index 00000000..06b9440a --- /dev/null +++ b/admin/src/View/Local_listing/HtmlView.php @@ -0,0 +1,247 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Local_listing; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Local_listing Html View class + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Local_listing view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // set params + $this->params = ComponentHelper::getParams('com_sermondistributor'); + // Assign the variables + $this->form = $this->get('Form'); + $this->item = $this->get('Item'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->state = $this->get('State'); + // get action permissions + $this->canDo = SermondistributorHelper::getActions('local_listing', $this->item); + // get input + $jinput = Factory::getApplication()->input; + $this->ref = $jinput->get('ref', 0, 'word'); + $this->refid = $jinput->get('refid', 0, 'int'); + $return = $jinput->get('return', null, 'base64'); + // set the referral string + $this->referral = ''; + if ($this->refid && $this->ref) + { + // return to the item that referred to this item + $this->referral = '&ref=' . (string) $this->ref . '&refid=' . (int) $this->refid; + } + elseif($this->ref) + { + // return to the list view that referred to this item + $this->referral = '&ref=' . (string) $this->ref; + } + // check return value + if (!is_null($return)) + { + // add the return value + $this->referral .= '&return=' . (string) $return; + } + + // Set the toolbar + $this->addToolBar(); + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + Factory::getApplication()->input->set('hidemainmenu', true); + $user = Factory::getApplication()->getIdentity(); + $userId = $user->id; + $isNew = $this->item->id == 0; + + ToolbarHelper::title( Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_LOCAL_LISTING_NEW' : 'COM_SERMONDISTRIBUTOR_LOCAL_LISTING_EDIT'), 'pencil-2 article-add'); + // Built the actions for new and existing records. + if (StringHelper::check($this->referral)) + { + if ($this->canDo->get('local_listing.create') && $isNew) + { + // We can create the record. + ToolbarHelper::save('local_listing.save', 'JTOOLBAR_SAVE'); + } + elseif ($this->canDo->get('local_listing.edit')) + { + // We can save the record. + ToolbarHelper::save('local_listing.save', 'JTOOLBAR_SAVE'); + } + if ($isNew) + { + // Do not creat but cancel. + ToolbarHelper::cancel('local_listing.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + // We can close it. + ToolbarHelper::cancel('local_listing.cancel', 'JTOOLBAR_CLOSE'); + } + } + else + { + if ($isNew) + { + // For new records, check the create permission. + if ($this->canDo->get('local_listing.create')) + { + ToolbarHelper::apply('local_listing.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('local_listing.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::custom('local_listing.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + }; + ToolbarHelper::cancel('local_listing.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + if ($this->canDo->get('local_listing.edit')) + { + // We can save the new record + ToolbarHelper::apply('local_listing.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('local_listing.save', 'JTOOLBAR_SAVE'); + // We can save this record, but check the create permission to see + // if we can return to make a new one. + if ($this->canDo->get('local_listing.create')) + { + ToolbarHelper::custom('local_listing.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + } + } + $canVersion = ($this->canDo->get('core.version') && $this->canDo->get('local_listing.version')); + if ($this->state->params->get('save_history', 1) && $this->canDo->get('local_listing.edit') && $canVersion) + { + ToolbarHelper::versions('com_sermondistributor.local_listing', $this->item->id); + } + if ($this->canDo->get('local_listing.create')) + { + ToolbarHelper::custom('local_listing.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); + } + ToolbarHelper::cancel('local_listing.cancel', 'JTOOLBAR_CLOSE'); + } + } + ToolbarHelper::divider(); + ToolbarHelper::inlinehelp(); + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('local_listing'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 30) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $isNew = ($this->item->id < 1); + $this->getDocument()->setTitle(Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_LOCAL_LISTING_NEW' : 'COM_SERMONDISTRIBUTOR_LOCAL_LISTING_EDIT')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // Add Ajax Token + $this->getDocument()->addScriptDeclaration("var token = '" . Session::getFormToken() . "';"); + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + // add JavaScripts + Html::_('script', 'media/com_sermondistributor/uikit/js/uikit.min.js', ['version' => 'auto']); + // add the style sheets + Html::_('stylesheet', 'media/com_sermondistributor/uikit/css/uikit.gradient.min.css', ['version' => 'auto']); + } +} diff --git a/admin/views/index.html b/admin/src/View/Local_listing/index.html similarity index 100% rename from admin/views/index.html rename to admin/src/View/Local_listing/index.html diff --git a/admin/src/View/Local_listings/HtmlView.php b/admin/src/View/Local_listings/HtmlView.php new file mode 100644 index 00000000..b32a4bc7 --- /dev/null +++ b/admin/src/View/Local_listings/HtmlView.php @@ -0,0 +1,232 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Local_listings; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor Html View class for the Local_listings + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Local_listings view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // Assign data to the view + $this->items = $this->get('Items'); + $this->pagination = $this->get('Pagination'); + $this->state = $this->get('State'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->user ??= Factory::getApplication()->getIdentity(); + // Load the filter form from xml. + $this->filterForm = $this->get('FilterForm'); + // Load the active filters. + $this->activeFilters = $this->get('ActiveFilters'); + // Add the list ordering clause. + $this->listOrder = $this->escape($this->state->get('list.ordering', 'a.id')); + $this->listDirn = $this->escape($this->state->get('list.direction', 'DESC')); + $this->saveOrder = $this->listOrder == 'a.ordering'; + // set the return here value + $this->return_here = urlencode(base64_encode((string) Uri::getInstance())); + // get global action permissions + $this->canDo = SermondistributorHelper::getActions('local_listing'); + $this->canEdit = $this->canDo->get('local_listing.edit'); + $this->canState = $this->canDo->get('local_listing.edit.state'); + $this->canCreate = $this->canDo->get('local_listing.create'); + $this->canDelete = $this->canDo->get('local_listing.delete'); + $this->canBatch = ($this->canDo->get('local_listing.batch') && $this->canDo->get('core.batch')); + + // If we don't have items we load the empty state + if (is_array($this->items) && !count((array) $this->items) && $this->isEmptyState = $this->get('IsEmptyState')) + { + $this->setLayout('emptystate'); + } + + // We don't need toolbar in the modal window. + if ($this->getLayout() !== 'modal') + { + $this->addToolbar(); + } + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS'), 'link'); + + if ($this->canCreate) + { + ToolbarHelper::addNew('local_listing.add'); + } + + // Only load if there are items + if (ArrayHelper::check($this->items)) + { + if ($this->canEdit) + { + ToolbarHelper::editList('local_listing.edit'); + } + + if ($this->canState) + { + ToolbarHelper::publishList('local_listings.publish'); + ToolbarHelper::unpublishList('local_listings.unpublish'); + ToolbarHelper::archiveList('local_listings.archive'); + + if ($this->canDo->get('core.admin')) + { + ToolbarHelper::checkin('local_listings.checkin'); + } + } + + if ($this->state->get('filter.published') == -2 && ($this->canState && $this->canDelete)) + { + ToolbarHelper::deleteList('', 'local_listings.delete', 'JTOOLBAR_EMPTY_TRASH'); + } + elseif ($this->canState && $this->canDelete) + { + ToolbarHelper::trash('local_listings.trash'); + } + } + + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('local_listings'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + + // add the options comp button + if ($this->canDo->get('core.admin') || $this->canDo->get('core.options')) + { + ToolbarHelper::preferences('com_sermondistributor'); + } + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $this->getDocument()->setTitle(Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTINGS')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 50) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Returns an array of fields the table can be sorted by + * + * @return array containing the field name to sort by as the key and display text as value + * @since 1.6 + */ + protected function getSortFields() + { + return array( + 'a.ordering' => Text::_('JGRID_HEADING_ORDERING'), + 'a.published' => Text::_('JSTATUS'), + 'a.name' => Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_NAME_LABEL'), + 'a.build' => Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_BUILD_LABEL'), + 'a.size' => Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_SIZE_LABEL'), + 'g.description' => Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_EXTERNAL_SOURCE_LABEL'), + 'a.key' => Text::_('COM_SERMONDISTRIBUTOR_LOCAL_LISTING_KEY_LABEL'), + 'a.id' => Text::_('JGRID_HEADING_ID') + ); + } +} diff --git a/admin/views/local_listing/tmpl/index.html b/admin/src/View/Local_listings/index.html similarity index 100% rename from admin/views/local_listing/tmpl/index.html rename to admin/src/View/Local_listings/index.html diff --git a/admin/src/View/Manual_updater/HtmlView.php b/admin/src/View/Manual_updater/HtmlView.php new file mode 100644 index 00000000..c09d9043 --- /dev/null +++ b/admin/src/View/Manual_updater/HtmlView.php @@ -0,0 +1,189 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Manual_updater; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\HeaderCheck; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor Html View class for the Manual_updater + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Display the view + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // get component params + $this->params = ComponentHelper::getParams('com_sermondistributor'); + // get the application + $this->app ??= Factory::getApplication(); + // get the user object + $this->user ??= $this->app->getIdentity(); + // get global action permissions + $this->canDo = SermondistributorHelper::getActions('manual_updater'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + // Initialise variables. + $this->items = $this->get('Items'); + + // We don't need toolbar in the modal window. + if ($this->getLayout() !== 'modal') + { + // add the tool bar + $this->addToolBar(); + } + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode(PHP_EOL, $errors), 500); + } + + parent::display($tpl); + + // Set the html view document stuff + $this->_prepareDocument(); + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + + // Only load jQuery if needed. (default is true) + if ($this->params->get('add_jquery_framework', 1) == 1) + { + Html::_('jquery.framework'); + } + // Load the header checker class. + // Initialize the header checker. + $HeaderCheck = new HeaderCheck(); + + // Load uikit options. + $uikit = $this->params->get('uikit_load'); + // Set script size. + $size = $this->params->get('uikit_min'); + // The uikit css. + if ((!$HeaderCheck->css_loaded('uikit.min') || $uikit == 1) && $uikit != 2 && $uikit != 3) + { + Html::_('stylesheet', 'media/com_sermondistributor/uikit-v3/css/uikit'.$size.'.css', ['version' => 'auto']); + } + // The uikit js. + if ((!$HeaderCheck->js_loaded('uikit.min') || $uikit == 1) && $uikit != 2 && $uikit != 3) + { + Html::_('script', 'media/com_sermondistributor/uikit-v3/js/uikit'.$size.'.js', ['version' => 'auto']); + Html::_('script', 'media/com_sermondistributor/uikit-v3/js/uikit-icons'.$size.'.js', ['version' => 'auto']); + } + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + // hide the main menu + $this->app->input->set('hidemainmenu', true); + // add title to the page + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_MANUAL_UPDATER'),'cogs'); + // add cpanel button + ToolbarHelper::custom('manual_updater.dashboard', 'grid-2', '', 'COM_SERMONDISTRIBUTOR_DASH', false); + if ($this->canDo->get('manual_updater.external_sources')) + { + // add External Sources button. + ToolbarHelper::custom('manual_updater.gotoExternalSources', 'puzzle custom-button-gotoexternalsources', '', 'COM_SERMONDISTRIBUTOR_EXTERNAL_SOURCES', false); + } + + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('manual_updater'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + + // add the options comp button + if ($this->canDo->get('core.admin') || $this->canDo->get('core.options')) + { + ToolbarHelper::preferences('com_sermondistributor'); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = false, int $length = 40) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } +} diff --git a/admin/views/local_listings/index.html b/admin/src/View/Manual_updater/index.html similarity index 100% rename from admin/views/local_listings/index.html rename to admin/src/View/Manual_updater/index.html diff --git a/admin/src/View/Preacher/HtmlView.php b/admin/src/View/Preacher/HtmlView.php new file mode 100644 index 00000000..d815958e --- /dev/null +++ b/admin/src/View/Preacher/HtmlView.php @@ -0,0 +1,254 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Preacher; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Preacher Html View class + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Preacher view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // set params + $this->params = ComponentHelper::getParams('com_sermondistributor'); + // Assign the variables + $this->form = $this->get('Form'); + $this->item = $this->get('Item'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->state = $this->get('State'); + // get action permissions + $this->canDo = SermondistributorHelper::getActions('preacher', $this->item); + // get input + $jinput = Factory::getApplication()->input; + $this->ref = $jinput->get('ref', 0, 'word'); + $this->refid = $jinput->get('refid', 0, 'int'); + $return = $jinput->get('return', null, 'base64'); + // set the referral string + $this->referral = ''; + if ($this->refid && $this->ref) + { + // return to the item that referred to this item + $this->referral = '&ref=' . (string) $this->ref . '&refid=' . (int) $this->refid; + } + elseif($this->ref) + { + // return to the list view that referred to this item + $this->referral = '&ref=' . (string) $this->ref; + } + // check return value + if (!is_null($return)) + { + // add the return value + $this->referral .= '&return=' . (string) $return; + } + + // Get Linked view data + $this->vvvsermons = $this->get('Vvvsermons'); + + // Set the toolbar + $this->addToolBar(); + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + Factory::getApplication()->input->set('hidemainmenu', true); + $user = Factory::getApplication()->getIdentity(); + $userId = $user->id; + $isNew = $this->item->id == 0; + + ToolbarHelper::title( Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_PREACHER_NEW' : 'COM_SERMONDISTRIBUTOR_PREACHER_EDIT'), 'pencil-2 article-add'); + // Built the actions for new and existing records. + if (StringHelper::check($this->referral)) + { + if ($this->canDo->get('preacher.create') && $isNew) + { + // We can create the record. + ToolbarHelper::save('preacher.save', 'JTOOLBAR_SAVE'); + } + elseif ($this->canDo->get('preacher.edit')) + { + // We can save the record. + ToolbarHelper::save('preacher.save', 'JTOOLBAR_SAVE'); + } + if ($isNew) + { + // Do not creat but cancel. + ToolbarHelper::cancel('preacher.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + // We can close it. + ToolbarHelper::cancel('preacher.cancel', 'JTOOLBAR_CLOSE'); + } + } + else + { + if ($isNew) + { + // For new records, check the create permission. + if ($this->canDo->get('preacher.create')) + { + ToolbarHelper::apply('preacher.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('preacher.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::custom('preacher.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + }; + ToolbarHelper::cancel('preacher.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + if ($this->canDo->get('preacher.edit')) + { + // We can save the new record + ToolbarHelper::apply('preacher.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('preacher.save', 'JTOOLBAR_SAVE'); + // We can save this record, but check the create permission to see + // if we can return to make a new one. + if ($this->canDo->get('preacher.create')) + { + ToolbarHelper::custom('preacher.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + } + } + $canVersion = ($this->canDo->get('core.version') && $this->canDo->get('preacher.version')); + if ($this->state->params->get('save_history', 1) && $this->canDo->get('preacher.edit') && $canVersion) + { + ToolbarHelper::versions('com_sermondistributor.preacher', $this->item->id); + } + if ($this->canDo->get('preacher.create')) + { + ToolbarHelper::custom('preacher.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); + } + ToolbarHelper::cancel('preacher.cancel', 'JTOOLBAR_CLOSE'); + } + } + ToolbarHelper::divider(); + ToolbarHelper::inlinehelp(); + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('preacher'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 30) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $isNew = ($this->item->id < 1); + $this->getDocument()->setTitle(Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_PREACHER_NEW' : 'COM_SERMONDISTRIBUTOR_PREACHER_EDIT')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + + // Add the CSS for Footable + Html::_('stylesheet', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css', ['version' => 'auto']); + Html::_('stylesheet', 'media/com_sermondistributor/footable-v3/css/footable.standalone.min.css', ['version' => 'auto']); + // Add the JavaScript for Footable (adding all functions) + Html::_('script', 'media/com_sermondistributor/footable-v3/js/footable.min.js', ['version' => 'auto']); + + $footable = "jQuery(document).ready(function() { jQuery(function () { jQuery('.footable').footable();});});"; + $this->getDocument()->addScriptDeclaration($footable); + + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } +} diff --git a/admin/views/local_listings/tmpl/index.html b/admin/src/View/Preacher/index.html similarity index 100% rename from admin/views/local_listings/tmpl/index.html rename to admin/src/View/Preacher/index.html diff --git a/admin/src/View/Preachers/HtmlView.php b/admin/src/View/Preachers/HtmlView.php new file mode 100644 index 00000000..438d1cc4 --- /dev/null +++ b/admin/src/View/Preachers/HtmlView.php @@ -0,0 +1,229 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Preachers; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor Html View class for the Preachers + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Preachers view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // Assign data to the view + $this->items = $this->get('Items'); + $this->pagination = $this->get('Pagination'); + $this->state = $this->get('State'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->user ??= Factory::getApplication()->getIdentity(); + // Load the filter form from xml. + $this->filterForm = $this->get('FilterForm'); + // Load the active filters. + $this->activeFilters = $this->get('ActiveFilters'); + // Add the list ordering clause. + $this->listOrder = $this->escape($this->state->get('list.ordering', 'a.id')); + $this->listDirn = $this->escape($this->state->get('list.direction', 'DESC')); + $this->saveOrder = $this->listOrder == 'a.ordering'; + // set the return here value + $this->return_here = urlencode(base64_encode((string) Uri::getInstance())); + // get global action permissions + $this->canDo = SermondistributorHelper::getActions('preacher'); + $this->canEdit = $this->canDo->get('preacher.edit'); + $this->canState = $this->canDo->get('preacher.edit.state'); + $this->canCreate = $this->canDo->get('preacher.create'); + $this->canDelete = $this->canDo->get('preacher.delete'); + $this->canBatch = ($this->canDo->get('preacher.batch') && $this->canDo->get('core.batch')); + + // If we don't have items we load the empty state + if (is_array($this->items) && !count((array) $this->items) && $this->isEmptyState = $this->get('IsEmptyState')) + { + $this->setLayout('emptystate'); + } + + // We don't need toolbar in the modal window. + if ($this->getLayout() !== 'modal') + { + $this->addToolbar(); + } + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_PREACHERS'), 'user'); + + if ($this->canCreate) + { + ToolbarHelper::addNew('preacher.add'); + } + + // Only load if there are items + if (ArrayHelper::check($this->items)) + { + if ($this->canEdit) + { + ToolbarHelper::editList('preacher.edit'); + } + + if ($this->canState) + { + ToolbarHelper::publishList('preachers.publish'); + ToolbarHelper::unpublishList('preachers.unpublish'); + ToolbarHelper::archiveList('preachers.archive'); + + if ($this->canDo->get('core.admin')) + { + ToolbarHelper::checkin('preachers.checkin'); + } + } + + if ($this->state->get('filter.published') == -2 && ($this->canState && $this->canDelete)) + { + ToolbarHelper::deleteList('', 'preachers.delete', 'JTOOLBAR_EMPTY_TRASH'); + } + elseif ($this->canState && $this->canDelete) + { + ToolbarHelper::trash('preachers.trash'); + } + } + + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('preachers'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + + // add the options comp button + if ($this->canDo->get('core.admin') || $this->canDo->get('core.options')) + { + ToolbarHelper::preferences('com_sermondistributor'); + } + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $this->getDocument()->setTitle(Text::_('COM_SERMONDISTRIBUTOR_PREACHERS')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 50) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Returns an array of fields the table can be sorted by + * + * @return array containing the field name to sort by as the key and display text as value + * @since 1.6 + */ + protected function getSortFields() + { + return array( + 'a.ordering' => Text::_('JGRID_HEADING_ORDERING'), + 'a.published' => Text::_('JSTATUS'), + 'a.name' => Text::_('COM_SERMONDISTRIBUTOR_PREACHER_NAME_LABEL'), + 'a.description' => Text::_('COM_SERMONDISTRIBUTOR_PREACHER_DESCRIPTION_LABEL'), + 'a.id' => Text::_('JGRID_HEADING_ID') + ); + } +} diff --git a/admin/views/manual_updater/index.html b/admin/src/View/Preachers/index.html similarity index 100% rename from admin/views/manual_updater/index.html rename to admin/src/View/Preachers/index.html diff --git a/admin/src/View/Series/HtmlView.php b/admin/src/View/Series/HtmlView.php new file mode 100644 index 00000000..c55ce269 --- /dev/null +++ b/admin/src/View/Series/HtmlView.php @@ -0,0 +1,254 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Series; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Series Html View class + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Series view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // set params + $this->params = ComponentHelper::getParams('com_sermondistributor'); + // Assign the variables + $this->form = $this->get('Form'); + $this->item = $this->get('Item'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->state = $this->get('State'); + // get action permissions + $this->canDo = SermondistributorHelper::getActions('series', $this->item); + // get input + $jinput = Factory::getApplication()->input; + $this->ref = $jinput->get('ref', 0, 'word'); + $this->refid = $jinput->get('refid', 0, 'int'); + $return = $jinput->get('return', null, 'base64'); + // set the referral string + $this->referral = ''; + if ($this->refid && $this->ref) + { + // return to the item that referred to this item + $this->referral = '&ref=' . (string) $this->ref . '&refid=' . (int) $this->refid; + } + elseif($this->ref) + { + // return to the list view that referred to this item + $this->referral = '&ref=' . (string) $this->ref; + } + // check return value + if (!is_null($return)) + { + // add the return value + $this->referral .= '&return=' . (string) $return; + } + + // Get Linked view data + $this->vwcsermons = $this->get('Vwcsermons'); + + // Set the toolbar + $this->addToolBar(); + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + Factory::getApplication()->input->set('hidemainmenu', true); + $user = Factory::getApplication()->getIdentity(); + $userId = $user->id; + $isNew = $this->item->id == 0; + + ToolbarHelper::title( Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_SERIES_NEW' : 'COM_SERMONDISTRIBUTOR_SERIES_EDIT'), 'pencil-2 article-add'); + // Built the actions for new and existing records. + if (StringHelper::check($this->referral)) + { + if ($this->canDo->get('series.create') && $isNew) + { + // We can create the record. + ToolbarHelper::save('series.save', 'JTOOLBAR_SAVE'); + } + elseif ($this->canDo->get('series.edit')) + { + // We can save the record. + ToolbarHelper::save('series.save', 'JTOOLBAR_SAVE'); + } + if ($isNew) + { + // Do not creat but cancel. + ToolbarHelper::cancel('series.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + // We can close it. + ToolbarHelper::cancel('series.cancel', 'JTOOLBAR_CLOSE'); + } + } + else + { + if ($isNew) + { + // For new records, check the create permission. + if ($this->canDo->get('series.create')) + { + ToolbarHelper::apply('series.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('series.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::custom('series.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + }; + ToolbarHelper::cancel('series.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + if ($this->canDo->get('series.edit')) + { + // We can save the new record + ToolbarHelper::apply('series.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('series.save', 'JTOOLBAR_SAVE'); + // We can save this record, but check the create permission to see + // if we can return to make a new one. + if ($this->canDo->get('series.create')) + { + ToolbarHelper::custom('series.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + } + } + $canVersion = ($this->canDo->get('core.version') && $this->canDo->get('series.version')); + if ($this->state->params->get('save_history', 1) && $this->canDo->get('series.edit') && $canVersion) + { + ToolbarHelper::versions('com_sermondistributor.series', $this->item->id); + } + if ($this->canDo->get('series.create')) + { + ToolbarHelper::custom('series.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); + } + ToolbarHelper::cancel('series.cancel', 'JTOOLBAR_CLOSE'); + } + } + ToolbarHelper::divider(); + ToolbarHelper::inlinehelp(); + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('series'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 30) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $isNew = ($this->item->id < 1); + $this->getDocument()->setTitle(Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_SERIES_NEW' : 'COM_SERMONDISTRIBUTOR_SERIES_EDIT')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + + // Add the CSS for Footable + Html::_('stylesheet', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css', ['version' => 'auto']); + Html::_('stylesheet', 'media/com_sermondistributor/footable-v3/css/footable.standalone.min.css', ['version' => 'auto']); + // Add the JavaScript for Footable (adding all functions) + Html::_('script', 'media/com_sermondistributor/footable-v3/js/footable.min.js', ['version' => 'auto']); + + $footable = "jQuery(document).ready(function() { jQuery(function () { jQuery('.footable').footable();});});"; + $this->getDocument()->addScriptDeclaration($footable); + + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } +} diff --git a/admin/views/manual_updater/tmpl/index.html b/admin/src/View/Series/index.html similarity index 100% rename from admin/views/manual_updater/tmpl/index.html rename to admin/src/View/Series/index.html diff --git a/admin/src/View/Series_list/HtmlView.php b/admin/src/View/Series_list/HtmlView.php new file mode 100644 index 00000000..5fb722fd --- /dev/null +++ b/admin/src/View/Series_list/HtmlView.php @@ -0,0 +1,228 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Series_list; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor Html View class for the Series_list + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Series_list view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // Assign data to the view + $this->items = $this->get('Items'); + $this->pagination = $this->get('Pagination'); + $this->state = $this->get('State'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->user ??= Factory::getApplication()->getIdentity(); + // Load the filter form from xml. + $this->filterForm = $this->get('FilterForm'); + // Load the active filters. + $this->activeFilters = $this->get('ActiveFilters'); + // Add the list ordering clause. + $this->listOrder = $this->escape($this->state->get('list.ordering', 'a.id')); + $this->listDirn = $this->escape($this->state->get('list.direction', 'DESC')); + $this->saveOrder = $this->listOrder == 'a.ordering'; + // set the return here value + $this->return_here = urlencode(base64_encode((string) Uri::getInstance())); + // get global action permissions + $this->canDo = SermondistributorHelper::getActions('series'); + $this->canEdit = $this->canDo->get('series.edit'); + $this->canState = $this->canDo->get('series.edit.state'); + $this->canCreate = $this->canDo->get('series.create'); + $this->canDelete = $this->canDo->get('series.delete'); + $this->canBatch = ($this->canDo->get('series.batch') && $this->canDo->get('core.batch')); + + // If we don't have items we load the empty state + if (is_array($this->items) && !count((array) $this->items) && $this->isEmptyState = $this->get('IsEmptyState')) + { + $this->setLayout('emptystate'); + } + + // We don't need toolbar in the modal window. + if ($this->getLayout() !== 'modal') + { + $this->addToolbar(); + } + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_SERIES_LIST'), 'folder-open'); + + if ($this->canCreate) + { + ToolbarHelper::addNew('series.add'); + } + + // Only load if there are items + if (ArrayHelper::check($this->items)) + { + if ($this->canEdit) + { + ToolbarHelper::editList('series.edit'); + } + + if ($this->canState) + { + ToolbarHelper::publishList('series_list.publish'); + ToolbarHelper::unpublishList('series_list.unpublish'); + ToolbarHelper::archiveList('series_list.archive'); + + if ($this->canDo->get('core.admin')) + { + ToolbarHelper::checkin('series_list.checkin'); + } + } + + if ($this->state->get('filter.published') == -2 && ($this->canState && $this->canDelete)) + { + ToolbarHelper::deleteList('', 'series_list.delete', 'JTOOLBAR_EMPTY_TRASH'); + } + elseif ($this->canState && $this->canDelete) + { + ToolbarHelper::trash('series_list.trash'); + } + } + + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('series_list'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + + // add the options comp button + if ($this->canDo->get('core.admin') || $this->canDo->get('core.options')) + { + ToolbarHelper::preferences('com_sermondistributor'); + } + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $this->getDocument()->setTitle(Text::_('COM_SERMONDISTRIBUTOR_SERIES_LIST')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 50) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Returns an array of fields the table can be sorted by + * + * @return array containing the field name to sort by as the key and display text as value + * @since 1.6 + */ + protected function getSortFields() + { + return array( + 'a.ordering' => Text::_('JGRID_HEADING_ORDERING'), + 'a.published' => Text::_('JSTATUS'), + 'a.name' => Text::_('COM_SERMONDISTRIBUTOR_SERIES_NAME_LABEL'), + 'a.id' => Text::_('JGRID_HEADING_ID') + ); + } +} diff --git a/admin/views/preacher/tmpl/index.html b/admin/src/View/Series_list/index.html similarity index 100% rename from admin/views/preacher/tmpl/index.html rename to admin/src/View/Series_list/index.html diff --git a/admin/src/View/Sermon/HtmlView.php b/admin/src/View/Sermon/HtmlView.php new file mode 100644 index 00000000..e4a75b7b --- /dev/null +++ b/admin/src/View/Sermon/HtmlView.php @@ -0,0 +1,256 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Sermon; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermon Html View class + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Sermon view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // set params + $this->params = ComponentHelper::getParams('com_sermondistributor'); + // Assign the variables + $this->form = $this->get('Form'); + $this->item = $this->get('Item'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->state = $this->get('State'); + // get action permissions + $this->canDo = SermondistributorHelper::getActions('sermon', $this->item); + // get input + $jinput = Factory::getApplication()->input; + $this->ref = $jinput->get('ref', 0, 'word'); + $this->refid = $jinput->get('refid', 0, 'int'); + $return = $jinput->get('return', null, 'base64'); + // set the referral string + $this->referral = ''; + if ($this->refid && $this->ref) + { + // return to the item that referred to this item + $this->referral = '&ref=' . (string) $this->ref . '&refid=' . (int) $this->refid; + } + elseif($this->ref) + { + // return to the list view that referred to this item + $this->referral = '&ref=' . (string) $this->ref; + } + // check return value + if (!is_null($return)) + { + // add the return value + $this->referral .= '&return=' . (string) $return; + } + + // Get Linked view data + $this->vwbstastics = $this->get('Vwbstastics'); + + // Set the toolbar + $this->addToolBar(); + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + Factory::getApplication()->input->set('hidemainmenu', true); + $user = Factory::getApplication()->getIdentity(); + $userId = $user->id; + $isNew = $this->item->id == 0; + + ToolbarHelper::title( Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_SERMON_NEW' : 'COM_SERMONDISTRIBUTOR_SERMON_EDIT'), 'pencil-2 article-add'); + // Built the actions for new and existing records. + if (StringHelper::check($this->referral)) + { + if ($this->canDo->get('sermon.create') && $isNew) + { + // We can create the record. + ToolbarHelper::save('sermon.save', 'JTOOLBAR_SAVE'); + } + elseif ($this->canDo->get('sermon.edit')) + { + // We can save the record. + ToolbarHelper::save('sermon.save', 'JTOOLBAR_SAVE'); + } + if ($isNew) + { + // Do not creat but cancel. + ToolbarHelper::cancel('sermon.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + // We can close it. + ToolbarHelper::cancel('sermon.cancel', 'JTOOLBAR_CLOSE'); + } + } + else + { + if ($isNew) + { + // For new records, check the create permission. + if ($this->canDo->get('sermon.create')) + { + ToolbarHelper::apply('sermon.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('sermon.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::custom('sermon.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + }; + ToolbarHelper::cancel('sermon.cancel', 'JTOOLBAR_CANCEL'); + } + else + { + if ($this->canDo->get('sermon.edit')) + { + // We can save the new record + ToolbarHelper::apply('sermon.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('sermon.save', 'JTOOLBAR_SAVE'); + // We can save this record, but check the create permission to see + // if we can return to make a new one. + if ($this->canDo->get('sermon.create')) + { + ToolbarHelper::custom('sermon.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + } + } + $canVersion = ($this->canDo->get('core.version') && $this->canDo->get('sermon.version')); + if ($this->state->params->get('save_history', 1) && $this->canDo->get('sermon.edit') && $canVersion) + { + ToolbarHelper::versions('com_sermondistributor.sermon', $this->item->id); + } + if ($this->canDo->get('sermon.create')) + { + ToolbarHelper::custom('sermon.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); + } + ToolbarHelper::cancel('sermon.cancel', 'JTOOLBAR_CLOSE'); + } + } + ToolbarHelper::divider(); + ToolbarHelper::inlinehelp(); + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('sermon'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 30) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $isNew = ($this->item->id < 1); + $this->getDocument()->setTitle(Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_SERMON_NEW' : 'COM_SERMONDISTRIBUTOR_SERMON_EDIT')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // Add Ajax Token + $this->getDocument()->addScriptDeclaration("var token = '" . Session::getFormToken() . "';"); + + // Add the CSS for Footable + Html::_('stylesheet', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css', ['version' => 'auto']); + Html::_('stylesheet', 'media/com_sermondistributor/footable-v3/css/footable.standalone.min.css', ['version' => 'auto']); + // Add the JavaScript for Footable (adding all functions) + Html::_('script', 'media/com_sermondistributor/footable-v3/js/footable.min.js', ['version' => 'auto']); + + $footable = "jQuery(document).ready(function() { jQuery(function () { jQuery('.footable').footable();});});"; + $this->getDocument()->addScriptDeclaration($footable); + + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } +} diff --git a/admin/views/preachers/index.html b/admin/src/View/Sermon/index.html similarity index 100% rename from admin/views/preachers/index.html rename to admin/src/View/Sermon/index.html diff --git a/admin/views/sermondistributor/view.html.php b/admin/src/View/Sermondistributor/HtmlView.php similarity index 61% rename from admin/views/sermondistributor/view.html.php rename to admin/src/View/Sermondistributor/HtmlView.php index 619d7dd3..352c7b91 100644 --- a/admin/views/sermondistributor/view.html.php +++ b/admin/src/View/Sermondistributor/HtmlView.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage view.html.php + @subpackage HtmlView.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,16 +21,26 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Sermondistributor; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - - +\defined('_JEXEC') or die; /** * Sermondistributor View class + * + * @since 1.6 */ -class SermondistributorViewSermondistributor extends JViewLegacy +class HtmlView extends BaseHtmlView { /** * View display method @@ -39,69 +49,70 @@ class SermondistributorViewSermondistributor extends JViewLegacy function display($tpl = null) { // Assign data to the view - $this->icons = $this->get('Icons'); - $this->contributors = SermondistributorHelper::getContributors(); - $this->github = $this->get('Github'); + $this->icons = $this->get('Icons'); + $this->contributors = SermondistributorHelper::getContributors(); + + // get the manifest details of the component + $this->manifest = SermondistributorHelper::manifest(); $this->wiki = $this->get('Wiki'); $this->noticeboard = $this->get('Noticeboard'); $this->readme = $this->get('Readme'); - - // get the manifest details of the component - $this->manifest = SermondistributorHelper::manifest(); - + // Set the toolbar $this->addToolBar(); - + // Check for errors. if (count($errors = $this->get('Errors'))) { - throw new Exception(implode("\n", $errors), 500); + throw new \Exception(implode("\n", $errors), 500); } + // Set the html view document stuff + $this->_prepareDocument(); + // Display the template parent::display($tpl); - - // Set the document - $this->setDocument(); } /** - * Setting the toolbar + * Add the page title and toolbar. + * + * @return void + * @since 1.6 */ - protected function addToolBar() + protected function addToolbar(): void { $canDo = SermondistributorHelper::getActions('sermondistributor'); - JToolBarHelper::title(JText::_('COM_SERMONDISTRIBUTOR_DASHBOARD'), 'grid-2'); + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_DASHBOARD'), 'grid-2'); // set help url for this view if found $this->help_url = SermondistributorHelper::getHelpUrl('sermondistributor'); - if (SermondistributorHelper::checkString($this->help_url)) + if (StringHelper::check($this->help_url)) { - JToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); } if ($canDo->get('core.admin') || $canDo->get('core.options')) { - JToolBarHelper::preferences('com_sermondistributor'); + ToolbarHelper::preferences('com_sermondistributor'); } } /** - * Method to set up the document properties + * Prepare some document related stuff. * - * @return void + * @return void + * @since 1.6 */ - protected function setDocument() + protected function _prepareDocument(): void { - $document = JFactory::getDocument(); - - // add dashboard style sheets - $document->addStyleSheet(JURI::root() . "administrator/components/com_sermondistributor/assets/css/dashboard.css"); - // set page title - $document->setTitle(JText::_('COM_SERMONDISTRIBUTOR_DASHBOARD')); - + $this->getDocument()->setTitle(Text::_('COM_SERMONDISTRIBUTOR_DASHBOARD')); + // add manifest to page JavaScript - $document->addScriptDeclaration("var manifest = jQuery.parseJSON('" . json_encode($this->manifest) . "');", "text/javascript"); + $this->getDocument()->addScriptDeclaration("var manifest = JSON.parse('" . json_encode($this->manifest) . "');", "text/javascript"); + + // add dashboard style sheets + Html::_('stylesheet', "administrator/components/com_sermondistributor/assets/css/dashboard.css", ['version' => 'auto']); } } diff --git a/admin/views/preachers/tmpl/index.html b/admin/src/View/Sermondistributor/index.html similarity index 100% rename from admin/views/preachers/tmpl/index.html rename to admin/src/View/Sermondistributor/index.html diff --git a/admin/src/View/Sermons/HtmlView.php b/admin/src/View/Sermons/HtmlView.php new file mode 100644 index 00000000..cb7ffc55 --- /dev/null +++ b/admin/src/View/Sermons/HtmlView.php @@ -0,0 +1,234 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Sermons; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor Html View class for the Sermons + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Sermons view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // Assign data to the view + $this->items = $this->get('Items'); + $this->pagination = $this->get('Pagination'); + $this->state = $this->get('State'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->user ??= Factory::getApplication()->getIdentity(); + // Load the filter form from xml. + $this->filterForm = $this->get('FilterForm'); + // Load the active filters. + $this->activeFilters = $this->get('ActiveFilters'); + // Add the list ordering clause. + $this->listOrder = $this->escape($this->state->get('list.ordering', 'a.id')); + $this->listDirn = $this->escape($this->state->get('list.direction', 'DESC')); + $this->saveOrder = $this->listOrder == 'a.ordering'; + // set the return here value + $this->return_here = urlencode(base64_encode((string) Uri::getInstance())); + // get global action permissions + $this->canDo = SermondistributorHelper::getActions('sermon'); + $this->canEdit = $this->canDo->get('sermon.edit'); + $this->canState = $this->canDo->get('sermon.edit.state'); + $this->canCreate = $this->canDo->get('sermon.create'); + $this->canDelete = $this->canDo->get('sermon.delete'); + $this->canBatch = ($this->canDo->get('sermon.batch') && $this->canDo->get('core.batch')); + + // If we don't have items we load the empty state + if (is_array($this->items) && !count((array) $this->items) && $this->isEmptyState = $this->get('IsEmptyState')) + { + $this->setLayout('emptystate'); + } + + // We don't need toolbar in the modal window. + if ($this->getLayout() !== 'modal') + { + $this->addToolbar(); + } + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_SERMONS'), 'book'); + + if ($this->canCreate) + { + ToolbarHelper::addNew('sermon.add'); + } + + // Only load if there are items + if (ArrayHelper::check($this->items)) + { + if ($this->canEdit) + { + ToolbarHelper::editList('sermon.edit'); + } + + if ($this->canState) + { + ToolbarHelper::publishList('sermons.publish'); + ToolbarHelper::unpublishList('sermons.unpublish'); + ToolbarHelper::archiveList('sermons.archive'); + + if ($this->canDo->get('core.admin')) + { + ToolbarHelper::checkin('sermons.checkin'); + } + } + + if ($this->state->get('filter.published') == -2 && ($this->canState && $this->canDelete)) + { + ToolbarHelper::deleteList('', 'sermons.delete', 'JTOOLBAR_EMPTY_TRASH'); + } + elseif ($this->canState && $this->canDelete) + { + ToolbarHelper::trash('sermons.trash'); + } + } + + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('sermons'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + + // add the options comp button + if ($this->canDo->get('core.admin') || $this->canDo->get('core.options')) + { + ToolbarHelper::preferences('com_sermondistributor'); + } + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $this->getDocument()->setTitle(Text::_('COM_SERMONDISTRIBUTOR_SERMONS')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 50) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Returns an array of fields the table can be sorted by + * + * @return array containing the field name to sort by as the key and display text as value + * @since 1.6 + */ + protected function getSortFields() + { + return array( + 'a.ordering' => Text::_('JGRID_HEADING_ORDERING'), + 'a.published' => Text::_('JSTATUS'), + 'a.name' => Text::_('COM_SERMONDISTRIBUTOR_SERMON_NAME_LABEL'), + 'g.name' => Text::_('COM_SERMONDISTRIBUTOR_SERMON_PREACHER_LABEL'), + 'h.name' => Text::_('COM_SERMONDISTRIBUTOR_SERMON_SERIES_LABEL'), + 'a.short_description' => Text::_('COM_SERMONDISTRIBUTOR_SERMON_SHORT_DESCRIPTION_LABEL'), + 'category_title' => Text::_('COM_SERMONDISTRIBUTOR_SERMON_SERMONS_CATEGORIES'), + 'a.link_type' => Text::_('COM_SERMONDISTRIBUTOR_SERMON_LINK_TYPE_LABEL'), + 'a.source' => Text::_('COM_SERMONDISTRIBUTOR_SERMON_SOURCE_LABEL'), + 'a.id' => Text::_('JGRID_HEADING_ID') + ); + } +} diff --git a/admin/views/series/tmpl/index.html b/admin/src/View/Sermons/index.html similarity index 100% rename from admin/views/series/tmpl/index.html rename to admin/src/View/Sermons/index.html diff --git a/admin/views/statistic/view.html.php b/admin/src/View/Statistic/HtmlView.php similarity index 51% rename from admin/views/statistic/view.html.php rename to admin/src/View/Statistic/HtmlView.php index 02971971..19506431 100644 --- a/admin/views/statistic/view.html.php +++ b/admin/src/View/Statistic/HtmlView.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage view.html.php + @subpackage HtmlView.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -21,34 +21,56 @@ A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Statistic; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\StringHelper; // No direct access to this file -defined('_JEXEC') or die('Restricted access'); - -use Joomla\CMS\MVC\View\HtmlView; +\defined('_JEXEC') or die; /** * Statistic Html View class + * + * @since 1.6 */ -class SermondistributorViewStatistic extends HtmlView +class HtmlView extends BaseHtmlView { /** - * display method of View - * @return void + * Statistic view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 */ public function display($tpl = null) { // set params - $this->params = JComponentHelper::getParams('com_sermondistributor'); + $this->params = ComponentHelper::getParams('com_sermondistributor'); // Assign the variables $this->form = $this->get('Form'); $this->item = $this->get('Item'); - $this->script = $this->get('Script'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); $this->state = $this->get('State'); // get action permissions $this->canDo = SermondistributorHelper::getActions('statistic', $this->item); // get input - $jinput = JFactory::getApplication()->input; + $jinput = Factory::getApplication()->input; $this->ref = $jinput->get('ref', 0, 'word'); $this->refid = $jinput->get('refid', 0, 'int'); $return = $jinput->get('return', null, 'base64'); @@ -57,70 +79,73 @@ class SermondistributorViewStatistic extends HtmlView if ($this->refid && $this->ref) { // return to the item that referred to this item - $this->referral = '&ref=' . (string)$this->ref . '&refid=' . (int)$this->refid; + $this->referral = '&ref=' . (string) $this->ref . '&refid=' . (int) $this->refid; } elseif($this->ref) { // return to the list view that referred to this item - $this->referral = '&ref=' . (string)$this->ref; + $this->referral = '&ref=' . (string) $this->ref; } // check return value if (!is_null($return)) { // add the return value - $this->referral .= '&return=' . (string)$return; + $this->referral .= '&return=' . (string) $return; } // Set the toolbar $this->addToolBar(); - + // Check for errors. if (count($errors = $this->get('Errors'))) { - throw new Exception(implode("\n", $errors), 500); + throw new \Exception(implode("\n", $errors), 500); } + // Set the html view document stuff + $this->_prepareDocument(); + // Display the template parent::display($tpl); - - // Set the document - $this->setDocument(); } /** - * Setting the toolbar + * Add the page title and toolbar. + * + * @return void + * @since 1.6 */ - protected function addToolBar() + protected function addToolbar(): void { - JFactory::getApplication()->input->set('hidemainmenu', true); - $user = JFactory::getUser(); + Factory::getApplication()->input->set('hidemainmenu', true); + $user = Factory::getApplication()->getIdentity(); $userId = $user->id; $isNew = $this->item->id == 0; - JToolbarHelper::title( JText::_($isNew ? 'COM_SERMONDISTRIBUTOR_STATISTIC_NEW' : 'COM_SERMONDISTRIBUTOR_STATISTIC_EDIT'), 'pencil-2 article-add'); + ToolbarHelper::title( Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_STATISTIC_NEW' : 'COM_SERMONDISTRIBUTOR_STATISTIC_EDIT'), 'pencil-2 article-add'); // Built the actions for new and existing records. - if (SermondistributorHelper::checkString($this->referral)) + if (StringHelper::check($this->referral)) { if ($this->canDo->get('statistic.create') && $isNew) { // We can create the record. - JToolBarHelper::save('statistic.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::save('statistic.save', 'JTOOLBAR_SAVE'); } elseif ($this->canDo->get('statistic.edit')) { // We can save the record. - JToolBarHelper::save('statistic.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::save('statistic.save', 'JTOOLBAR_SAVE'); } if ($isNew) { // Do not creat but cancel. - JToolBarHelper::cancel('statistic.cancel', 'JTOOLBAR_CANCEL'); + ToolbarHelper::cancel('statistic.cancel', 'JTOOLBAR_CANCEL'); } else { // We can close it. - JToolBarHelper::cancel('statistic.cancel', 'JTOOLBAR_CLOSE'); + ToolbarHelper::cancel('statistic.cancel', 'JTOOLBAR_CLOSE'); } } else @@ -130,81 +155,87 @@ class SermondistributorViewStatistic extends HtmlView // For new records, check the create permission. if ($this->canDo->get('statistic.create')) { - JToolBarHelper::apply('statistic.apply', 'JTOOLBAR_APPLY'); - JToolBarHelper::save('statistic.save', 'JTOOLBAR_SAVE'); - JToolBarHelper::custom('statistic.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + ToolbarHelper::apply('statistic.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('statistic.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::custom('statistic.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); }; - JToolBarHelper::cancel('statistic.cancel', 'JTOOLBAR_CANCEL'); + ToolbarHelper::cancel('statistic.cancel', 'JTOOLBAR_CANCEL'); } else { if ($this->canDo->get('statistic.edit')) { // We can save the new record - JToolBarHelper::apply('statistic.apply', 'JTOOLBAR_APPLY'); - JToolBarHelper::save('statistic.save', 'JTOOLBAR_SAVE'); + ToolbarHelper::apply('statistic.apply', 'JTOOLBAR_APPLY'); + ToolbarHelper::save('statistic.save', 'JTOOLBAR_SAVE'); // We can save this record, but check the create permission to see // if we can return to make a new one. if ($this->canDo->get('statistic.create')) { - JToolBarHelper::custom('statistic.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); + ToolbarHelper::custom('statistic.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); } } $canVersion = ($this->canDo->get('core.version') && $this->canDo->get('statistic.version')); if ($this->state->params->get('save_history', 1) && $this->canDo->get('statistic.edit') && $canVersion) { - JToolbarHelper::versions('com_sermondistributor.statistic', $this->item->id); + ToolbarHelper::versions('com_sermondistributor.statistic', $this->item->id); } if ($this->canDo->get('statistic.create')) { - JToolBarHelper::custom('statistic.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); + ToolbarHelper::custom('statistic.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); } - JToolBarHelper::cancel('statistic.cancel', 'JTOOLBAR_CLOSE'); + ToolbarHelper::cancel('statistic.cancel', 'JTOOLBAR_CLOSE'); } } - JToolbarHelper::divider(); + ToolbarHelper::divider(); + ToolbarHelper::inlinehelp(); // set help url for this view if found $this->help_url = SermondistributorHelper::getHelpUrl('statistic'); - if (SermondistributorHelper::checkString($this->help_url)) + if (StringHelper::check($this->help_url)) { - JToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); } } /** * Escapes a value for output in a view script. * - * @param mixed $var The output to escape. + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. * * @return mixed The escaped value. + * @since 1.6 */ - public function escape($var) + public function escape($var, bool $shorten = true, int $length = 30) { - if(strlen($var) > 30) + if (!is_string($var)) { - // use the helper htmlEscape method instead and shorten the string - return SermondistributorHelper::htmlEscape($var, $this->_charset, true, 30); + return $var; } - // use the helper htmlEscape method instead. - return SermondistributorHelper::htmlEscape($var, $this->_charset); + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); } /** - * Method to set up the document properties + * Prepare some document related stuff. * - * @return void + * @return void + * @since 1.6 */ - protected function setDocument() + protected function _prepareDocument(): void { $isNew = ($this->item->id < 1); - if (!isset($this->document)) + $this->getDocument()->setTitle(Text::_($isNew ? 'COM_SERMONDISTRIBUTOR_STATISTIC_NEW' : 'COM_SERMONDISTRIBUTOR_STATISTIC_EDIT')); + // add styles + foreach ($this->styles as $style) { - $this->document = JFactory::getDocument(); + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); } - $this->document->setTitle(JText::_($isNew ? 'COM_SERMONDISTRIBUTOR_STATISTIC_NEW' : 'COM_SERMONDISTRIBUTOR_STATISTIC_EDIT')); - $this->document->addStyleSheet(JURI::root() . "administrator/components/com_sermondistributor/assets/css/statistic.css", (SermondistributorHelper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css'); - $this->document->addScript(JURI::root() . $this->script, (SermondistributorHelper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/javascript'); - $this->document->addScript(JURI::root() . "administrator/components/com_sermondistributor/views/statistic/submitbutton.js", (SermondistributorHelper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/javascript'); - JText::script('view not acceptable. Error'); } } diff --git a/admin/views/series_list/index.html b/admin/src/View/Statistic/index.html similarity index 100% rename from admin/views/series_list/index.html rename to admin/src/View/Statistic/index.html diff --git a/admin/src/View/Statistics/HtmlView.php b/admin/src/View/Statistics/HtmlView.php new file mode 100644 index 00000000..ebb08c02 --- /dev/null +++ b/admin/src/View/Statistics/HtmlView.php @@ -0,0 +1,232 @@ + + @copyright Copyright (C) 2015. All Rights Reserved + @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html + + A sermon distributor that links to Dropbox. + +/----------------------------------------------------------------------------------------------------------------------------------*/ +namespace TrueChristianChurch\Component\Sermondistributor\Administrator\View\Statistics; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Toolbar\Toolbar; +use Joomla\CMS\Form\FormHelper; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\FileLayout; +use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\Toolbar\ToolbarHelper; +use Joomla\CMS\Document\Document; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; +use VDM\Joomla\Utilities\ArrayHelper; +use VDM\Joomla\Utilities\StringHelper; + +// No direct access to this file +\defined('_JEXEC') or die; + +/** + * Sermondistributor Html View class for the Statistics + * + * @since 1.6 + */ +class HtmlView extends BaseHtmlView +{ + /** + * Statistics view display method + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + * @since 1.6 + */ + public function display($tpl = null) + { + // Assign data to the view + $this->items = $this->get('Items'); + $this->pagination = $this->get('Pagination'); + $this->state = $this->get('State'); + $this->styles = $this->get('Styles'); + $this->scripts = $this->get('Scripts'); + $this->user ??= Factory::getApplication()->getIdentity(); + // Load the filter form from xml. + $this->filterForm = $this->get('FilterForm'); + // Load the active filters. + $this->activeFilters = $this->get('ActiveFilters'); + // Add the list ordering clause. + $this->listOrder = $this->escape($this->state->get('list.ordering', 'a.id')); + $this->listDirn = $this->escape($this->state->get('list.direction', 'DESC')); + $this->saveOrder = $this->listOrder == 'a.ordering'; + // set the return here value + $this->return_here = urlencode(base64_encode((string) Uri::getInstance())); + // get global action permissions + $this->canDo = SermondistributorHelper::getActions('statistic'); + $this->canEdit = $this->canDo->get('statistic.edit'); + $this->canState = $this->canDo->get('statistic.edit.state'); + $this->canCreate = $this->canDo->get('statistic.create'); + $this->canDelete = $this->canDo->get('statistic.delete'); + $this->canBatch = ($this->canDo->get('statistic.batch') && $this->canDo->get('core.batch')); + + // If we don't have items we load the empty state + if (is_array($this->items) && !count((array) $this->items) && $this->isEmptyState = $this->get('IsEmptyState')) + { + $this->setLayout('emptystate'); + } + + // We don't need toolbar in the modal window. + if ($this->getLayout() !== 'modal') + { + $this->addToolbar(); + } + + // Check for errors. + if (count($errors = $this->get('Errors'))) + { + throw new \Exception(implode("\n", $errors), 500); + } + + // Set the html view document stuff + $this->_prepareDocument(); + + // Display the template + parent::display($tpl); + } + + /** + * Add the page title and toolbar. + * + * @return void + * @since 1.6 + */ + protected function addToolbar(): void + { + ToolbarHelper::title(Text::_('COM_SERMONDISTRIBUTOR_STATISTICS'), 'bars'); + + if ($this->canCreate) + { + ToolbarHelper::addNew('statistic.add'); + } + + // Only load if there are items + if (ArrayHelper::check($this->items)) + { + if ($this->canEdit) + { + ToolbarHelper::editList('statistic.edit'); + } + + if ($this->canState) + { + ToolbarHelper::publishList('statistics.publish'); + ToolbarHelper::unpublishList('statistics.unpublish'); + ToolbarHelper::archiveList('statistics.archive'); + + if ($this->canDo->get('core.admin')) + { + ToolbarHelper::checkin('statistics.checkin'); + } + } + + if ($this->state->get('filter.published') == -2 && ($this->canState && $this->canDelete)) + { + ToolbarHelper::deleteList('', 'statistics.delete', 'JTOOLBAR_EMPTY_TRASH'); + } + elseif ($this->canState && $this->canDelete) + { + ToolbarHelper::trash('statistics.trash'); + } + } + + // set help url for this view if found + $this->help_url = SermondistributorHelper::getHelpUrl('statistics'); + if (StringHelper::check($this->help_url)) + { + ToolbarHelper::help('COM_SERMONDISTRIBUTOR_HELP_MANAGER', false, $this->help_url); + } + + // add the options comp button + if ($this->canDo->get('core.admin') || $this->canDo->get('core.options')) + { + ToolbarHelper::preferences('com_sermondistributor'); + } + } + + /** + * Prepare some document related stuff. + * + * @return void + * @since 1.6 + */ + protected function _prepareDocument(): void + { + $this->getDocument()->setTitle(Text::_('COM_SERMONDISTRIBUTOR_STATISTICS')); + // add styles + foreach ($this->styles as $style) + { + Html::_('stylesheet', $style, ['version' => 'auto']); + } + // add scripts + foreach ($this->scripts as $script) + { + Html::_('script', $script, ['version' => 'auto']); + } + } + + /** + * Escapes a value for output in a view script. + * + * @param mixed $var The output to escape. + * @param bool $shorten The switch to shorten. + * @param int $length The shorting length. + * + * @return mixed The escaped value. + * @since 1.6 + */ + public function escape($var, bool $shorten = true, int $length = 50) + { + if (!is_string($var)) + { + return $var; + } + + return StringHelper::html($var, $this->_charset ?? 'UTF-8', $shorten, $length); + } + + /** + * Returns an array of fields the table can be sorted by + * + * @return array containing the field name to sort by as the key and display text as value + * @since 1.6 + */ + protected function getSortFields() + { + return array( + 'a.ordering' => Text::_('JGRID_HEADING_ORDERING'), + 'a.published' => Text::_('JSTATUS'), + 'a.filename' => Text::_('COM_SERMONDISTRIBUTOR_STATISTIC_FILENAME_LABEL'), + 'g.name' => Text::_('COM_SERMONDISTRIBUTOR_STATISTIC_SERMON_LABEL'), + 'h.name' => Text::_('COM_SERMONDISTRIBUTOR_STATISTIC_PREACHER_LABEL'), + 'i.name' => Text::_('COM_SERMONDISTRIBUTOR_STATISTIC_SERIES_LABEL'), + 'a.counter' => Text::_('COM_SERMONDISTRIBUTOR_STATISTIC_COUNTER_LABEL'), + 'a.id' => Text::_('JGRID_HEADING_ID') + ); + } +} diff --git a/admin/views/series_list/tmpl/index.html b/admin/src/View/Statistics/index.html similarity index 100% rename from admin/views/series_list/tmpl/index.html rename to admin/src/View/Statistics/index.html diff --git a/admin/views/sermon/tmpl/index.html b/admin/src/View/index.html similarity index 100% rename from admin/views/sermon/tmpl/index.html rename to admin/src/View/index.html diff --git a/admin/views/sermondistributor/index.html b/admin/src/index.html similarity index 100% rename from admin/views/sermondistributor/index.html rename to admin/src/index.html diff --git a/admin/views/external_source/tmpl/edit.php b/admin/tmpl/external_source/default.php similarity index 88% rename from admin/views/external_source/tmpl/edit.php rename to admin/tmpl/external_source/default.php index c44e77f8..1266c2d1 100644 --- a/admin/views/external_source/tmpl/edit.php +++ b/admin/tmpl/external_source/default.php @@ -10,10 +10,10 @@ /------------------------------------------------------------------------------------------------------------------------------------/ - @version 2.1.x + @version 5.0.x @created 22nd October, 2015 @package Sermon Distributor - @subpackage edit.php + @subpackage default.php @author Llewellyn van der Merwe @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html @@ -22,92 +22,92 @@ /----------------------------------------------------------------------------------------------------------------------------------*/ -// No direct access to this file -defined('_JEXEC') or die('Restricted access'); +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\HTML\HTMLHelper as Html; +use Joomla\CMS\Layout\LayoutHelper; +use Joomla\CMS\Router\Route; +use TrueChristianChurch\Component\Sermondistributor\Administrator\Helper\SermondistributorHelper; + +/** @var Joomla\CMS\WebAsset\WebAssetManager $wa */ +$wa = $this->getDocument()->getWebAssetManager(); +$wa->useScript('keepalive')->useScript('form.validate'); +Html::_('bootstrap.tooltip'); + +// No direct access to this file +defined('_JEXEC') or die; -JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html'); -JHtml::_('behavior.formvalidator'); -JHtml::_('formbehavior.chosen', 'select'); -JHtml::_('behavior.keepalive'); -$componentParams = $this->params; // will be removed just use $this->params instead ?>