สร้าง Component สำหรับ Joomla 2.5 การสร้าง ACL (Access Control List)

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: สร้าง Component สำหรับ Joomla 2.5 การสร้าง ACL (Access Control List)

Re: สร้าง Component สำหรับ Joomla 2.5 การสร้าง ACL (Access Control List)

โดย tsukasaz » 11/05/2012 3:03 pm

ดูการแสดงผล ในหน้าของ component Hello World จะมี tab ของ permissions เพิ่มเข้ามา
แนบไฟล์
acl1 (Small).JPG
acl1 (Small).JPG (38.11 KiB) Viewed 4028 times

Re: สร้าง Component สำหรับ Joomla 2.5 การสร้าง ACL (Access Control List)

โดย tsukasaz » 11/05/2012 2:56 pm

เข้าไปในโฟลเดอร์ admin -> models เปิดไฟล์ helloworld.php แก้โค้ด

โค้ด: เลือกทั้งหมด

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla modelform library
jimport('joomla.application.component.modeladmin');
 
/**
 * HelloWorld Model
 */
class HelloWorldModelHelloWorld extends JModelAdmin
{
    /**
     * Method override to check if you can edit an existing record.
     *
     * @param    array    $data    An array of input data.
     * @param    string    $key    The name of the key for the primary key.
     *
     * @return    boolean
     * @since    2.5
     */
    protected function allowEdit($data = array(), $key = 'id')
    {
        // Check specific edit permission then general edit permission.
        return JFactory::getUser()->authorise('core.edit', 'com_helloworld.message.'.
                                              ((int) isset($data[$key]) ? $data[$key] : 0))
               or parent::allowEdit($data, $key);
    }
    /**
     * Returns a reference to the a Table object, always creating it.
     *
     * @param    type    The table type to instantiate
     * @param    string    A prefix for the table class name. Optional.
     * @param    array    Configuration array for model. Optional.
     * @return    JTable    A database object
     * @since    2.5
     */
    public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array()) 
    {
        return JTable::getInstance($type, $prefix, $config);
    }
    /**
     * Method to get the record 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    mixed    A JForm object on success, false on failure
     * @since    2.5
     */
    public function getForm($data = array(), $loadData = true) 
    {
        // Get the form.
        $form = $this->loadForm('com_helloworld.helloworld', 'helloworld',
                                array('control' => 'jform', 'load_data' => $loadData));
        if (empty($form)) 
        {
            return false;
        }
        return $form;
    }
    /**
     * Method to get the script that have to be included on the form
     *
     * @return string    Script files
     */
    public function getScript() 
    {
        return 'administrator/components/com_helloworld/models/forms/helloworld.js';
    }
    /**
     * Method to get the data that should be injected in the form.
     *
     * @return    mixed    The data for the form.
     * @since    2.5
     */
    protected function loadFormData() 
    {
        // Check the session for previously entered form data.
        $data = JFactory::getApplication()->getUserState('com_helloworld.edit.helloworld.data', array());
        if (empty($data)) 
        {
            $data = $this->getItem();
        }
        return $data;
    }
} 
เปิดโฟลเดอร์ admin -> tables แก้โค้ด helloworld.php

โค้ด: เลือกทั้งหมด

<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
 
// import Joomla table library
jimport('joomla.database.table');
 
/**
 * Hello Table class
 */
class HelloWorldTableHelloWorld extends JTable
{
    /**
     * Constructor
     *
     * @param object Database connector object
     */
    function __construct(&$db) 
    {
        parent::__construct('#__helloworld', 'id', $db);
    }
    /**
     * Overloaded bind function
     *
     * @param       array           named array
     * @return      null|string     null is operation was satisfactory, otherwise returns an error
     * @see JTable:bind
     * @since 1.5
     */
    public function bind($array, $ignore = '') 
    {
        if (isset($array['params']) && is_array($array['params'])) 
        {
            // Convert the params field to a string.
            $parameter = new JRegistry;
            $parameter->loadArray($array['params']);
            $array['params'] = (string)$parameter;
        }
 
        // Bind the rules.
        if (isset($array['rules']) && is_array($array['rules']))
        {
            $rules = new JAccessRules($array['rules']);
            $this->setRules($rules);
        }
 
        return parent::bind($array, $ignore);
    }
 
    /**
     * Overloaded load function
     *
     * @param       int $pk primary key
     * @param       boolean $reset reset data
     * @return      boolean
     * @see JTable:load
     */
    public function load($pk = null, $reset = true) 
    {
        if (parent::load($pk, $reset)) 
        {
            // Convert the params field to a registry.
            $params = new JRegistry;
            $params->loadJSON($this->params);
            $this->params = $params;
            return true;
        }
        else
        {
            return false;
        }
    }
    /**
     * Method to compute the default name of the asset.
     * The default name is in the form `table_name.id`
     * where id is the value of the primary key of the table.
     *
     * @return    string
     * @since    2.5
     */
    protected function _getAssetName()
    {
        $k = $this->_tbl_key;
        return 'com_helloworld.message.'.(int) $this->$k;
    }
 
    /**
     * Method to return the title to use for the asset table.
     *
     * @return    string
     * @since    2.5
     */
    protected function _getAssetTitle()
    {
        return $this->greeting;
    }
 
    /**
     * Get the parent asset id for the record
     *
     * @return    int
     * @since    2.5
     */
    protected function _getAssetParentId()
    {
        $asset = JTable::getInstance('Asset');
        $asset->loadByName('com_helloworld');
        return $asset->id;
    }
} 
เปิดโฟลเดอร์ admin -> views -> helloworld -> tmpl -> edit.php

โค้ด: เลือกทั้งหมด

<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
$params = $this->form->getFieldsets('params');
?>
<form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id='.(int) $this->item->id); ?>"
      method="post" name="adminForm" id="helloworld-form" class="form-validate">
 
   <div class="width-60 fltlft">
      <fieldset class="adminform">
         <legend><?php echo JText::_( 'COM_HELLOWORLD_HELLOWORLD_DETAILS' ); ?></legend>
         <ul class="adminformlist">
            <?php foreach($this->form->getFieldset('details') as $field): ?>
               <li><?php echo $field->label;echo $field->input;?></li>
            <?php endforeach; ?>
         </ul>
      </fieldset>
   </div>
 
   <div class="width-40 fltrt">
      <?php echo JHtml::_('sliders.start', 'helloworld-slider');
         foreach ($params as $name => $fieldset):
            echo JHtml::_('sliders.panel', JText::_($fieldset->label), $name.'-params');
            if (isset($fieldset->description) && trim($fieldset->description)): ?>
               <p class="tip"><?php echo $this->escape(JText::_($fieldset->description));?></p>
            <?php endif;?>
            <fieldset class="panelform" >
               <ul class="adminformlist">
                  <?php foreach ($this->form->getFieldset($name) as $field) : ?>
                     <li><?php echo $field->label; ?><?php echo $field->input; ?></li>
                  <?php endforeach; ?>
               </ul>
            </fieldset>
         <?php endforeach; ?>
 
      <?php echo JHtml::_('sliders.end'); ?>
   </div>
 
 
   <!-- begin ACL definition-->
 
   <div class="clr"></div>
 
   <?php if ($this->canDo->get('core.admin')): ?>
      <div class="width-100 fltlft">
         <?php echo JHtml::_('sliders.start', 'permissions-sliders-'.$this->item->id, array('useCookie'=>1)); ?>
 
            <?php echo JHtml::_('sliders.panel', JText::_('COM_HELLOWORLD_FIELDSET_RULES'), 'access-rules'); ?>
            <fieldset class="panelform">
               <?php echo $this->form->getLabel('rules'); ?>
               <?php echo $this->form->getInput('rules'); ?>
            </fieldset>
 
         <?php echo JHtml::_('sliders.end'); ?>
      </div>
   <?php endif; ?>
 
   <!-- end ACL definition-->
 
   <div>
      <input type="hidden" name="task" value="helloworld.edit" />
      <?php echo JHtml::_('form.token'); ?>
   </div>
</form>
เปิด helloworld.xml มาแก้โค้ดใหม่

โค้ด: เลือกทั้งหมด

<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="2.5.0" method="upgrade">
 
	<name>COM_HELLOWORLD</name>
	<!-- The following elements are optional and free of formatting constraints -->
	<creationDate>November 2009</creationDate>
	<author>John Doe</author>
	<authorEmail>[email protected]</authorEmail>
	<authorUrl>http://www.example.org</authorUrl>
	<copyright>Copyright Info</copyright>
	<license>License Info</license>
	<!--  The version string is recorded in the components table -->
	<version>0.0.14</version>
	<!-- The description is optional and defaults to the name -->
	<description>COM_HELLOWORLD_DESCRIPTION</description>
 
	<install> <!-- Runs on install -->
		<sql>
			<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
		</sql>
	</install>
	<uninstall> <!-- Runs on uninstall -->
		<sql>
			<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>
		</sql>
	</uninstall>
	<update> <!-- Runs on update; New in 2.5 -->
		<schemas>
			<schemapath type="mysql">sql/updates/mysql</schemapath>
		</schemas>
	</update>
 
	<!-- Site Main File Copy Section -->
	<!-- Note the folder attribute: This attribute describes the folder
		to copy FROM in the package to install therefore files copied
		in this section are copied from /site/ in the package -->
	<files folder="site">
		<filename>index.html</filename>
		<filename>helloworld.php</filename>
		<filename>controller.php</filename>
		<folder>views</folder>
		<folder>models</folder>
		<folder>language</folder>
	</files>
 
	<media destination="com_helloworld" folder="media">
		<filename>index.html</filename>
		<folder>images</folder>
	</media>
 
	<administration>
		<!-- Administration Menu Section -->
		<menu img="../media/com_helloworld/images/tux-16x16.png">COM_HELLOWORLD_MENU</menu>
		<!-- Administration Main File Copy Section -->
		<!-- Note the folder attribute: This attribute describes the folder
			to copy FROM in the package to install therefore files copied
			in this section are copied from /admin/ in the package -->
		<files folder="admin">
			<!-- Admin Main File Copy Section -->
			<filename>index.html</filename>
			<filename>config.xml</filename>
			<filename>access.xml</filename>
			<filename>helloworld.php</filename>
			<filename>controller.php</filename>
			<!-- SQL files section -->
			<folder>sql</folder>
			<!-- tables files section -->
			<folder>tables</folder>
			<!-- models files section -->
			<folder>models</folder>
			<!-- views files section -->
			<folder>views</folder>
			<!-- controllers files section -->
			<folder>controllers</folder>
			<!-- helpers files section -->
			<folder>helpers</folder>
		</files>
 
		<languages folder="admin">
			<language tag="en-GB">language/en-GB/en-GB.com_helloworld.ini</language>
			<language tag="en-GB">language/en-GB/en-GB.com_helloworld.sys.ini</language>
		</languages>
	</administration>
 
</extension>
ทำเป็น .zip แล้ว เข้าไปหน้าของ administrator ไปเพิ่ม extensions เข้าไปใหม่

สร้าง Component สำหรับ Joomla 2.5 การสร้าง ACL (Access Control List)

โดย tsukasaz » 11/05/2012 2:53 pm

ข้อมูลเกี่ยวกับ ACL (Access Control List)

เริ่มจากสร้างไฟล์ access.xml ในโฟลเดอร์ admin

โค้ด: เลือกทั้งหมด

<?xml version="1.0" encoding="utf-8" ?>
<access component="com_helloworld">
	<section name="component">
		<action name="core.admin" title="JACTION_ADMIN" description="JACTION_ADMIN_COMPONENT_DESC" />
		<action name="core.manage" title="JACTION_MANAGE" description="JACTION_MANAGE_COMPONENT_DESC" />
		<action name="core.create" title="JACTION_CREATE" description="JACTION_CREATE_COMPONENT_DESC" />
		<action name="core.delete" title="JACTION_DELETE" description="JACTION_DELETE_COMPONENT_DESC" />
		<action name="core.edit" title="JACTION_EDIT" description="JACTION_EDIT_COMPONENT_DESC" />
	</section>
	<section name="message">
		<action name="core.delete" title="JACTION_DELETE" description="COM_HELLOWORLD_ACCESS_DELETE_DESC" />
		<action name="core.edit" title="JACTION_EDIT" description="COM_HELLOWORLD_ACCESS_EDIT_DESC" />
	</section>
</access>
แล้วแก้โค้ดในไฟล์ helloworld.php

โค้ด: เลือกทั้งหมด

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// Access check.
if (!JFactory::getUser()->authorise('core.manage', 'com_helloworld')) 
{
    return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
}
 
// require helper file
JLoader::register('HelloWorldHelper', dirname(__FILE__) . DS . 'helpers' . DS . 'helloworld.php');
 
// import joomla controller library
jimport('joomla.application.component.controller');
 
// Get an instance of the controller prefixed by HelloWorld
$controller = JController::getInstance('HelloWorld');
 
// Perform the Request task
$controller->execute(JRequest::getCmd('task'));
 
// Redirect if set by the controller
$controller->redirect(); 
สร้าง toolbar โดยเข้าไปที่โฟลเดอร์ admin -> views -> helloworlds เปิดไฟล์ view.html.php แก้โค้ด

โค้ด: เลือกทั้งหมด

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla view library
jimport('joomla.application.component.view');
 
/**
 * HelloWorlds View
 */
class HelloWorldViewHelloWorlds extends JView
{
    /**
     * HelloWorlds view display method
     * @return void
     */
    function display($tpl = null) 
    {
        // Get data from the model
        $items = $this->get('Items');
        $pagination = $this->get('Pagination');
 
        // Check for errors.
        if (count($errors = $this->get('Errors'))) 
        {
            JError::raiseError(500, implode('<br />', $errors));
            return false;
        }
        // Assign data to the view
        $this->items = $items;
        $this->pagination = $pagination;
 
        // Set the toolbar
        $this->addToolBar();
 
        // Display the template
        parent::display($tpl);
 
        // Set the document
        $this->setDocument();
    }
 
    /**
     * Setting the toolbar
     */
    protected function addToolBar() 
    {
        $canDo = HelloWorldHelper::getActions();
        JToolBarHelper::title(JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLDS'), 'helloworld');
        if ($canDo->get('core.create')) 
        {
            JToolBarHelper::addNew('helloworld.add', 'JTOOLBAR_NEW');
        }
        if ($canDo->get('core.edit')) 
        {
            JToolBarHelper::editList('helloworld.edit', 'JTOOLBAR_EDIT');
        }
        if ($canDo->get('core.delete')) 
        {
            JToolBarHelper::deleteList('', 'helloworlds.delete', 'JTOOLBAR_DELETE');
        }
        if ($canDo->get('core.admin')) 
        {
            JToolBarHelper::divider();
            JToolBarHelper::preferences('com_helloworld');
        }
    }
    /**
     * Method to set up the document properties
     *
     * @return void
     */
    protected function setDocument() 
    {
        $document = JFactory::getDocument();
        $document->setTitle(JText::_('COM_HELLOWORLD_ADMINISTRATION'));
    }
} 
และในโฟลเดอร์ admin -> views -> helloworld เปิดไฟล์ view.html.php

โค้ด: เลือกทั้งหมด

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla view library
jimport('joomla.application.component.view');
 
/**
 * HelloWorld View
 */
class HelloWorldViewHelloWorld extends JView
{
    /**
     * display method of Hello view
     * @return void
     */
    public function display($tpl = null) 
    {
        // get the Data
        $form = $this->get('Form');
        $item = $this->get('Item');
        $script = $this->get('Script');
 
        // Check for errors.
        if (count($errors = $this->get('Errors'))) 
        {
            JError::raiseError(500, implode('<br />', $errors));
            return false;
        }
        // Assign the Data
        $this->form = $form;
        $this->item = $item;
        $this->script = $script;
 
        // Set the toolbar
        $this->addToolBar();
 
        // Display the template
        parent::display($tpl);
 
        // Set the document
        $this->setDocument();
    }
 
    /**
     * Setting the toolbar
     */
    protected function addToolBar() 
    {
        JRequest::setVar('hidemainmenu', true);
        $user = JFactory::getUser();
        $userId = $user->id;
        $isNew = $this->item->id == 0;
        $canDo = HelloWorldHelper::getActions($this->item->id);
        JToolBarHelper::title($isNew ? JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW')
                                     : JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT'), 'helloworld');
        // Built the actions for new and existing records.
        if ($isNew) 
        {
            // For new records, check the create permission.
            if ($canDo->get('core.create')) 
            {
                JToolBarHelper::apply('helloworld.apply', 'JTOOLBAR_APPLY');
                JToolBarHelper::save('helloworld.save', 'JTOOLBAR_SAVE');
                JToolBarHelper::custom('helloworld.save2new', 'save-new.png', 'save-new_f2.png',
                                       'JTOOLBAR_SAVE_AND_NEW', false);
            }
            JToolBarHelper::cancel('helloworld.cancel', 'JTOOLBAR_CANCEL');
        }
        else
        {
            if ($canDo->get('core.edit'))
            {
                // We can save the new record
                JToolBarHelper::apply('helloworld.apply', 'JTOOLBAR_APPLY');
                JToolBarHelper::save('helloworld.save', 'JTOOLBAR_SAVE');
 
                // We can save this record, but check the create permission to see
                // if we can return to make a new one.
                if ($canDo->get('core.create')) 
                {
                    JToolBarHelper::custom('helloworld.save2new', 'save-new.png', 'save-new_f2.png',
                                           'JTOOLBAR_SAVE_AND_NEW', false);
                }
            }
            if ($canDo->get('core.create')) 
            {
                JToolBarHelper::custom('helloworld.save2copy', 'save-copy.png', 'save-copy_f2.png',
                                       'JTOOLBAR_SAVE_AS_COPY', false);
            }
            JToolBarHelper::cancel('helloworld.cancel', 'JTOOLBAR_CLOSE');
        }
    }
    /**
     * Method to set up the document properties
     *
     * @return void
     */
    protected function setDocument() 
    {
        $isNew = $this->item->id == 0;
        $document = JFactory::getDocument();
        $document->setTitle($isNew ? JText::_('COM_HELLOWORLD_HELLOWORLD_CREATING')
                                   : JText::_('COM_HELLOWORLD_HELLOWORLD_EDITING'));
        $document->addScript(JURI::root() . $this->script);
        $document->addScript(JURI::root() . "/administrator/components/com_helloworld"
                                          . "/views/helloworld/submitbutton.js");
        JText::script('COM_HELLOWORLD_HELLOWORLD_ERROR_UNACCEPTABLE');
    }
} 
เปิดโฟลเดอร์ admin -> helpers แก้ไฟล์ helloworld.php

โค้ด: เลือกทั้งหมด

<?php
// No direct access to this file
defined('_JEXEC') or die;
 
/**
 * HelloWorld component helper.
 */
abstract class HelloWorldHelper
{
    /**
     * Configure the Linkbar.
     */
    public static function addSubmenu($submenu) 
    {
        JSubMenuHelper::addEntry(JText::_('COM_HELLOWORLD_SUBMENU_MESSAGES'),
                                 'index.php?option=com_helloworld', $submenu == 'messages');
        JSubMenuHelper::addEntry(JText::_('COM_HELLOWORLD_SUBMENU_CATEGORIES'),
                                 'index.php?option=com_categories&view=categories&extension=com_helloworld',
                                 $submenu == 'categories');
        // set some global property
        $document = JFactory::getDocument();
        $document->addStyleDeclaration('.icon-48-helloworld ' .
                                       '{background-image: url(../media/com_helloworld/images/tux-48x48.png);}');
        if ($submenu == 'categories') 
        {
            $document->setTitle(JText::_('COM_HELLOWORLD_ADMINISTRATION_CATEGORIES'));
        }
    }
    /**
     * Get the actions
     */
    public static function getActions($messageId = 0)
    {    
        jimport('joomla.access.access');
        $user    = JFactory::getUser();
        $result    = new JObject;
 
        if (empty($messageId)) {
            $assetName = 'com_helloworld';
        }
        else {
            $assetName = 'com_helloworld.message.'.(int) $messageId;
        }
 
        $actions = JAccess::getActions('com_helloworld', 'component');
 
        foreach ($actions as $action) {
            $result->set($action->name, $user->authorise($action->name, $assetName));
        }
 
        return $result;
    }
} 
ในโฟลเดอร์ admin แ้้ก้ไฟล์ config.xml

โค้ด: เลือกทั้งหมด

<?xml version="1.0" encoding="utf-8"?>
<config>
	<fieldset
		name="greetings"
		label="COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_LABEL"
		description="COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_DESC"
	>
		<field
			name="show_category"
			type="radio"
			label="COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_LABEL"
			description="COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_DESC"
			default="0"
		>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>
	</fieldset>
	<fieldset
		name="permissions"
		label="JCONFIG_PERMISSIONS_LABEL"
		description="JCONFIG_PERMISSIONS_DESC"
	>
		<field
			name="rules"
			type="rules"
			label="JCONFIG_PERMISSIONS_LABEL"
			class="inputbox"
			validate="rules"
			filter="rules"
			component="com_helloworld"
			section="component"
		/>
	</fieldset>
</config>

ข้างบน