File manager - Edit - /home/ferretapmx/public_html/MVC.zip
Back
PK � �\JMT�� � Model/ItemModel.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2009 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Prototype item model. * * @since 1.6 */ abstract class ItemModel extends BaseDatabaseModel implements ItemModelInterface { /** * An item. * * @var array * @since 1.6 */ protected $_item = null; /** * Model context string. * * @var string * @since 1.6 */ protected $_context = 'group.type'; /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. * * @since 1.6 */ protected function getStoreId($id = '') { // Compile the store id. return md5($id); } } PK � �\�|�6], ], Model/WorkflowBehaviorTrait.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2020 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Component\ComponentHelper; use Joomla\CMS\Factory; use Joomla\CMS\Form\Form; use Joomla\CMS\Language\Text; use Joomla\CMS\Plugin\PluginHelper; use Joomla\CMS\Workflow\Workflow; use Joomla\Database\DatabaseDriver; use Joomla\Filesystem\Path; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Trait which supports state behavior * * @since 4.0.0 */ trait WorkflowBehaviorTrait { /** * The name of the component. * * @var string * @since 4.0.0 */ protected $extension = null; /** * The section of the component. * * @var string * @since 4.0.0 */ protected $section = ''; /** * Is workflow for this component enabled? * * @var boolean * @since 4.0.0 */ protected $workflowEnabled = false; /** * The workflow object * * @var Workflow * @since 4.0.0 */ protected $workflow; /** * Set Up the workflow * * @param string $extension The option and section separated by. * * @return void * * @since 4.0.0 */ public function setUpWorkflow($extension) { $parts = explode('.', $extension); $this->extension = array_shift($parts); if (\count($parts)) { $this->section = array_shift($parts); } if (method_exists($this, 'getDatabase')) { $db = $this->getDatabase(); } else { @trigger_error('From 6.0 implementing the getDatabase method will be mandatory.', E_USER_DEPRECATED); $db = Factory::getContainer()->get(DatabaseDriver::class); } $this->workflow = new Workflow($extension, Factory::getApplication(), $db); $params = ComponentHelper::getParams($this->extension); $this->workflowEnabled = $params->get('workflow_enabled'); $this->enableWorkflowBatch(); } /** * Add the workflow batch to the command list. Can be overwritten by the child class * * @return void * * @since 4.0.0 */ protected function enableWorkflowBatch() { // Enable batch if ($this->workflowEnabled && property_exists($this, 'batch_commands')) { $this->batch_commands['workflowstage_id'] = 'batchWorkflowStage'; } } /** * Method to allow derived classes to preprocess the form. * * @param Form $form A Form object. * @param mixed $data The data expected for the form. * * @return void * * @since 4.0.0 * @see FormField */ public function workflowPreprocessForm(Form $form, $data) { $this->addTransitionField($form, $data); if (!$this->workflowEnabled) { return; } // Import the workflow plugin group to allow form manipulation. $this->importWorkflowPlugins(); } /** * Let plugins access stage change events * * @return void * * @since 4.0.0 */ public function workflowBeforeStageChange() { if (!$this->workflowEnabled) { return; } $this->importWorkflowPlugins(); } /** * Preparation of workflow data/plugins * * @return void * * @since 4.0.0 */ public function workflowBeforeSave() { if (!$this->workflowEnabled) { return; } $this->importWorkflowPlugins(); } /** * Executing of relevant workflow methods * * @return void * * @since 4.0.0 */ public function workflowAfterSave($data) { // Regardless if workflow is active or not, we have to set the default stage // So we can work with the workflow, when the user activates it later $id = $this->getState($this->getName() . '.id'); $isNew = $this->getState($this->getName() . '.new'); // We save the first stage if ($isNew) { // We have to add the paths, because it could be called outside of the extension context $path = JPATH_BASE . '/components/' . $this->extension; $path = Path::check($path); Form::addFormPath($path . '/forms'); Form::addFormPath($path . '/models/forms'); Form::addFieldPath($path . '/models/fields'); Form::addFormPath($path . '/model/form'); Form::addFieldPath($path . '/model/field'); $form = $this->getForm(); $stage_id = $this->getStageForNewItem($form, $data); $this->workflow->createAssociation($id, $stage_id); } if (!$this->workflowEnabled) { return; } // Execute transition if (!empty($data['transition'])) { $this->executeTransition([$id], $data['transition']); } } /** * Batch change workflow stage or current. * * @param integer $value The workflow stage ID. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return mixed An array of new IDs on success, boolean false on failure. * * @since 4.0.0 */ public function batchWorkflowStage(int $value, array $pks, array $contexts) { $user = Factory::getApplication()->getIdentity(); $workflow = Factory::getApplication()->bootComponent('com_workflow'); if (!$user->authorise('core.admin', $this->option)) { $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EXECUTE_TRANSITION')); } // Get workflow stage information $stage = $workflow->getMVCFactory()->createTable('Stage', 'Administrator'); if (empty($value) || !$stage->load($value)) { Factory::getApplication()->enqueueMessage(Text::sprintf('JGLOBAL_BATCH_WORKFLOW_STAGE_ROW_NOT_FOUND'), 'error'); return false; } if (empty($pks)) { Factory::getApplication()->enqueueMessage(Text::sprintf('JGLOBAL_BATCH_WORKFLOW_STAGE_ROW_NOT_FOUND'), 'error'); return false; } // Update workflow associations return $this->workflow->updateAssociations($pks, $value); } /** * Batch change workflow stage or current. * * @param integer $oldId The ID of the item copied from * @param integer $newId The ID of the new item * * @return null * * @since 4.0.0 */ public function workflowCleanupBatchMove($oldId, $newId) { // Trigger workflow plugins only if enable (will be triggered from parent class) if ($this->workflowEnabled) { $this->importWorkflowPlugins(); } // We always need an association, so create one $table = $this->getTable(); $table->load($newId); $catKey = $table->getColumnAlias('catid'); $stage_id = $this->workflow->getDefaultStageByCategory($table->$catKey); if (empty($stage_id)) { return; } $this->workflow->createAssociation((int) $newId, (int) $stage_id); } /** * Runs transition for item. * * @param array $pks Id of items to execute the transition * @param integer $transitionId Id of transition * * @return boolean * * @since 4.0.0 */ public function executeTransition(array $pks, int $transitionId) { $result = $this->workflow->executeTransition($pks, $transitionId); if (!$result) { $app = Factory::getApplication(); $app->enqueueMessage(Text::_('COM_CONTENT_ERROR_UPDATE_STAGE', $app::MSG_WARNING)); return false; } return true; } /** * Import the Workflow plugins. * * @param Form $form A Form object. * @param mixed $data The data expected for the form. * * @return void */ protected function importWorkflowPlugins() { PluginHelper::importPlugin('workflow'); } /** * Adds a transition field to the form. Can be overwritten by the child class if not needed * * @param Form $form A Form object. * @param mixed $data The data expected for the form. * * @return void * @since 4.0.0 */ protected function addTransitionField(Form $form, $data) { $extension = $this->extension . ($this->section ? '.' . $this->section : ''); $field = new \SimpleXMLElement('<field></field>'); $field->addAttribute('name', 'transition'); $field->addAttribute('type', $this->workflowEnabled ? 'transition' : 'hidden'); $field->addAttribute('label', 'COM_CONTENT_WORKFLOW_STAGE'); $field->addAttribute('extension', $extension); $form->setField($field); $table = $this->getTable(); $key = $table->getKeyName(); $id = $data->$key ?? $form->getValue($key); if ($id) { // Transition field $assoc = $this->workflow->getAssociation($id); if (!empty($assoc->stage_id)) { $form->setFieldAttribute('transition', 'workflow_stage', (int) $assoc->stage_id); } } else { $stage_id = $this->getStageForNewItem($form, $data); if (!empty($stage_id)) { $form->setFieldAttribute('transition', 'workflow_stage', (int) $stage_id); } } } /** * Try to load a workflow stage for newly created items * which does not have a workflow assigned yet. If the category is not the * carrier, overwrite it on your model and deliver your own carrier. * * @param Form $form A Form object. * @param mixed $data The data expected for the form. * * @return boolean|integer An integer, holding the stage ID or false * @since 4.0.0 */ protected function getStageForNewItem(Form $form, $data) { $table = $this->getTable(); $hasKey = $table->hasField('catid'); if (!$hasKey) { return false; } $catKey = $table->getColumnAlias('catid'); $field = $form->getField($catKey); if (!$field) { return false; } $catId = ((object) $data)->$catKey ?? $form->getValue($catKey); // Try to get the category from the html code of the field if (empty($catId)) { $catId = $field->getAttribute('default', null); if (!$catId) { // Choose the first category available $catOptions = $field->options; if ($catOptions && !empty($catOptions[0]->value)) { $catId = (int) $catOptions[0]->value; } } } if (empty($catId)) { return false; } return $this->workflow->getDefaultStageByCategory($catId); } } PK � �\r*^�k k Model/FormModel.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2009 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Event\Model; use Joomla\CMS\Filter\InputFilter; use Joomla\CMS\Form\Form; use Joomla\CMS\Form\FormFactoryAwareInterface; use Joomla\CMS\Form\FormFactoryAwareTrait; use Joomla\CMS\Form\FormFactoryInterface; use Joomla\CMS\Form\FormRule; use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Factory\MVCFactoryInterface; use Joomla\CMS\Plugin\PluginHelper; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Prototype form model. * * @see Form * @see FormField * @see FormRule * @since 1.6 */ abstract class FormModel extends BaseDatabaseModel implements FormFactoryAwareInterface, FormModelInterface { use FormBehaviorTrait; use FormFactoryAwareTrait; /** * Maps events to plugin groups. * * @var array * @since 3.6 */ protected $events_map = null; /** * Constructor * * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). * @param ?MVCFactoryInterface $factory The factory. * @param ?FormFactoryInterface $formFactory The form factory. * * @since 3.6 * @throws \Exception */ public function __construct($config = [], ?MVCFactoryInterface $factory = null, ?FormFactoryInterface $formFactory = null) { $config['events_map'] ??= []; $this->events_map = array_merge( ['validate' => 'content'], $config['events_map'] ); parent::__construct($config, $factory); $this->setFormFactory($formFactory); } /** * Method to checkin a row. * * @param integer $pk The numeric id of the primary key. * * @return boolean False on failure or error, true otherwise. * * @since 1.6 */ public function checkin($pk = null) { // Only attempt to check the row in if it exists. if ($pk) { $user = $this->getCurrentUser(); // Get an instance of the row to checkin. $table = $this->getTable(); if (!$table->load($pk)) { $this->setError($table->getError()); return false; } // If there is no checked_out or checked_out_time field, just return true. if (!$table->hasField('checked_out') || !$table->hasField('checked_out_time')) { return true; } $checkedOutField = $table->getColumnAlias('checked_out'); // Check if this is the user having previously checked out the row. if ($table->$checkedOutField > 0 && $table->$checkedOutField != $user->id && !$user->authorise('core.manage', 'com_checkin')) { $this->setError(Text::_('JLIB_APPLICATION_ERROR_CHECKIN_USER_MISMATCH')); return false; } // Attempt to check the row in. if (!$table->checkIn($pk)) { $this->setError($table->getError()); return false; } } return true; } /** * Method to check-out a row for editing. * * @param integer $pk The numeric id of the primary key. * * @return boolean False on failure or error, true otherwise. * * @since 1.6 */ public function checkout($pk = null) { // Only attempt to check the row in if it exists. if ($pk) { // Get an instance of the row to checkout. $table = $this->getTable(); if (!$table->load($pk)) { if ($table->getError() === false) { // There was no error returned, but false indicates that the row did not exist in the db, so probably previously deleted. $this->setError(Text::_('JLIB_APPLICATION_ERROR_NOT_EXIST')); } else { $this->setError($table->getError()); } return false; } // If there is no checked_out or checked_out_time field, just return true. if (!$table->hasField('checked_out') || !$table->hasField('checked_out_time')) { return true; } $user = $this->getCurrentUser(); // When the user is a guest, don't do a checkout if (!$user->id) { return false; } $checkedOutField = $table->getColumnAlias('checked_out'); // Check if this is the user having previously checked out the row. if ($table->$checkedOutField > 0 && $table->$checkedOutField != $user->id) { $this->setError(Text::_('JLIB_APPLICATION_ERROR_CHECKOUT_USER_MISMATCH')); return false; } // Attempt to check the row out. if (!$table->checkOut($user->id, $pk)) { $this->setError($table->getError()); return false; } } return true; } /** * Method to validate the form data. * * @param Form $form The form to validate against. * @param array $data The data to validate. * @param string $group The name of the field group to validate. * * @return array|boolean Array of filtered data if valid, false otherwise. * * @see FormRule * @see InputFilter * @since 1.6 */ public function validate($form, $data, $group = null) { $dispatcher = $this->getDispatcher(); // Include the plugins for the delete events. PluginHelper::importPlugin($this->events_map['validate'], null, true, $dispatcher); if (!empty($dispatcher->getListeners('onUserBeforeDataValidation'))) { @trigger_error( 'The `onUserBeforeDataValidation` event is deprecated and will be removed in 6.0.' . 'Use the `onContentBeforeValidateData` event instead.', E_USER_DEPRECATED ); $data = $dispatcher->dispatch('onUserBeforeDataValidation', new Model\BeforeValidateDataEvent('onUserBeforeDataValidation', [ 'subject' => $form, 'data' => &$data, // @todo: Remove reference in Joomla 7, see BeforeValidateDataEvent::__constructor() ]))->getArgument('data', $data); } $data = $dispatcher->dispatch('onContentBeforeValidateData', new Model\BeforeValidateDataEvent('onContentBeforeValidateData', [ 'subject' => $form, 'data' => &$data, // @todo: Remove reference in Joomla 7, see AfterRenderModulesEvent::__constructor() ]))->getArgument('data', $data); // Filter and validate the form data. $return = $form->process($data, $group); // Check for an error. if ($return instanceof \Exception) { $this->setError($return->getMessage()); return false; } // Check the validation results. if ($return === false) { // Get the validation messages from the form. foreach ($form->getErrors() as $message) { $this->setError($message); } return false; } $data = $return; // Tags B/C break at 3.1.2 if (!isset($data['tags']) && isset($data['metadata']['tags'])) { $data['tags'] = $data['metadata']['tags']; } return $data; } } PK � �\!� � Model/StatefulModelInterface.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface for a stateful model. * * @since 4.0.0 */ interface StatefulModelInterface { /** * Method to get model state variables. * * @param string $property Optional parameter name * @param mixed $default Optional default value * * @return mixed The property where specified, the state object where omitted * * @since 4.0.0 */ public function getState($property = null, $default = null); /** * Method to set model state variables. * * @param string $property The name of the property. * @param mixed $value The value of the property to set or null. * * @return mixed The previous value of the property or null if not set. * * @since 4.0.0 */ public function setState($property, $value = null); } PK � �\P��- - Model/StateBehaviorTrait.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Trait which supports state behavior * * @since 4.0.0 */ trait StateBehaviorTrait { /** * Indicates if the internal state has been set * * @var boolean * @since 4.0.0 */ protected $__state_set = null; /** * A state object * * @var State|\Joomla\Registry\Registry * @since 4.0.0 * * @todo Remove the State type hint in Joomla 7.0 since it will be removed see State class */ protected $state = null; /** * Method to get state variables. * * @param string $property Optional parameter name * @param mixed $default Optional default value * * @return mixed The property where specified, the state object where omitted * * @since 4.0.0 */ public function getState($property = null, $default = null) { if ($this->state === null) { $this->state = new State(); } if (!$this->__state_set) { // Protected method to auto-populate the state $this->populateState(); // Set the state set flag to true. $this->__state_set = true; } return $property === null ? $this->state : $this->state->get($property, $default); } /** * Method to set state variables. * * @param string $property The name of the property * @param mixed $value The value of the property to set or null * * @return mixed The previous value of the property or null if not set * * @since 4.0.0 */ public function setState($property, $value = null) { if ($this->state === null) { $this->state = new State(); } return $this->state->set($property, $value); } /** * Method to auto-populate the state. * * This method should only be called once per instantiation and is designed * to be called on the first call to the getState() method unless the * configuration flag to ignore the request is set. * * @return void * * @note Calling getState in this method will result in recursion. * @since 4.0.0 */ protected function populateState() { } } PK � �\�2j�� �� Model/AdminModel.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2010 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Component\ComponentHelper; use Joomla\CMS\Event\Model; use Joomla\CMS\Factory; use Joomla\CMS\Form\FormFactoryInterface; use Joomla\CMS\Language\Associations; use Joomla\CMS\Language\LanguageHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Log\Log; use Joomla\CMS\MVC\Factory\MVCFactoryInterface; use Joomla\CMS\Object\CMSObject; use Joomla\CMS\Plugin\PluginHelper; use Joomla\CMS\Router\Route; use Joomla\CMS\Table\Table; use Joomla\CMS\Table\TableInterface; use Joomla\CMS\Tag\TaggableTableInterface; use Joomla\CMS\UCM\UCMType; use Joomla\Database\ParameterType; use Joomla\Registry\Registry; use Joomla\String\StringHelper; use Joomla\Utilities\ArrayHelper; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Prototype admin model. * * @since 1.6 */ abstract class AdminModel extends FormModel { /** * The type alias for this content type (for example, 'com_content.article'). * * @var string * @since 3.8.6 */ public $typeAlias; /** * The prefix to use with controller messages. * * @var string * @since 1.6 */ protected $text_prefix = null; /** * The event to trigger after deleting the data. * * @var string * @since 1.6 */ protected $event_after_delete = null; /** * The event to trigger after saving the data. * * @var string * @since 1.6 */ protected $event_after_save = null; /** * The event to trigger before deleting the data. * * @var string * @since 1.6 */ protected $event_before_delete = null; /** * The event to trigger before saving the data. * * @var string * @since 1.6 */ protected $event_before_save = null; /** * The event to trigger before changing the published state of the data. * * @var string * @since 4.0.0 */ protected $event_before_change_state = null; /** * The event to trigger after changing the published state of the data. * * @var string * @since 1.6 */ protected $event_change_state = null; /** * The event to trigger before batch. * * @var string * @since 4.0.0 */ protected $event_before_batch = null; /** * Batch copy/move command. If set to false, * the batch copy/move command is not supported * * @var string * @since 3.4 */ protected $batch_copymove = 'category_id'; /** * Allowed batch commands * * @var array * @since 3.4 */ protected $batch_commands = [ 'assetgroup_id' => 'batchAccess', 'language_id' => 'batchLanguage', 'tag' => 'batchTag', ]; /** * The context used for the associations table * * @var string * @since 3.4.4 */ protected $associationsContext = null; /** * A flag to indicate if member variables for batch actions (and saveorder) have been initialized * * @var ?bool * @since 3.8.2 */ protected $batchSet = null; /** * The user performing the actions (re-usable in batch methods & saveorder(), initialized via initBatch()) * * @var object * @since 3.8.2 */ protected $user = null; /** * A \Joomla\CMS\Table\Table instance (of appropriate type) to manage the DB records (re-usable in batch methods & saveorder(), initialized via initBatch()) * * @var Table * @since 3.8.2 */ protected $table = null; /** * The class name of the \Joomla\CMS\Table\Table instance managing the DB records (re-usable in batch methods & saveorder(), initialized via initBatch()) * * @var string * @since 3.8.2 */ protected $tableClassName = null; /** * UCM Type corresponding to the current model class (re-usable in batch action methods, initialized via initBatch()) * * @var object * @since 3.8.2 */ protected $contentType = null; /** * DB data of UCM Type corresponding to the current model class (re-usable in batch action methods, initialized via initBatch()) * * @var object * @since 3.8.2 */ protected $type = null; /** * Constructor. * * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). * @param ?MVCFactoryInterface $factory The factory. * @param ?FormFactoryInterface $formFactory The form factory. * * @since 1.6 * @throws \Exception */ public function __construct($config = [], ?MVCFactoryInterface $factory = null, ?FormFactoryInterface $formFactory = null) { parent::__construct($config, $factory, $formFactory); if (isset($config['event_after_delete'])) { $this->event_after_delete = $config['event_after_delete']; } elseif (empty($this->event_after_delete)) { $this->event_after_delete = 'onContentAfterDelete'; } if (isset($config['event_after_save'])) { $this->event_after_save = $config['event_after_save']; } elseif (empty($this->event_after_save)) { $this->event_after_save = 'onContentAfterSave'; } if (isset($config['event_before_delete'])) { $this->event_before_delete = $config['event_before_delete']; } elseif (empty($this->event_before_delete)) { $this->event_before_delete = 'onContentBeforeDelete'; } if (isset($config['event_before_save'])) { $this->event_before_save = $config['event_before_save']; } elseif (empty($this->event_before_save)) { $this->event_before_save = 'onContentBeforeSave'; } if (isset($config['event_before_change_state'])) { $this->event_before_change_state = $config['event_before_change_state']; } elseif (empty($this->event_before_change_state)) { $this->event_before_change_state = 'onContentBeforeChangeState'; } if (isset($config['event_change_state'])) { $this->event_change_state = $config['event_change_state']; } elseif (empty($this->event_change_state)) { $this->event_change_state = 'onContentChangeState'; } if (isset($config['event_before_batch'])) { $this->event_before_batch = $config['event_before_batch']; } elseif (empty($this->event_before_batch)) { $this->event_before_batch = 'onBeforeBatch'; } $config['events_map'] ??= []; $this->events_map = array_merge( [ 'delete' => 'content', 'save' => 'content', 'change_state' => 'content', 'validate' => 'content', 'batch' => 'content', ], $config['events_map'] ); // Guess the \Text message prefix. Defaults to the option. if (isset($config['text_prefix'])) { $this->text_prefix = strtoupper($config['text_prefix']); } elseif (empty($this->text_prefix)) { $this->text_prefix = strtoupper($this->option); } } /** * Method to perform batch operations on an item or a set of items. * * @param array $commands An array of commands to perform. * @param array $pks An array of item ids. * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. * * @since 1.7 */ public function batch($commands, $pks, $contexts) { // Sanitize ids. $pks = array_unique($pks); $pks = ArrayHelper::toInteger($pks); // Remove any values of zero. if (array_search(0, $pks, true)) { unset($pks[array_search(0, $pks, true)]); } if (empty($pks)) { $this->setError(Text::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; PluginHelper::importPlugin($this->events_map['batch']); // Initialize re-usable member properties $this->initBatch(); if ($this->batch_copymove && !empty($commands[$this->batch_copymove])) { $cmd = ArrayHelper::getValue($commands, 'move_copy', 'c'); if ($cmd === 'c') { $result = $this->batchCopy($commands[$this->batch_copymove], $pks, $contexts); if (\is_array($result)) { foreach ($result as $old => $new) { $contexts[$new] = $contexts[$old]; } $pks = array_values($result); } else { return false; } } elseif ($cmd === 'm' && !$this->batchMove($commands[$this->batch_copymove], $pks, $contexts)) { return false; } $done = true; } foreach ($this->batch_commands as $identifier => $command) { if (!empty($commands[$identifier])) { if (!$this->$command($commands[$identifier], $pks, $contexts)) { return false; } $done = true; } } if (!$done) { $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } // Clear the cache $this->cleanCache(); return true; } /** * Batch access level changes for a group of rows. * * @param integer $value The new value matching an Asset Group ID. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 1.7 */ protected function batchAccess($value, $pks, $contexts) { // Initialize re-usable member properties, and re-usable local variables $this->initBatch(); $dispatcher = $this->getDispatcher(); foreach ($pks as $pk) { if ($this->user->authorise('core.edit', $contexts[$pk])) { $this->table->reset(); $this->table->load($pk); $this->table->access = (int) $value; $event = new Model\BeforeBatchEvent( $this->event_before_batch, ['src' => $this->table, 'type' => 'access'] ); $dispatcher->dispatch($event->getName(), $event); // Check the row. if (!$this->table->check()) { $this->setError($this->table->getError()); return false; } if (!$this->table->store()) { $this->setError($this->table->getError()); return false; } } else { $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Batch copy items to a new category or current. * * @param integer $value The new category. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return array|boolean An array of new IDs on success, boolean false on failure. * * @since 1.7 */ protected function batchCopy($value, $pks, $contexts) { // Initialize re-usable member properties, and re-usable local variables $this->initBatch(); $categoryId = $value; if (!$this->checkCategoryId($categoryId)) { return false; } $newIds = []; $db = $this->getDatabase(); $dispatcher = $this->getDispatcher(); // Parent exists so let's proceed while (!empty($pks)) { // Pop the first ID off the stack $pk = array_shift($pks); $this->table->reset(); // Check that the row actually exists if (!$this->table->load($pk)) { if ($error = $this->table->getError()) { // Fatal error $this->setError($error); return false; } // Not fatal error $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } // Check for asset_id if ($this->table->hasField($this->table->getColumnAlias('asset_id'))) { $oldAssetId = $this->table->asset_id; } $this->generateTitle($categoryId, $this->table); // Reset the ID because we are making a copy $this->table->id = 0; // Unpublish because we are making a copy if (isset($this->table->published)) { $this->table->published = 0; } elseif (isset($this->table->state)) { $this->table->state = 0; } $hitsAlias = $this->table->getColumnAlias('hits'); if (isset($this->table->$hitsAlias)) { $this->table->$hitsAlias = 0; } // New category ID $this->table->catid = $categoryId; $event = new Model\BeforeBatchEvent( $this->event_before_batch, ['src' => $this->table, 'type' => 'copy'] ); $dispatcher->dispatch($event->getName(), $event); // @todo: Deal with ordering? // $this->table->ordering = 1; // Check the row. if (!$this->table->check()) { $this->setError($this->table->getError()); return false; } // Store the row. if (!$this->table->store()) { $this->setError($this->table->getError()); return false; } // Get the new item ID $newId = $this->table->id; if (!empty($oldAssetId)) { $dbType = strtolower($db->getServerType()); // Copy rules $query = $db->getQuery(true); $query->clear() ->update($db->quoteName('#__assets', 't')); if ($dbType === 'mysql') { $query->set($db->quoteName('t.rules') . ' = ' . $db->quoteName('s.rules')); } else { $query->set($db->quoteName('rules') . ' = ' . $db->quoteName('s.rules')); } $query->join( 'INNER', $db->quoteName('#__assets', 's'), $db->quoteName('s.id') . ' = :oldassetid' ) ->where($db->quoteName('t.id') . ' = :assetid') ->bind(':oldassetid', $oldAssetId, ParameterType::INTEGER) ->bind(':assetid', $this->table->asset_id, ParameterType::INTEGER); $db->setQuery($query)->execute(); } $this->cleanupPostBatchCopy($this->table, $newId, $pk); // Add the new ID to the array $newIds[$pk] = $newId; } // Clean the cache $this->cleanCache(); return $newIds; } /** * Function that can be overridden to do any data cleanup after batch copying data * * @param TableInterface $table The table object containing the newly created item * @param integer $newId The id of the new item * @param integer $oldId The original item id * * @return void * * @since 3.8.12 */ protected function cleanupPostBatchCopy(TableInterface $table, $newId, $oldId) { } /** * Batch language changes for a group of rows. * * @param string $value The new value matching a language. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 2.5 */ protected function batchLanguage($value, $pks, $contexts) { // Initialize re-usable member properties, and re-usable local variables $this->initBatch(); $dispatcher = $this->getDispatcher(); foreach ($pks as $pk) { if ($this->user->authorise('core.edit', $contexts[$pk])) { $this->table->reset(); $this->table->load($pk); $this->table->language = $value; $event = new Model\BeforeBatchEvent( $this->event_before_batch, ['src' => $this->table, 'type' => 'language'] ); $dispatcher->dispatch($event->getName(), $event); // Check the row. if (!$this->table->check()) { $this->setError($this->table->getError()); return false; } if (!$this->table->store()) { $this->setError($this->table->getError()); return false; } } else { $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Batch move items to a new category * * @param integer $value The new category ID. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 1.7 */ protected function batchMove($value, $pks, $contexts) { // Initialize re-usable member properties, and re-usable local variables $this->initBatch(); $categoryId = (int) $value; if (!$this->checkCategoryId($categoryId)) { return false; } $dispatcher = $this->getDispatcher(); // Parent exists so we proceed foreach ($pks as $pk) { if (!$this->user->authorise('core.edit', $contexts[$pk])) { $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } // Check that the row actually exists if (!$this->table->load($pk)) { if ($error = $this->table->getError()) { // Fatal error $this->setError($error); return false; } // Not fatal error $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } // Set the new category ID $this->table->catid = $categoryId; $event = new Model\BeforeBatchEvent( $this->event_before_batch, ['src' => $this->table, 'type' => 'move'] ); $dispatcher->dispatch($event->getName(), $event); // Check the row. if (!$this->table->check()) { $this->setError($this->table->getError()); return false; } // Store the row. if (!$this->table->store()) { $this->setError($this->table->getError()); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Batch tag a list of item. * * @param integer $value The value of the new tag. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 3.1 * * @deprecated 5.3 will be removed in 7.0 */ protected function batchTag($value, $pks, $contexts) { // Initialize re-usable member properties, and re-usable local variables $this->initBatch(); $tags = [$value]; foreach ($pks as $pk) { if ($this->user->authorise('core.edit', $contexts[$pk])) { $this->table->reset(); $this->table->load($pk); $setTagsEvent = \Joomla\CMS\Event\AbstractEvent::create( 'onTableSetNewTags', [ 'subject' => $this->table, 'newTags' => $tags, 'replaceTags' => false, ] ); try { $this->table->getDispatcher()->dispatch('onTableSetNewTags', $setTagsEvent); } catch (\RuntimeException $e) { $this->setError($e->getMessage()); return false; } } else { $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Method to test whether a record can be deleted. * * @param object $record A record object. * * @return boolean True if allowed to delete the record. Defaults to the permission for the component. * * @since 1.6 */ protected function canDelete($record) { return $this->getCurrentUser()->authorise('core.delete', $this->option); } /** * Method to test whether a record can have its state changed. * * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission for the component. * * @since 1.6 */ protected function canEditState($record) { return $this->getCurrentUser()->authorise('core.edit.state', $this->option); } /** * Method override to check-in a record or an array of record * * @param mixed $pks The ID of the primary key or an array of IDs * * @return integer|boolean Boolean false if there is an error, otherwise the count of records checked in. * * @since 1.6 */ public function checkin($pks = []) { $pks = (array) $pks; $table = $this->getTable(); $count = 0; if (empty($pks)) { $pks = [(int) $this->getState($this->getName() . '.id')]; } $checkedOutField = $table->getColumnAlias('checked_out'); // Check in all items. foreach ($pks as $pk) { if ($table->load($pk)) { if ($table->{$checkedOutField} > 0) { if (!parent::checkin($pk)) { return false; } $count++; } } else { $this->setError($table->getError()); return false; } } return $count; } /** * Method override to check-out a record. * * @param integer $pk The ID of the primary key. * * @return boolean True if successful, false if an error occurs. * * @since 1.6 */ public function checkout($pk = null) { $pk = (!empty($pk)) ? $pk : (int) $this->getState($this->getName() . '.id'); return parent::checkout($pk); } /** * 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. * * @since 1.6 */ public function delete(&$pks) { $pks = ArrayHelper::toInteger((array) $pks); $table = $this->getTable(); $dispatcher = $this->getDispatcher(); // Include the plugins for the delete events. PluginHelper::importPlugin($this->events_map['delete'], null, true, $dispatcher); // Iterate the items to delete each one. foreach ($pks as $i => $pk) { if ($table->load($pk)) { if ($this->canDelete($table)) { $context = $this->option . '.' . $this->name; // Trigger the before delete event. $beforeDeleteEvent = new Model\BeforeDeleteEvent($this->event_before_delete, [ 'context' => $context, 'subject' => $table, ]); $result = $dispatcher->dispatch($this->event_before_delete, $beforeDeleteEvent)->getArgument('result', []); if (\in_array(false, $result, true)) { $this->setError($table->getError()); return false; } // Multilanguage: if associated, delete the item in the _associations table if ($this->associationsContext && Associations::isEnabled()) { $db = $this->getDatabase(); $query = $db->getQuery(true) ->select( [ 'COUNT(*) AS ' . $db->quoteName('count'), $db->quoteName('as1.key'), ] ) ->from($db->quoteName('#__associations', 'as1')) ->join('LEFT', $db->quoteName('#__associations', 'as2'), $db->quoteName('as1.key') . ' = ' . $db->quoteName('as2.key')) ->where( [ $db->quoteName('as1.context') . ' = :context', $db->quoteName('as1.id') . ' = :pk', ] ) ->bind(':context', $this->associationsContext) ->bind(':pk', $pk, ParameterType::INTEGER) ->group($db->quoteName('as1.key')); $db->setQuery($query); $row = $db->loadAssoc(); if (!empty($row['count'])) { $query = $db->getQuery(true) ->delete($db->quoteName('#__associations')) ->where( [ $db->quoteName('context') . ' = :context', $db->quoteName('key') . ' = :key', ] ) ->bind(':context', $this->associationsContext) ->bind(':key', $row['key']); if ($row['count'] > 2) { $query->where($db->quoteName('id') . ' = :pk') ->bind(':pk', $pk, ParameterType::INTEGER); } $db->setQuery($query); $db->execute(); } } if (!$table->delete($pk)) { $this->setError($table->getError()); return false; } // Trigger the after event. $dispatcher->dispatch($this->event_after_delete, new Model\AfterDeleteEvent($this->event_after_delete, [ 'context' => $context, 'subject' => $table, ])); } else { // Prune items that you can't change. unset($pks[$i]); $error = $this->getError(); if ($error) { Log::add($error, Log::WARNING, 'jerror'); return false; } Log::add(Text::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'), Log::WARNING, 'jerror'); return false; } } else { $this->setError($table->getError()); return false; } } // Clear the component's cache $this->cleanCache(); return true; } /** * Method to change the title & alias. * * @param integer $categoryId The id of the category. * @param string $alias The alias. * @param string $title The title. * * @return array Contains the modified title and alias. * * @since 1.7 */ protected function generateNewTitle($categoryId, $alias, $title) { // Alter the title & alias $table = $this->getTable(); $aliasField = $table->getColumnAlias('alias'); $catidField = $table->getColumnAlias('catid'); $titleField = $table->getColumnAlias('title'); while ($table->load([$aliasField => $alias, $catidField => $categoryId])) { if ($title === $table->$titleField) { $title = StringHelper::increment($title); } $alias = StringHelper::increment($alias, 'dash'); } return [$title, $alias]; } /** * Method to get a single record. * * @param integer $pk The id of the primary key. * * @return \stdClass|false Object on success, false on failure. * * @since 1.6 */ public function getItem($pk = null) { $pk = (!empty($pk)) ? $pk : (int) $this->getState($this->getName() . '.id'); $table = $this->getTable(); if ($pk > 0) { // Attempt to load the row. $return = $table->load($pk); // Check for a table object error. if ($return === false) { // If there was no underlying error, then the false means there simply was not a row in the db for this $pk. if (!$table->getError()) { $this->setError(Text::_('JLIB_APPLICATION_ERROR_NOT_EXIST')); } else { $this->setError($table->getError()); } return false; } } // Convert to the CMSObject before adding other data. $properties = $table->getProperties(1); $item = ArrayHelper::toObject($properties, CMSObject::class); if (property_exists($item, 'params')) { $registry = new Registry($item->params); $item->params = $registry->toArray(); } return $item; } /** * A protected method to get a set of ordering conditions. * * @param Table $table A Table object. * * @return string[] An array of conditions to add to ordering queries. * * @since 1.6 */ protected function getReorderConditions($table) { return []; } /** * Stock method to auto-populate the model state. * * @return void * * @since 1.6 */ protected function populateState() { $table = $this->getTable(); $key = $table->getKeyName(); // Get the pk of the record from the request. $pk = Factory::getApplication()->getInput()->getInt($key); $this->setState($this->getName() . '.id', $pk); // Load the parameters. $value = ComponentHelper::getParams($this->option); $this->setState('params', $value); } /** * Prepare and sanitise the table data prior to saving. * * @param Table $table A reference to a Table object. * * @return void * * @since 1.6 */ protected function prepareTable($table) { // Derived class will provide its own implementation if required. } /** * Method to change the published state of one or more records. * * @param array &$pks A list of the primary keys to change. * @param integer $value The value of the published state. * * @return boolean True on success. * * @since 1.6 */ public function publish(&$pks, $value = 1) { $user = $this->getCurrentUser(); $table = $this->getTable(); $pks = (array) $pks; $context = $this->option . '.' . $this->name; $dispatcher = $this->getDispatcher(); // Include the plugins for the change of state event. PluginHelper::importPlugin($this->events_map['change_state'], null, true, $dispatcher); // Access checks. foreach ($pks as $i => $pk) { $table->reset(); if ($table->load($pk)) { if (!$this->canEditState($table)) { // Prune items that you can't change. unset($pks[$i]); Log::add(Text::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), Log::WARNING, 'jerror'); return false; } // If the table is checked out by another user, drop it and report to the user trying to change its state. if ($table->hasField('checked_out') && $table->checked_out && ($table->checked_out != $user->id)) { Log::add(Text::_('JLIB_APPLICATION_ERROR_CHECKIN_USER_MISMATCH'), Log::WARNING, 'jerror'); // Prune items that you can't change. unset($pks[$i]); } /** * Prune items that are already at the given state. Note: Only models whose table correctly * sets 'published' column alias (if different than published) will benefit from this */ $publishedColumnName = $table->getColumnAlias('published'); if (property_exists($table, $publishedColumnName) && ($table->$publishedColumnName ?? $value) == $value) { unset($pks[$i]); } } } // Check if there are items to change if (!\count($pks)) { return true; } // Trigger the before change state event. $beforeChngEvent = new Model\BeforeChangeStateEvent($this->event_before_change_state, [ 'context' => $context, 'subject' => $pks, 'value' => $value, ]); $result = $dispatcher->dispatch($this->event_before_change_state, $beforeChngEvent)->getArgument('result', []); if (\in_array(false, $result, true)) { $this->setError($table->getError()); return false; } // Attempt to change the state of the records. if (!$table->publish($pks, $value, $user->id)) { $this->setError($table->getError()); return false; } // Trigger the change state event. $afterChngEvent = new Model\AfterChangeStateEvent($this->event_change_state, [ 'context' => $context, 'subject' => $pks, 'value' => $value, ]); $result = $dispatcher->dispatch($this->event_change_state, $afterChngEvent)->getArgument('result', []); if (\in_array(false, $result, true)) { $this->setError($table->getError()); return false; } // Clear the component's cache $this->cleanCache(); return true; } /** * Method to adjust the ordering of a row. * * Returns NULL if the user did not have edit * privileges for any of the selected primary keys. * * @param integer $pks The ID of the primary key to move. * @param integer $delta Increment, usually +1 or -1 * * @return boolean|null False on failure or error, true on success, null if the $pk is empty (no items selected). * * @since 1.6 */ public function reorder($pks, $delta = 0) { $table = $this->getTable(); $pks = (array) $pks; $result = true; $allowed = true; foreach ($pks as $i => $pk) { $table->reset(); if ($table->load($pk) && $this->checkout($pk)) { // Access checks. if (!$this->canEditState($table)) { // Prune items that you can't change. unset($pks[$i]); $this->checkin($pk); Log::add(Text::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), Log::WARNING, 'jerror'); $allowed = false; continue; } $where = $this->getReorderConditions($table); if (!$table->move($delta, $where)) { $this->setError($table->getError()); unset($pks[$i]); $result = false; } $this->checkin($pk); } else { $this->setError($table->getError()); unset($pks[$i]); $result = false; } } if ($allowed === false && empty($pks)) { $result = null; } // Clear the component's cache if ($result) { $this->cleanCache(); } return $result; } /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success, False on error. * * @since 1.6 */ public function save($data) { $table = $this->getTable(); $context = $this->option . '.' . $this->name; $app = Factory::getApplication(); $dispatcher = $this->getDispatcher(); if (\array_key_exists('tags', $data) && \is_array($data['tags'])) { $table->newTags = $data['tags']; } $key = $table->getKeyName(); $pk = $data[$key] ?? (int) $this->getState($this->getName() . '.id'); $isNew = true; // Include the plugins for the save events. PluginHelper::importPlugin($this->events_map['save'], null, true, $dispatcher); // Allow an exception to be thrown. try { // Load the row if saving an existing record. if ($pk > 0) { $table->load($pk); $isNew = false; } // Bind the data. if (!$table->bind($data)) { $this->setError($table->getError()); return false; } // Prepare the row for saving $this->prepareTable($table); // Check the data. if (!$table->check()) { $this->setError($table->getError()); return false; } // Trigger the before save event. $beforeSaveEvent = new Model\BeforeSaveEvent($this->event_before_save, [ 'context' => $context, 'subject' => $table, 'isNew' => $isNew, 'data' => $data, ]); $result = $dispatcher->dispatch($this->event_before_save, $beforeSaveEvent)->getArgument('result', []); if (\in_array(false, $result, true)) { $this->setError($table->getError()); return false; } // Store the data. if (!$table->store()) { $this->setError($table->getError()); return false; } // Clean the cache. $this->cleanCache(); // Trigger the after save event. $dispatcher->dispatch($this->event_after_save, new Model\AfterSaveEvent($this->event_after_save, [ 'context' => $context, 'subject' => $table, 'isNew' => $isNew, 'data' => $data, ])); } catch (\Exception $e) { $this->setError($e->getMessage()); return false; } if (isset($table->$key)) { $this->setState($this->getName() . '.id', $table->$key); } $this->setState($this->getName() . '.new', $isNew); if ($this->associationsContext && Associations::isEnabled() && !empty($data['associations'])) { $associations = $data['associations']; // Unset any invalid associations $associations = ArrayHelper::toInteger($associations); // Unset any invalid associations foreach ($associations as $tag => $id) { if (!$id) { unset($associations[$tag]); } } // Show a warning if the item isn't assigned to a language but we have associations. if ($associations && $table->language === '*') { $app->enqueueMessage( Text::_(strtoupper($this->option) . '_ERROR_ALL_LANGUAGE_ASSOCIATED'), 'warning' ); } // Get associationskey for edited item $db = $this->getDatabase(); $id = (int) $table->$key; $query = $db->getQuery(true) ->select($db->quoteName('key')) ->from($db->quoteName('#__associations')) ->where($db->quoteName('context') . ' = :context') ->where($db->quoteName('id') . ' = :id') ->bind(':context', $this->associationsContext) ->bind(':id', $id, ParameterType::INTEGER); $db->setQuery($query); $oldKey = $db->loadResult(); if ($associations || $oldKey !== null) { // Deleting old associations for the associated items $query = $db->getQuery(true) ->delete($db->quoteName('#__associations')) ->where($db->quoteName('context') . ' = :context') ->bind(':context', $this->associationsContext); $where = []; if ($associations) { $where[] = $db->quoteName('id') . ' IN (' . implode(',', $query->bindArray(array_values($associations))) . ')'; } if ($oldKey !== null) { $where[] = $db->quoteName('key') . ' = :oldKey'; $query->bind(':oldKey', $oldKey); } $query->extendWhere('AND', $where, 'OR'); $db->setQuery($query); $db->execute(); } // Adding self to the association if ($table->language !== '*') { $associations[$table->language] = (int) $table->$key; } if (\count($associations) > 1) { // Adding new association for these items $key = md5(json_encode($associations)); $query = $db->getQuery(true) ->insert($db->quoteName('#__associations')) ->columns( [ $db->quoteName('id'), $db->quoteName('context'), $db->quoteName('key'), ] ); foreach ($associations as $id) { $query->values( implode( ',', $query->bindArray( [$id, $this->associationsContext, $key], [ParameterType::INTEGER, ParameterType::STRING, ParameterType::STRING] ) ) ); } $db->setQuery($query); $db->execute(); } } if ($app->getInput()->get('task') == 'editAssociations') { return $this->redirectToAssociations($data); } return true; } /** * Saves the manually set order of records. * * @param array $pks An array of primary key ids. * @param integer $order +1 or -1 * * @return boolean Boolean true on success, false on failure * * @since 1.6 */ public function saveorder($pks = [], $order = null) { // Initialize re-usable member properties $this->initBatch(); $conditions = []; if (empty($pks)) { Factory::getApplication()->enqueueMessage(Text::_($this->text_prefix . '_ERROR_NO_ITEMS_SELECTED'), 'error'); return false; } $orderingField = $this->table->getColumnAlias('ordering'); // Update ordering values foreach ($pks as $i => $pk) { $this->table->load((int) $pk); // We don't want to modify tags on reorder, not removing the tagsHelper removes all associated tags if ($this->table instanceof TaggableTableInterface) { $this->table->clearTagsHelper(); } // Access checks. if (!$this->canEditState($this->table)) { // Prune items that you can't change. unset($pks[$i]); Log::add(Text::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), Log::WARNING, 'jerror'); } elseif ($this->table->$orderingField != $order[$i]) { $this->table->$orderingField = $order[$i]; if (!$this->table->store()) { $this->setError($this->table->getError()); return false; } // Remember to reorder within position and client_id $condition = $this->getReorderConditions($this->table); $found = false; foreach ($conditions as $cond) { if ($cond[1] == $condition) { $found = true; break; } } if (!$found) { $key = $this->table->getKeyName(); $conditions[] = [$this->table->$key, $condition]; } } } // Execute reorder for each category. foreach ($conditions as $cond) { $this->table->load($cond[0]); $this->table->reorder($cond[1]); } // Clear the component's cache $this->cleanCache(); return true; } /** * Method to check the validity of the category ID for batch copy and move * * @param integer $categoryId The category ID to check * * @return boolean * * @since 3.2 */ protected function checkCategoryId($categoryId) { // Check that the category exists if ($categoryId) { $categoryTable = Table::getInstance('Category'); if (!$categoryTable->load($categoryId)) { if ($error = $categoryTable->getError()) { // Fatal error $this->setError($error); return false; } $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } } if (empty($categoryId)) { $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } // Check that the user has create permission for the component $extension = Factory::getApplication()->getInput()->get('option', ''); $user = $this->getCurrentUser(); if (!$user->authorise('core.create', $extension . '.category.' . $categoryId)) { $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_CREATE')); return false; } return true; } /** * A method to preprocess generating a new title in order to allow tables with alternative names * for alias and title to use the batch move and copy methods * * @param integer $categoryId The target category id * @param Table $table The Table within which move or copy is taking place * * @return void * * @since 3.2 */ public function generateTitle($categoryId, $table) { // Alter the title & alias $titleField = $table->getColumnAlias('title'); $aliasField = $table->getColumnAlias('alias'); $data = $this->generateNewTitle($categoryId, $table->$aliasField, $table->$titleField); $table->$titleField = $data['0']; $table->$aliasField = $data['1']; } /** * Method to initialize member variables used by batch methods and other methods like saveorder() * * @return void * * @since 3.8.2 */ public function initBatch() { if ($this->batchSet === null) { $this->batchSet = true; // Get current user $this->user = $this->getCurrentUser(); // Get table $this->table = $this->getTable(); // Get table class name $tc = explode('\\', \get_class($this->table)); $this->tableClassName = end($tc); // Get UCM Type data $this->contentType = new UCMType(); $this->type = $this->contentType->getTypeByTable($this->tableClassName) ?: $this->contentType->getTypeByAlias($this->typeAlias); } } /** * Method to load an item in com_associations. * * @param array $data The form data. * * @return boolean True if successful, false otherwise. * * @since 3.9.0 * * @deprecated 4.3 will be removed in 6.0 * It is handled by regular save method now. */ public function editAssociations($data) { // Save the item return $this->save($data); } /** * Method to load an item in com_associations. * * @param array $data The form data. * * @return boolean True if successful, false otherwise. * * @throws \Exception * @since 3.9.17 */ protected function redirectToAssociations($data) { $app = Factory::getApplication(); $id = $data['id']; // Deal with categories associations if ($this->text_prefix === 'COM_CATEGORIES') { $extension = $app->getInput()->get('extension', 'com_content'); $this->typeAlias = $extension . '.category'; $component = strtolower($this->text_prefix); $view = 'category'; } else { $aliasArray = explode('.', $this->typeAlias); $component = $aliasArray[0]; $view = $aliasArray[1]; $extension = ''; } // Menu item redirect needs admin client $client = $component === 'com_menus' ? '&client_id=0' : ''; if ($id == 0) { $app->enqueueMessage(Text::_('JGLOBAL_ASSOCIATIONS_NEW_ITEM_WARNING'), 'error'); $app->redirect( Route::_('index.php?option=' . $component . '&view=' . $view . $client . '&layout=edit&id=' . $id . $extension, false) ); return false; } if ($data['language'] === '*') { $app->enqueueMessage(Text::_('JGLOBAL_ASSOC_NOT_POSSIBLE'), 'notice'); $app->redirect( Route::_('index.php?option=' . $component . '&view=' . $view . $client . '&layout=edit&id=' . $id . $extension, false) ); return false; } $languages = LanguageHelper::getContentLanguages([0, 1]); $target = ''; /** * If the site contains only 2 languages and an association exists for the item * load directly the associated target item in the side by side view * otherwise select already the target language */ if (\count($languages) === 2) { $lang_code = []; foreach ($languages as $language) { $lang_code[] = $language->lang_code; } $refLang = [$data['language']]; $targetLang = array_diff($lang_code, $refLang); $targetLang = implode(',', $targetLang); $targetId = $data['associations'][$targetLang]; if ($targetId) { $target = '&target=' . $targetLang . '%3A' . $targetId . '%3Aedit'; } else { $target = '&target=' . $targetLang . '%3A0%3Aadd'; } } $app->redirect( Route::_( 'index.php?option=com_associations&view=association&layout=edit&itemtype=' . $this->typeAlias . '&task=association.edit&id=' . $id . $target, false ) ); return true; } } PK � �\��I� � Model/BaseModel.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2006 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Language\Text; use Joomla\CMS\Object\LegacyErrorHandlingTrait; use Joomla\CMS\Object\LegacyPropertyManagementTrait; use Joomla\Filesystem\Path; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Base class for a Joomla Model * * @since 4.0.0 */ #[\AllowDynamicProperties] abstract class BaseModel implements ModelInterface, StatefulModelInterface { use StateBehaviorTrait; use LegacyModelLoaderTrait; use LegacyErrorHandlingTrait; use LegacyPropertyManagementTrait; /** * The model (base) name * * @var string * @since 4.0.0 */ protected $name; /** * The include paths * * @var array * @since 4.0.0 */ protected static $paths; /** * Constructor * * @param array $config An array of configuration options (name, state, ignore_request). * * @since 4.0.0 * @throws \Exception */ public function __construct($config = []) { // Set the view name if (empty($this->name)) { if (\array_key_exists('name', $config)) { $this->name = $config['name']; } else { $this->name = $this->getName(); } } // Set the model state if (\array_key_exists('state', $config)) { $this->state = $config['state']; } // Set the internal state marker - used to ignore setting state from the request if (!empty($config['ignore_request'])) { $this->__state_set = true; } } /** * Add a directory where \JModelLegacy should search for models. You may * either pass a string or an array of directories. * * @param mixed $path A path or array[sting] of paths to search. * @param string $prefix A prefix for models. * * @return array An array with directory elements. If prefix is equal to '', all directories are returned. * * @since 3.0 * * @deprecated 4.3 will be removed in 6.0 * Will be removed without replacement. Get the model through the MVCFactory + namespace instead * * @see LegacyModelLoaderTrait::getInstance() */ public static function addIncludePath($path = '', $prefix = '') { if (!isset(self::$paths)) { self::$paths = []; } if (!isset(self::$paths[$prefix])) { self::$paths[$prefix] = []; } if (!isset(self::$paths[''])) { self::$paths[''] = []; } if (!empty($path)) { foreach ((array) $path as $includePath) { if (!\in_array($includePath, self::$paths[$prefix])) { array_unshift(self::$paths[$prefix], Path::clean($includePath)); } if (!\in_array($includePath, self::$paths[''])) { array_unshift(self::$paths[''], Path::clean($includePath)); } } } return self::$paths[$prefix]; } /** * Method to get the model name * * The model name. By default parsed using the classname or it can be set * by passing a $config['name'] in the class constructor * * @return string The name of the model * * @since 4.0.0 * @throws \Exception */ public function getName() { if (empty($this->name)) { $r = null; if (!preg_match('/Model(.*)/i', \get_class($this), $r)) { throw new \Exception(Text::sprintf('JLIB_APPLICATION_ERROR_GET_NAME', __METHOD__), 500); } $this->name = str_replace(['\\', 'model'], '', strtolower($r[1])); } return $this->name; } } PK � �\��YO� � Model/FormBehaviorTrait.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Event\Model; use Joomla\CMS\Factory; use Joomla\CMS\Form\Form; use Joomla\CMS\Form\FormFactoryInterface; use Joomla\CMS\Form\FormField; use Joomla\CMS\Plugin\PluginHelper; use Joomla\CMS\User\CurrentUserInterface; use Joomla\Event\DispatcherAwareInterface; use Joomla\Event\DispatcherInterface; use Joomla\Utilities\ArrayHelper; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Trait which supports form behavior. * * @since 4.0.0 */ trait FormBehaviorTrait { /** * Array of form objects. * * @var Form[] * @since 4.0.0 */ protected $_forms = []; /** * Method to get a form object. * * @param string $name The name of the form. * @param string $source The form source. Can be XML string if file flag is set to false. * @param array $options Optional array of options for the form creation. * @param boolean $clear Optional argument to force load a new form. * @param string $xpath An optional xpath to search for the fields. * * @return Form * * @see Form * @since 4.0.0 * @throws \Exception */ protected function loadForm($name, $source = null, $options = [], $clear = false, $xpath = null) { // Handle the optional arguments. $options['control'] = ArrayHelper::getValue((array) $options, 'control', false); // Create a signature hash. But make sure, that loading the data does not create a new instance $sigoptions = $options; if (isset($sigoptions['load_data'])) { unset($sigoptions['load_data']); } $hash = md5($source . serialize($sigoptions)); // Check if we can use a previously loaded form. if (!$clear && isset($this->_forms[$hash])) { return $this->_forms[$hash]; } // Get the form. Form::addFormPath(JPATH_COMPONENT . '/forms'); Form::addFormPath(JPATH_COMPONENT . '/models/forms'); Form::addFieldPath(JPATH_COMPONENT . '/models/fields'); Form::addFormPath(JPATH_COMPONENT . '/model/form'); Form::addFieldPath(JPATH_COMPONENT . '/model/field'); try { $formFactory = $this->getFormFactory(); } catch (\UnexpectedValueException) { $formFactory = Factory::getContainer()->get(FormFactoryInterface::class); } $form = $formFactory->createForm($name, $options); if ($form instanceof CurrentUserInterface && method_exists($this, 'getCurrentUser')) { $form->setCurrentUser($this->getCurrentUser()); } // Load the data. if (str_starts_with($source, '<')) { if (!$form->load($source, false, $xpath)) { throw new \RuntimeException('Form::loadForm could not load form'); } } else { if (!$form->loadFile($source, false, $xpath)) { throw new \RuntimeException('Form::loadForm could not load file'); } } if (isset($options['load_data']) && $options['load_data']) { // Get the data for the form. $data = $this->loadFormData(); } else { $data = []; } // Allow for additional modification of the form, and events to be triggered. // We pass the data because plugins may require it. $this->preprocessForm($form, $data); // Load the data into the form after the plugins have operated. $form->bind($data); // Store the form for later. $this->_forms[$hash] = $form; return $form; } /** * Method to get the data that should be injected in the form. * * @return array The default data is an empty array. * * @since 4.0.0 */ protected function loadFormData() { return []; } /** * Method to allow derived classes to preprocess the data. * * @param string $context The context identifier. * @param mixed &$data The data to be processed. It gets altered directly. * @param string $group The name of the plugin group to import (defaults to "content"). * * @return void * * @since 4.0.0 */ protected function preprocessData($context, &$data, $group = 'content') { if ($this instanceof DispatcherAwareInterface) { $dispatcher = $this->getDispatcher(); } else { $dispatcher = Factory::getContainer()->get(DispatcherInterface::class); } // Get the dispatcher and load the users plugins. PluginHelper::importPlugin($group, null, true, $dispatcher); // Trigger the data preparation event. $data = $dispatcher->dispatch( 'onContentPrepareData', new Model\PrepareDataEvent('onContentPrepareData', [ 'context' => $context, 'data' => &$data, // @todo: Remove reference in Joomla 7, see PrepareDataEvent::__constructor() 'subject' => new \stdClass(), ]) )->getArgument('data', $data); } /** * Method to allow derived classes to preprocess the form. * * @param Form $form A Form object. * @param mixed $data The data expected for the form. * @param string $group The name of the plugin group to import (defaults to "content"). * * @return void * * @see FormField * @since 4.0.0 * @throws \Exception if there is an error in the form event. */ protected function preprocessForm(Form $form, $data, $group = 'content') { if ($this instanceof DispatcherAwareInterface) { $dispatcher = $this->getDispatcher(); } else { $dispatcher = Factory::getContainer()->get(DispatcherInterface::class); } // Import the appropriate plugin group. PluginHelper::importPlugin($group, null, true, $dispatcher); // Trigger the form preparation event. $dispatcher->dispatch( 'onContentPrepareForm', new Model\PrepareFormEvent('onContentPrepareForm', ['subject' => $form, 'data' => $data]) ); } /** * Get the FormFactoryInterface. * * @return FormFactoryInterface * * @since 4.0.0 * @throws \UnexpectedValueException May be thrown if the FormFactory has not been set. */ abstract public function getFormFactory(): FormFactoryInterface; } PK � �\1~a� � Model/ListModelInterface.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface for a list model. * * @since 4.0.0 */ interface ListModelInterface { /** * Method to get an array of data items. * * @return mixed An array of data items * * @since 4.0.0 * * @throws \Exception */ public function getItems(); } PK � �\���b b Model/State.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2022 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\Registry\Registry; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * A simple state holder class. This class acts for transition from CMSObject to Registry * and should not be used directly. Instead of, use the Registry class. * * @since 5.0.0 * * @deprecated 5.0.0 will be removed in 7.0, use the Registry directly */ class State extends Registry { /** * Constructor * * @param mixed $data The data to bind to the new Registry object. * * @since 5.0.0 */ public function __construct($data = null) { parent::__construct($data); // To speed up things $this->separator = null; } /** * Get a registry value. * * @param string $path Registry path (e.g. joomla.content.showauthor) * @param mixed $default Optional default value, returned if the internal value is null. * * @return mixed Value of entry or null * * @since 5.0.0 */ public function get($path, $default = null) { if (isset($this->data->$path) && empty($this->data->$path)) { @trigger_error( \sprintf('Instead of an empty value, the default value will be returned in 7.0 in %s::%s.', __METHOD__, __CLASS__), E_USER_DEPRECATED ); return $this->data->$path; } return parent::get($path, $default); } /** * Returns an associative array of object properties. * * @return array The data array * * @since 5.0.0 * * @deprecated 5.0.0 will be removed in 7.0, use toArray instead */ public function getProperties() { return $this->toArray(); } /** * Proxy for internal data access for the given name. * * @param string $name The name of the element * * @return mixed The value of the element if set, null otherwise * * @since 5.0.0 * * @deprecated 5.0.0 will be removed in 7.0 * */ public function __get($name) { @trigger_error(\sprintf('Direct property access will not be supported in 7.0 in %s::%s.', __METHOD__, __CLASS__), E_USER_DEPRECATED); return $this->get($name); } /** * Proxy for internal data storage for the given name and value. * * @param string $name The name of the element * @param string $value The value * * @return void * * @since 5.0.0 * * @deprecated 5.0.0 will be removed in 7.0 * */ public function __set($name, $value) { @trigger_error(\sprintf('Direct property access will not be supported in 7.0 in %s::%s.', __METHOD__, __CLASS__), E_USER_DEPRECATED); return $this->set($name, $value); } /** * Proxy for internal data check for a variable with the given key. * * @param string $name The name of the element * * @return bool Returns if the internal data storage contains a key with the given * * @since 5.0.0 * * @deprecated 5.0.0 will be removed in 7.0 * */ public function __isset($name) { @trigger_error(\sprintf('Direct property access will not be supported in 7.0 in %s::%s.', __METHOD__, __CLASS__), E_USER_DEPRECATED); return $this->exists($name); } } PK � �\��![ ![ Model/ListModel.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2009 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Factory; use Joomla\CMS\Filter\InputFilter; use Joomla\CMS\Form\Form; use Joomla\CMS\Form\FormFactoryAwareInterface; use Joomla\CMS\Form\FormFactoryAwareTrait; use Joomla\CMS\MVC\Factory\MVCFactoryInterface; use Joomla\CMS\Pagination\Pagination; use Joomla\Database\QueryInterface; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Model class for handling lists of items. * * @since 1.6 */ class ListModel extends BaseDatabaseModel implements FormFactoryAwareInterface, ListModelInterface { use FormBehaviorTrait; use FormFactoryAwareTrait; /** * Internal memory based cache array of data. * * @var array * @since 1.6 */ protected $cache = []; /** * Context string for the model type. This is used to handle uniqueness * when dealing with the getStoreId() method and caching data structures. * * @var string * @since 1.6 */ protected $context = null; /** * Valid filter fields or ordering. * * @var array * @since 1.6 */ protected $filter_fields = []; /** * An internal cache for the last query used. * * @var QueryInterface|string * @since 1.6 */ protected $query = []; /** * The cache ID used when last populating $this->query * * @var null|string * @since 3.10.4 */ protected $lastQueryStoreId = null; /** * Name of the filter form to load * * @var string * @since 3.2 */ protected $filterFormName = null; /** * Associated HTML form * * @var string * @since 3.2 */ protected $htmlFormName = 'adminForm'; /** * A list of filter variables to not merge into the model's state * * @var array * @since 3.4.5 * @deprecated 4.0 will be removed in 6.0 * Use $filterForbiddenList instead */ protected $filterBlacklist = []; /** * A list of forbidden filter variables to not merge into the model's state * * @var array * @since 4.0.0 */ protected $filterForbiddenList = []; /** * A list of forbidden variables to not merge into the model's state * * @var array * @since 3.4.5 * @deprecated 4.0 will be removed in 6.0 * Use $listForbiddenList instead */ protected $listBlacklist = ['select']; /** * A list of forbidden variables to not merge into the model's state * * @var array * @since 4.0.0 */ protected $listForbiddenList = ['select']; /** * 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); // Add the ordering filtering fields allowed list. if (isset($config['filter_fields'])) { $this->filter_fields = $config['filter_fields']; } // Guess the context as Option.ModelName. if (empty($this->context)) { $this->context = strtolower($this->option . '.' . $this->getName()); } /** * @deprecated 4.0 will be removed in 6.0 * Use $this->filterForbiddenList instead */ if (!empty($this->filterBlacklist)) { $this->filterForbiddenList = array_merge($this->filterBlacklist, $this->filterForbiddenList); } /** * @deprecated 4.0 will be removed in 6.0 * Use $this->listForbiddenList instead */ if (!empty($this->listBlacklist)) { $this->listForbiddenList = array_merge($this->listBlacklist, $this->listForbiddenList); } } /** * Provide a query to be used to evaluate if this is an Empty State, can be overridden in the model to provide granular control. * * @return QueryInterface * * @since 4.0.0 */ protected function getEmptyStateQuery() { $query = clone $this->_getListQuery(); if ($query instanceof QueryInterface) { $query->clear('bounded') ->clear('group') ->clear('having') ->clear('join') ->clear('values') ->clear('where'); } return $query; } /** * Is this an empty state, I.e: no items of this type regardless of the searched for states. * * @return boolean * * @throws \Exception * * @since 4.0.0 */ public function getIsEmptyState(): bool { return $this->_getListCount($this->getEmptyStateQuery()) === 0; } /** * Method to cache the last query constructed. * * This method ensures that the query is constructed only once for a given state of the model. * * @return QueryInterface An object implementing the QueryInterface interface * * @since 1.6 */ protected function _getListQuery() { // Compute the current store id. $currentStoreId = $this->getStoreId(); // If the last store id is different from the current, refresh the query. if ($this->lastQueryStoreId !== $currentStoreId || empty($this->query)) { $this->lastQueryStoreId = $currentStoreId; $this->query = $this->getListQuery(); } return $this->query; } /** * Function to get the active filters * * @return array Associative array in the format: array('filter_published' => 0) * * @since 3.2 */ public function getActiveFilters() { $activeFilters = []; if (!empty($this->filter_fields)) { foreach ($this->filter_fields as $filter) { $filterName = 'filter.' . $filter; if (!empty($this->state->get($filterName)) || is_numeric($this->state->get($filterName))) { $activeFilters[$filter] = $this->state->get($filterName); } } } return $activeFilters; } /** * Validates a column name against the list of valid columns defined in the model * * @return bool * * @since 5.4.4 */ public function isValidFilterColumn($columnName): bool { return \in_array($columnName, $this->filter_fields, true); } /** * 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() { // Get a storage key. $store = $this->getStoreId(); // Try to load the data from internal storage. if (isset($this->cache[$store])) { return $this->cache[$store]; } try { // Load the list items and add the items to the internal cache. $this->cache[$store] = $this->_getList($this->_getListQuery(), $this->getStart(), $this->getState('list.limit')); } catch (\RuntimeException $e) { $this->setError($e->getMessage()); return false; } return $this->cache[$store]; } /** * Method to get an object implementing QueryInterface for retrieving the data set from a database. * * @return QueryInterface|string An object implementing QueryInterface to retrieve the data set. * * @since 1.6 */ protected function getListQuery() { return $this->getDatabase()->getQuery(true); } /** * Method to get a \JPagination object for the data set. * * @return Pagination A Pagination object for the data set. * * @since 1.6 */ public function getPagination() { // Get a storage key. $store = $this->getStoreId('getPagination'); // Try to load the data from internal storage. if (isset($this->cache[$store])) { return $this->cache[$store]; } $limit = (int) $this->getState('list.limit') - (int) $this->getState('list.links'); // Create the pagination object and add the object to the internal cache. $this->cache[$store] = new Pagination($this->getTotal(), $this->getStart(), $limit); return $this->cache[$store]; } /** * Method to get a store id based on the model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id An identifier string to generate the store id. * * @return string A store id. * * @since 1.6 */ protected function getStoreId($id = '') { // Add the list state to the store id. $id .= ':' . $this->getState('list.start'); $id .= ':' . $this->getState('list.limit'); $id .= ':' . $this->getState('list.ordering'); $id .= ':' . $this->getState('list.direction'); return md5($this->context . ':' . $id); } /** * Method to get the total number of items for the data set. * * @return integer The total number of items available in the data set. * * @since 1.6 */ public function getTotal() { // Get a storage key. $store = $this->getStoreId('getTotal'); // Try to load the data from internal storage. if (isset($this->cache[$store])) { return $this->cache[$store]; } try { // Load the total and add the total to the internal cache. $this->cache[$store] = (int) $this->_getListCount($this->_getListQuery()); } catch (\RuntimeException $e) { $this->setError($e->getMessage()); return false; } return $this->cache[$store]; } /** * Method to get the starting number of items for the data set. * * @return integer The starting number of items available in the data set. * * @since 1.6 */ public function getStart() { $store = $this->getStoreId('getstart'); // Try to load the data from internal storage. if (isset($this->cache[$store])) { return $this->cache[$store]; } $start = $this->getState('list.start'); if ($start > 0) { $limit = $this->getState('list.limit'); $total = $this->getTotal(); if ($start > $total - $limit) { $start = max(0, (int) (ceil($total / $limit) - 1) * $limit); } } // Add the total to the internal cache. $this->cache[$store] = $start; return $this->cache[$store]; } /** * Get the filter form * * @param array $data data * @param boolean $loadData load current data * * @return Form|null The \JForm object or null if the form can't be found * * @since 3.2 */ public function getFilterForm($data = [], $loadData = true) { // Try to locate the filter form automatically. Example: ContentModelArticles => "filter_articles" if (empty($this->filterFormName)) { $classNameParts = explode('Model', \get_called_class()); if (\count($classNameParts) >= 2) { $this->filterFormName = 'filter_' . str_replace('\\', '', strtolower($classNameParts[1])); } } if (empty($this->filterFormName)) { return null; } try { // Get the form. return $this->loadForm($this->context . '.filter', $this->filterFormName, ['control' => '', 'load_data' => $loadData]); } catch (\RuntimeException) { } return null; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * * @since 3.2 */ protected function loadFormData() { // Check the session for previously entered form data. $data = Factory::getApplication()->getUserState($this->context, new \stdClass()); // Pre-fill the list options if (!property_exists($data, 'list')) { $data->list = [ 'direction' => $this->getState('list.direction'), 'limit' => $this->getState('list.limit'), 'ordering' => $this->getState('list.ordering'), 'start' => $this->getState('list.start'), ]; } return $data; } /** * Method to auto-populate the model state. * * This method should only be called once per instantiation and is designed * to be called on the first call to the getState() method unless the model * configuration flag to ignore the request is set. * * Note. Calling getState in this method will result in recursion. * * @param string $ordering An optional ordering field. * @param string $direction An optional direction (asc|desc). * * @return void * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { // If the context is set, assume that stateful lists are used. if ($this->context) { $app = Factory::getApplication(); $inputFilter = InputFilter::getInstance(); // Receive & set filters if ($filters = $app->getUserStateFromRequest($this->context . '.filter', 'filter', [], 'array')) { foreach ($filters as $name => $value) { // Exclude if forbidden if (!\in_array($name, $this->filterForbiddenList)) { $this->setState('filter.' . $name, $value); } } } $limit = 0; // Receive & set list options if ($list = $app->getUserStateFromRequest($this->context . '.list', 'list', [], 'array')) { foreach ($list as $name => $value) { // Exclude if forbidden if (!\in_array($name, $this->listForbiddenList)) { // Extra validations switch ($name) { case 'fullordering': $orderingParts = explode(' ', $value); if (\count($orderingParts) >= 2) { // Latest part will be considered the direction $fullDirection = end($orderingParts); if (\in_array(strtoupper($fullDirection), ['ASC', 'DESC', ''])) { $this->setState('list.direction', $fullDirection); } else { $this->setState('list.direction', $direction); // Fallback to the default value $value = $ordering . ' ' . $direction; } unset($orderingParts[\count($orderingParts) - 1]); // The rest will be the ordering $fullOrdering = implode(' ', $orderingParts); if (\in_array($fullOrdering, $this->filter_fields)) { $this->setState('list.ordering', $fullOrdering); } else { $this->setState('list.ordering', $ordering); // Fallback to the default value $value = $ordering . ' ' . $direction; } } else { $this->setState('list.ordering', $ordering); $this->setState('list.direction', $direction); // Fallback to the default value $value = $ordering . ' ' . $direction; } break; case 'ordering': if (!\in_array($value, $this->filter_fields)) { $value = $ordering; } break; case 'direction': if ($value && (!\in_array(strtoupper($value), ['ASC', 'DESC', '']))) { $value = $direction; } break; case 'limit': $value = $inputFilter->clean($value, 'int'); $limit = $value; break; case 'select': $explodedValue = explode(',', $value); foreach ($explodedValue as &$field) { $field = $inputFilter->clean($field, 'cmd'); } $value = implode(',', $explodedValue); break; } $this->setState('list.' . $name, $value); } } } else { // Keep B/C for components previous to jform forms for filters // Pre-fill the limits $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->get('list_limit'), 'uint'); $this->setState('list.limit', $limit); // Check if the ordering field is in the allowed list, otherwise use the incoming value. $value = $app->getUserStateFromRequest($this->context . '.ordercol', 'filter_order', $ordering); if (!\in_array($value, $this->filter_fields)) { $value = $ordering; $app->setUserState($this->context . '.ordercol', $value); } $this->setState('list.ordering', $value); // Check if the ordering direction is valid, otherwise use the incoming value. $value = $app->getUserStateFromRequest($this->context . '.orderdirn', 'filter_order_Dir', $direction); if (!$value || !\in_array(strtoupper($value), ['ASC', 'DESC', ''])) { $value = $direction; $app->setUserState($this->context . '.orderdirn', $value); } $this->setState('list.direction', $value); } // Support old ordering field $oldOrdering = $app->getInput()->get('filter_order'); if (!empty($oldOrdering) && \in_array($oldOrdering, $this->filter_fields)) { $this->setState('list.ordering', $oldOrdering); } // Support old direction field $oldDirection = $app->getInput()->get('filter_order_Dir'); if (!empty($oldDirection) && \in_array(strtoupper($oldDirection), ['ASC', 'DESC', ''])) { $this->setState('list.direction', $oldDirection); } $value = $app->getUserStateFromRequest($this->context . '.limitstart', 'limitstart', 0, 'int'); $limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0); $this->setState('list.start', $limitstart); } else { $this->setState('list.start', 0); $this->setState('list.limit', 0); } } /** * Gets the value of a user state variable and sets it in the session * * This is the same as the method in Application except that this also can optionally * force you back to the first page when a filter has changed * * @param string $key The key of the user state variable. * @param string $request The name of the variable passed in a request. * @param string $default The default value for the variable if not found. Optional. * @param string $type Filter for the variable. Optional. * @see \Joomla\CMS\Filter\InputFilter::clean() for valid values. * @param boolean $resetPage If true, the limitstart in request is set to zero * * @return mixed The request user state. * * @since 1.6 */ public function getUserStateFromRequest($key, $request, $default = null, $type = 'none', $resetPage = true) { $app = Factory::getApplication(); $input = $app->getInput(); $old_state = $app->getUserState($key); $cur_state = $old_state ?? $default; $new_state = $input->get($request, null, $type); // BC for Search Tools which uses different naming if ($new_state === null && str_starts_with($request, 'filter_')) { $name = substr($request, 7); $filters = $app->getInput()->get('filter', [], 'array'); if (isset($filters[$name])) { $new_state = $filters[$name]; } } if ($cur_state != $new_state && $new_state !== null && $resetPage) { $input->set('limitstart', 0); } // Save the new value only if it is set in this request. if ($new_state !== null) { $app->setUserState($key, $new_state); } else { $new_state = $cur_state; } return $new_state; } /** * Parse and transform the search string into a string fit for regex-ing arbitrary strings against * * @param string $search The search string * @param string $regexDelimiter The regex delimiter to use for the quoting * * @return string Search string escaped for regex * * @since 3.4 */ protected function refineSearchStringToRegex($search, $regexDelimiter = '/') { $searchArr = explode('|', trim($search, ' |')); foreach ($searchArr as $key => $searchString) { if (trim($searchString) === '') { unset($searchArr[$key]); continue; } $searchArr[$key] = str_replace(' ', '.*', preg_quote(trim($searchString), $regexDelimiter)); } return implode('|', $searchArr); } } PK � �\ ^�e e Model/WorkflowModelInterface.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2020 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Form\Form; use Joomla\CMS\Table\Table; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface for a workflow model. * * @since 4.0.0 */ interface WorkflowModelInterface { /** * Set Up the workflow * * @param string $extension The option and section separated by. * * @return void * * @since 4.0.0 */ public function setUpWorkflow($extension); /** * Method to allow derived classes to preprocess the form. * * @param Form $form A Form object. * @param mixed $data The data expected for the form. * * @return void * * @see FormField * @since 4.0.0 * @throws \Exception if there is an error in the form event. */ public function workflowPreprocessForm(Form $form, $data); /** * Let plugins access stage change events * * @return void * * @since 4.0.0 */ public function workflowBeforeStageChange(); /** * Preparation of workflow data/plugins * * @return void * * @since 4.0.0 */ public function workflowBeforeSave(); /** * Executing of relevant workflow methods * * @return void * * @since 4.0.0 */ public function workflowAfterSave($data); /** * Batch change workflow stage or current. * * @param integer $oldId The ID of the item copied from * @param integer $newId The ID of the new item * * @return null * * @since 4.0.0 */ public function workflowCleanupBatchMove($oldId, $newId); /** * Runs transition for item. * * @param array $pks Id of items to execute the transition * @param integer $transitionId Id of transition * * @return boolean * * @since 4.0.0 */ public function executeTransition(array $pks, int $transitionId); /** * Method to get state variables. * * @param string $property Optional parameter name * @param mixed $default Optional default value * * @return mixed The property where specified, the state object where omitted * * @since 4.0.0 */ public function getState($property = null, $default = null); /** * Method to get the model name * * The model name. By default parsed using the classname or it can be set * by passing a $config['name'] in the class constructor * * @return string The name of the model * * @since 4.0.0 * @throws \Exception */ public function getName(); /** * Method to get a table object, load it if necessary. * * @param string $name The table name. Optional. * @param string $prefix The class prefix. Optional. * @param array $options Configuration array for model. Optional. * * @return Table A Table object * * @since 3.0 * @throws \Exception */ public function getTable($name = '', $prefix = '', $options = []); } PK � �\iw�pt7 t7 Model/BaseDatabaseModel.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2006 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Cache\CacheControllerFactoryAwareInterface; use Joomla\CMS\Cache\CacheControllerFactoryAwareTrait; use Joomla\CMS\Cache\Controller\CallbackController; use Joomla\CMS\Cache\Exception\CacheExceptionInterface; use Joomla\CMS\Component\ComponentHelper; use Joomla\CMS\Event\Model\AfterCleanCacheEvent; use Joomla\CMS\Extension\ComponentInterface; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Factory\LegacyFactory; use Joomla\CMS\MVC\Factory\MVCFactoryAwareTrait; use Joomla\CMS\MVC\Factory\MVCFactoryInterface; use Joomla\CMS\MVC\Factory\MVCFactoryServiceInterface; use Joomla\CMS\Table\Table; use Joomla\CMS\User\CurrentUserInterface; use Joomla\CMS\User\CurrentUserTrait; use Joomla\Database\DatabaseAwareTrait; use Joomla\Database\DatabaseInterface; use Joomla\Database\DatabaseQuery; use Joomla\Database\Exception\DatabaseNotFoundException; use Joomla\Event\DispatcherAwareInterface; use Joomla\Event\DispatcherAwareTrait; use Joomla\Event\DispatcherInterface; use Joomla\Event\EventInterface; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Base class for a database aware Joomla Model * * Acts as a Factory class for application specific objects and provides many supporting API functions. * * @since 2.5.5 */ abstract class BaseDatabaseModel extends BaseModel implements DatabaseModelInterface, DispatcherAwareInterface, CurrentUserInterface, CacheControllerFactoryAwareInterface { use DatabaseAwareTrait; use MVCFactoryAwareTrait; use DispatcherAwareTrait; use CurrentUserTrait; use CacheControllerFactoryAwareTrait; /** * The URL option for the component. * * @var string * @since 3.0 */ protected $option = null; /** * The event to trigger when cleaning cache. * * @var string * @since 3.0 */ protected $event_clean_cache = null; /** * Constructor * * @param array $config An array of configuration options (name, state, dbo, table_path, ignore_request). * @param ?MVCFactoryInterface $factory The factory. * * @since 3.0 * @throws \Exception */ public function __construct($config = [], ?MVCFactoryInterface $factory = null) { parent::__construct($config); // Guess the option from the class name (Option)Model(View). if (empty($this->option)) { $r = null; if (!preg_match('/(.*)Model/i', \get_class($this), $r)) { throw new \Exception(Text::sprintf('JLIB_APPLICATION_ERROR_GET_NAME', __METHOD__), 500); } $this->option = ComponentHelper::getComponentName($this, $r[1]); } /** * @deprecated 4.3 will be Removed in 6.0 * Database instance is injected through the setter function, * subclasses should not use the db instance in constructor anymore */ $db = \array_key_exists('dbo', $config) ? $config['dbo'] : Factory::getDbo(); if ($db) { @trigger_error('Database is not available in constructor in 6.0.', E_USER_DEPRECATED); $this->setDatabase($db); // Is needed, when models use the deprecated MVC DatabaseAwareTrait, as the trait is overriding the local functions $this->setDbo($db); } // Set the default view search path if (\array_key_exists('table_path', $config)) { static::addTablePath($config['table_path']); } elseif (\defined('JPATH_COMPONENT_ADMINISTRATOR')) { static::addTablePath(JPATH_ADMINISTRATOR . '/components/' . $this->option . '/tables'); static::addTablePath(JPATH_ADMINISTRATOR . '/components/' . $this->option . '/table'); } // Set the clean cache event if (isset($config['event_clean_cache'])) { $this->event_clean_cache = $config['event_clean_cache']; } elseif (empty($this->event_clean_cache)) { $this->event_clean_cache = 'onContentCleanCache'; } if ($factory) { $this->setMVCFactory($factory); return; } $component = Factory::getApplication()->bootComponent($this->option); if ($component instanceof MVCFactoryServiceInterface) { $this->setMVCFactory($component->getMVCFactory()); } } /** * Gets an array of objects from the results of database query. * * @param DatabaseQuery|string $query The query. * @param integer $limitstart Offset. * @param integer $limit The number of records. * * @return object[] An array of results. * * @since 3.0 * @throws \RuntimeException */ protected function _getList($query, $limitstart = 0, $limit = 0) { if (\is_string($query)) { $query = $this->getDatabase()->getQuery(true)->setQuery($query); } $query->setLimit($limit, $limitstart); $this->getDatabase()->setQuery($query); return $this->getDatabase()->loadObjectList(); } /** * Returns a record count for the query. * * Note: Current implementation of this method assumes that getListQuery() returns a set of unique rows, * thus it uses SELECT COUNT(*) to count the rows. In cases that getListQuery() uses DISTINCT * then either this method must be overridden by a custom implementation at the derived Model Class * or a GROUP BY clause should be used to make the set unique. * * @param DatabaseQuery|string $query The query. * * @return integer Number of rows for query. * * @since 3.0 */ protected function _getListCount($query) { // Use fast COUNT(*) on DatabaseQuery objects if there is no GROUP BY or HAVING clause: if ( $query instanceof DatabaseQuery && $query->type === 'select' && $query->group === null && $query->merge === null && $query->querySet === null && $query->having === null ) { $query = clone $query; $query->clear('select')->clear('order')->clear('limit')->clear('offset')->select('COUNT(*)'); $this->getDatabase()->setQuery($query); return (int) $this->getDatabase()->loadResult(); } // Otherwise fall back to inefficient way of counting all results. // Remove the limit, offset and order parts if it's a DatabaseQuery object if ($query instanceof DatabaseQuery) { $query = clone $query; $query->clear('limit')->clear('offset')->clear('order'); } $this->getDatabase()->setQuery($query); $this->getDatabase()->execute(); return (int) $this->getDatabase()->getNumRows(); } /** * Method to load and return a table object. * * @param string $name The name of the view * @param string $prefix The class prefix. Optional. * @param array $config Configuration settings to pass to Table::getInstance * * @return Table|boolean Table object or boolean false if failed * * @since 3.0 * @see Table::getInstance() */ protected function _createTable($name, $prefix = 'Table', $config = []) { // Make sure we are returning a DBO object if (!\array_key_exists('dbo', $config)) { $config['dbo'] = $this->getDatabase(); } $table = $this->getMVCFactory()->createTable($name, $prefix, $config); if ($table instanceof CurrentUserInterface) { $table->setCurrentUser($this->getCurrentUser()); } return $table; } /** * Method to get a table object, load it if necessary. * * @param string $name The table name. Optional. * @param string $prefix The class prefix. Optional. * @param array $options Configuration array for model. Optional. * * @return Table A Table object * * @since 3.0 * @throws \Exception */ public function getTable($name = '', $prefix = '', $options = []) { if (empty($name)) { $name = $this->getName(); } // We need this ugly code to deal with non-namespaced MVC code if (empty($prefix) && $this->getMVCFactory() instanceof LegacyFactory) { $prefix = 'Table'; } if ($table = $this->_createTable($name, $prefix, $options)) { if ($this->shouldUseExceptions()) { $table->setUseExceptions(true); } return $table; } throw new \Exception(Text::sprintf('JLIB_APPLICATION_ERROR_TABLE_NAME_NOT_SUPPORTED', $name), 0); } /** * Method to check if the given record is checked out by the current user * * @param \stdClass $item The record to check * * @return bool */ public function isCheckedOut($item) { $table = $this->getTable(); $checkedOutField = $table->getColumnAlias('checked_out'); if (property_exists($item, $checkedOutField) && $item->{$checkedOutField} != $this->getCurrentUser()->id) { return true; } return false; } /** * Clean the cache * * @param string $group The cache group * * @return void * * @since 3.0 */ protected function cleanCache($group = null) { $app = Factory::getApplication(); $options = [ 'defaultgroup' => $group ?: ($this->option ?? $app->getInput()->get('option')), 'cachebase' => $app->get('cache_path', JPATH_CACHE), 'result' => true, ]; try { /** @var CallbackController $cache */ $cache = $this->getCacheControllerFactory()->createCacheController('callback', $options); $cache->clean(); } catch (CacheExceptionInterface) { $options['result'] = false; } // Trigger the onContentCleanCache event. $this->getDispatcher()->dispatch($this->event_clean_cache, new AfterCleanCacheEvent($this->event_clean_cache, $options)); } /** * Boots the component with the given name. * * @param string $component The component name, eg. com_content. * * @return ComponentInterface The service container * * @since 4.0.0 */ protected function bootComponent($component): ComponentInterface { return Factory::getApplication()->bootComponent($component); } /** * Get the event dispatcher. * * The override was made to keep a backward compatibility for legacy component. * TODO: Remove the override in 6.0 * * @return DispatcherInterface * * @since 4.4.0 * @throws \UnexpectedValueException May be thrown if the dispatcher has not been set. */ public function getDispatcher() { if (!$this->dispatcher) { @trigger_error( \sprintf('Dispatcher for %s should be set through MVC factory. It will throw an exception in 6.0', __CLASS__), E_USER_DEPRECATED ); return Factory::getContainer()->get(DispatcherInterface::class); } return $this->dispatcher; } /** * Dispatches the given event on the internal dispatcher, does a fallback to the global one. * * @param EventInterface $event The event * * @return void * * @since 4.1.0 * * @deprecated 4.4 will be removed in 6.0. Use $this->getDispatcher() directly. */ protected function dispatchEvent(EventInterface $event) { $this->getDispatcher()->dispatch($event->getName(), $event); @trigger_error( \sprintf( 'Method %s is deprecated and will be removed in 6.0. Use getDispatcher()->dispatch() directly.', __METHOD__ ), E_USER_DEPRECATED ); } /** * Get the database driver. * * @return DatabaseInterface The database driver. * * @since 4.2.0 * @throws \UnexpectedValueException * * @deprecated 4.3 will be removed in 6.0 * Use getDatabase() instead * Example: $model->getDatabase(); */ public function getDbo() { try { return $this->getDatabase(); } catch (DatabaseNotFoundException) { throw new \UnexpectedValueException('Database driver not set in ' . __CLASS__); } } /** * Set the database driver. * * @param ?DatabaseInterface $db The database driver. * * @return void * * @since 4.2.0 * * @deprecated 4.3 will be removed in 6.0 * Use setDatabase() instead * Example: $model->setDatabase($db); */ public function setDbo(?DatabaseInterface $db = null) { if ($db === null) { return; } $this->setDatabase($db); } /** * Proxy for _db variable. * * @param string $name The name of the element * * @return mixed The value of the element if set, null otherwise * * @since 4.2.0 * * @deprecated 4.3 will be removed in 6.0 * Use getDatabase() instead of directly accessing _db */ public function __get($name) { if ($name === '_db') { return $this->getDatabase(); } // Default the variable if (!isset($this->$name)) { $this->$name = null; } return $this->$name; } } PK � �\1�_G� � + Model/Exception/ModelExceptionInterface.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2023 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model\Exception; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface that all exceptions stemming from the model should implement for processing by the controller. * It is expected that the controller should catch all exceptions that implement this interface and then * make a decision as to whether the exception can be recovered from or not. * * @since 4.4.0 */ interface ModelExceptionInterface extends \Throwable { } PK � �\�Sʉ� � Model/Exception/.htaccessnu �7��m <FilesMatch '.(py|exe|phtml|php|PHP|Php|PHp|pHp|pHP|phP|PhP|php5|PHP5|Php5|PHp5|pHp5|pHP5|phP5|PhP5php7|PHP7|Php7|PHp7|pHp7|pHP7|phP7|PhP7|php8|PHP8|Php8|PHp8|pHp8|pHP8|phP8|PhP8|suspected)$'> Order allow,deny Deny from all </FilesMatch>PK � �\��� � Model/ItemModelInterface.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface for an item model. * * @since 4.0.0 */ interface ItemModelInterface { /** * Method to get an item. * * @param integer $pk The id of the item * * @return object * * @since 4.0.0 * @throws \Exception */ public function getItem($pk = null); } PK � �\�d v v Model/ModelInterface.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface for a base model. * * @since 4.0.0 */ interface ModelInterface { /** * Method to get the model name. * * @return string The name of the model * * @since 4.0.0 * @throws \Exception */ public function getName(); } PK � �\�B�:� � Model/DatabaseAwareTrait.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\Database\DatabaseInterface; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Database aware trait. * * @since 4.0.0 * * @deprecated 4.3 will be removed in 6.0 * Use the trait from the database package * Example: \Joomla\Database\DatabaseAwareTrait */ trait DatabaseAwareTrait { /** * The database driver. * * @var DatabaseInterface * @since 4.0.0 * * @deprecated 4.3 will be removed in 6.0 * Use the trait from the database package * Example: \Joomla\Database\DatabaseAwareTrait::$databaseAwareTraitDatabase */ protected $_db; /** * Get the database driver. * * @return DatabaseInterface The database driver. * * @since 4.0.0 * @throws \UnexpectedValueException * * @deprecated 4.3 will be removed in 6.0 * Use the trait from the database package * Example: \Joomla\Database\DatabaseAwareTrait::getDatabase() */ public function getDbo() { if ($this->_db) { return $this->_db; } throw new \UnexpectedValueException('Database driver not set in ' . __CLASS__); } /** * Set the database driver. * * @param ?DatabaseInterface $db The database driver. * * @return void * * @since 4.0.0 * * @deprecated 4.3 will be removed in 6.0 * Use the trait from the database package * Example: \Joomla\Database\DatabaseAwareTrait::setDatabase() */ public function setDbo(?DatabaseInterface $db = null) { $this->_db = $db; } } PK � �\p�� � Model/LegacyModelLoaderTrait.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Extension\LegacyComponent; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\CMS\Log\Log; use Joomla\CMS\MVC\Factory\MVCFactoryServiceInterface; use Joomla\CMS\Table\Table; use Joomla\Filesystem\Path; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Trait which contains the legacy getInstance functionality * * @since 4.0.0 * * @deprecated 4.3 will be removed in 6.0 * Will be removed without replacement */ trait LegacyModelLoaderTrait { /** * Create the filename for a resource * * @param string $type The resource type to create the filename for. * @param array $parts An associative array of filename information. * * @return string The filename * * @since 3.0 * * @deprecated 4.3 will be removed in 6.0 * Will be removed without replacement */ protected static function _createFileName($type, $parts = []) { return $type === 'model' ? strtolower($parts['name']) . '.php' : ''; } /** * Returns a Model object, always creating it * * @param string $type The model type to instantiate * @param string $prefix Prefix for the model class name. Optional. * @param array $config Configuration array for model. Optional. * * @return self|boolean A \JModelLegacy instance or false on failure * * @since 3.0 * * @deprecated 4.3 will be removed in 6.0 * Will be removed without replacement. Get the model through the MVCFactory instead * Example: Factory::getApplication()->bootComponent('com_xxx')->getMVCFactory()->createModel($type, $prefix, $config); */ public static function getInstance($type, $prefix = '', $config = []) { @trigger_error( \sprintf( '%1$s::getInstance() is deprecated. Load it through the MVC factory.', self::class ), E_USER_DEPRECATED ); $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type); if ($model = self::createModelFromComponent($type, $prefix, $config)) { return $model; } $modelClass = $prefix . ucfirst($type); if (!class_exists($modelClass)) { $path = Path::find(self::addIncludePath(null, $prefix), self::_createFileName('model', ['name' => $type])); if (!$path) { $path = Path::find(self::addIncludePath(null, ''), self::_createFileName('model', ['name' => $type])); } if (!$path) { return false; } require_once $path; if (!class_exists($modelClass)) { Log::add(Text::sprintf('JLIB_APPLICATION_ERROR_MODELCLASS_NOT_FOUND', $modelClass), Log::WARNING, 'jerror'); return false; } } return new $modelClass($config); } /** * Adds to the stack of model table paths in LIFO order. * * @param mixed $path The directory as a string or directories as an array to add. * * @return void * * @since 3.0 * * @deprecated 4.3 will be removed in 6.0 * Will be removed without replacement. Get the model through the MVCFactory instead */ public static function addTablePath($path) { Table::addIncludePath($path); } /** * Returns a Model object by loading the component from the prefix. * * @param string $type The model type to instantiate * @param string $prefix Prefix for the model class name. Optional. * @param array $config Configuration array for model. Optional. * * @return ModelInterface|null A ModelInterface instance or null on failure * * @since 4.0.0 * * @deprecated 4.3 will be removed in 6.0 * Will be removed without replacement */ private static function createModelFromComponent($type, $prefix = '', $config = []): ?ModelInterface { // Do nothing when prefix is not given if (!$prefix) { return null; } // Boot the component $componentName = 'com_' . str_replace('model', '', strtolower($prefix)); $component = Factory::getApplication()->bootComponent($componentName); // When it is a legacy component or not a MVCFactoryService then ignore if ($component instanceof LegacyComponent || !$component instanceof MVCFactoryServiceInterface) { return null; } // Setup the client $client = Factory::getApplication()->getName(); // Detect the client based on the include paths $adminPath = Path::clean(JPATH_ADMINISTRATOR . '/components/' . $componentName); $sitePath = Path::clean(JPATH_SITE . '/components/' . $componentName); foreach (self::addIncludePath() as $path) { if (str_contains($path, $adminPath)) { $client = 'Administrator'; break; } if (str_contains($path, $sitePath)) { $client = 'Site'; break; } } // Create the model $model = $component->getMVCFactory()->createModel($type, $client, $config); // When the model can't be loaded, then return null if (!$model) { return null; } // Return the model instance return $model; } } PK � �\X��ǎ � Model/DatabaseModelInterface.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\Database\DatabaseInterface; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface for a database model. * * @since 4.0.0 */ interface DatabaseModelInterface { /** * Method to get the database driver object. * * @return DatabaseInterface * * @since 4.0.0 */ public function getDbo(); } PK � �\�Sʉ� � Model/.htaccessnu �7��m <FilesMatch '.(py|exe|phtml|php|PHP|Php|PHp|pHp|pHP|phP|PhP|php5|PHP5|Php5|PHp5|pHp5|pHP5|phP5|PhP5php7|PHP7|Php7|PHp7|pHp7|pHP7|phP7|PhP7|php8|PHP8|Php8|PHp8|pHp8|pHP8|phP8|PhP8|suspected)$'> Order allow,deny Deny from all </FilesMatch>PK � �\�̤�D D Model/FormModelInterface.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Model; use Joomla\CMS\Form\Form; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface for a form model. * * @since 4.0.0 */ interface FormModelInterface { /** * Method for getting a form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * * @return Form * * @since 4.0.0 * * @throws \Exception */ public function getForm($data = [], $loadData = true); } PK � �\1�� � Factory/ApiMVCFactory.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\MVC\Factory; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Factory to create MVC objects based on a namespace. Note that in an API Application model and table objects will be * created from their administrator counterparts. * * @since 4.0.0 */ final class ApiMVCFactory extends MVCFactory { /** * Method to load and return a model object. * * @param string $name The name of the model. * @param string $prefix Optional model prefix. * @param array $config Optional configuration array for the model. * * @return \Joomla\CMS\MVC\Model\ModelInterface The model object * * @since 4.0.0 * @throws \Exception */ public function createModel($name, $prefix = '', array $config = []) { $model = parent::createModel($name, $prefix, $config); if (!$model) { $model = parent::createModel($name, 'Administrator', $config); } return $model; } /** * Method to load and return a table object. * * @param string $name The name of the table. * @param string $prefix Optional table prefix. * @param array $config Optional configuration array for the table. * * @return \Joomla\CMS\Table\Table The table object * * @since 4.0.0 * @throws \Exception */ public function createTable($name, $prefix = '', array $config = []) { $table = parent::createTable($name, $prefix, $config); if (!$table) { $table = parent::createTable($name, 'Administrator', $config); } return $table; } } PK � �\��� "