IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » joomla The latest public joomla snipts.

showing 1-20 of 20 snipts for joomla
  • search class
    <?php
    /**
     * @version   $Id: search.php 1040 2010-04-16 11:20:57Z torkil $
     * @package   Author
     * @copyright Copyright (C) 2009 BEDRE reklame. All rights reserved.
     * @license   GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
     * @link      http://www.bedre.no
     * @todo      If areas are not passed to the constructor, this whole class will fail miserably
     */
    
    require_once(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_search'.DS.'helpers'.DS.'search.php');
    require_once(JPATH_SITE.DS.'components'.DS.'com_author'.DS.'router.php');
    
    class SearchModel extends KModelDefault
    {
        /**
         * Constructor.
         * @param array $options
         * @todo Needs to be fed $options['areas']. Have to either require this or drop an exception
         *       or try to make the class more independent or self-sufficient
         */
        public function __construct(array $options = array())
        {
            parent::__construct($options);
            $this->_initializeScopeVars($options);
            $this->component = $this->getClassName('prefix');
        }
    
        /**
         * This is called when the class observes an event it is supposed to respond to
         *
         * @param array $args
         * @return mixed
         */
        public function update(array $args = array())
        {
            if (isset($args['event']) && method_exists($this, $args['event'])) {
                $event = $args['event'];
                return $this->$event($args);
            }
        }
    
        /**
         * onSearch event observed
         *
         * @param <type> $args
         * @return <type>
         */
        public function onSearch($args)
        {
            call_user_func_array(array($this, '_setArgs'), $args);
            $this->_setSearchScope($this->args['areas']);
    
            $results = array();
    
            if ($this->_shouldSearch()) {
                $results = $this->_getSearchResults();
            }
    
            return $results;
        }
    
        /**
         * Triggered by observable pattern when search areas are pulled from the plugin
         *
         * @param array $args
         * @return array Areas this class can search
         */
        public function onSearchAreas($args)
        {
            return $this->areas;
        }
    
        protected function _setArgs($text, $phrase, $order, $areas, $event)
        {
            $args['text']   = $text;
            $args['phrase'] = $phrase;
            $args['order']  = $order;
            $args['areas']  = $areas;
            $args['event']  = $event;
            $args['words']  = $this->_getSearchWords($args['text'], $args['phrase']);
            $this->args     = $args;
        }
    
        protected function _getSearchResults()
        {
            foreach ($this->scope as $area) {
                $modelName      = KInflector::pluralize($area);
                $table          = KFactory::get('admin::com.'.$this->component.'.model.'.$modelName)->getTable();
                $params         = $this->_getPluginParams();
                $query          = $this->_buildSearchQuery($area);
    
                $results[$area] = $table->fetchAll(
                                      $query,
                                      0,
                                      $params->def('search_limit', 50)
                                  );
            }
    
            return $this->_cleanupSearchResults($results);
        }
    
        protected function _buildSearchQuery($area)
        {
            $modelName  = KInflector::pluralize($area);
            $model      = KFactory::get('admin::com.'.$this->component.'.model.'.$modelName);
    
            if (method_exists($model, '_buildSearchQuery')) {
                return $model->_buildSearchQuery($this);
            } else {
                $query = $this->_db->getQuery();
                $key   = $model->getTable()->getPrimaryKey();
    
                $this->_buildSearchQueryFields($query, $area);
                $this->_buildSearchQueryFrom($query, $area);
                $this->_buildSearchQueryWhere($query, $area);
    
                return $query;
            }
        }
    
        protected function _cleanupSearchResults($results)
        {
            $articles = array();
    
            foreach ($results as $area => $areaResult) {
                if (count($areaResult)) {
                    foreach ($areaResult as $row) {
                        $article             = new stdClass();
                        $article->title      = $row->title;
                        $article->text       = isset($row->text) ? strip_tags($row->text) : '';
                        $article->href       = $this->_buildRoute($row, $area);
                        $article->created    = isset($row->created) ? $row->created : '';
                        $article->browsernav = '';
                        $article->section    = '';
                        $articles[] = $article;
                    }
                }
            }
    
            return $articles;
        }
    
        protected function _buildRoute($article, $area)
        {
            $view   = KInflector::singularize($area);
            $idName = $this->component.'_'.$view.'_id';
            return JRoute::_('index.php?option=com_'.$this->component.'&view='.$view.'&id='.$article->$idName.'&Itemid='.AuthorRouter::getItemId($view, $article->$idName));
        }
    
        /**
         * Select what columns to return from the search
         *
         * @param KDatabaseQuery $query
         * @param string $area
         */
        protected function _buildSearchQueryFields(KDatabaseQuery $query, $area)
        {
            $modelName  = KInflector::pluralize($area);
            $model      = KFactory::get('admin::com.'.$this->component.'.model.'.$modelName);
    
            if (method_exists($model, '_buildSearchQueryFields')) {
                $model->_buildSearchQueryFields($query);
            } else {
                $columns = $model->getTable()->getColumns();
                if (in_array(array('title', 'text'), $columns)) {
                    $query->select('title', 'text');
                } else {
                    $query->select();
                }
            }
        }
    
        protected function _buildSearchQueryFrom(KDatabaseQuery $query, $area)
        {
            $modelName = KInflector::pluralize($area);
            $model     = KFactory::get('admin::com.'.$this->component.'.model.'.$modelName);
        	$name      = $model->getTable()->getTableName();
        	$query->from($name.' AS tbl');
        }
    
        /**
         * Loop through all searchwords, and for each word, match that word against the searchable
         * columns in this area (read: table).
         *
         * @param KDatabaseQuery $query
         * @param string $area
         */
        protected function _buildSearchQueryWhere(KDatabaseQuery $query, $area)
        {
            // Search specific restrictions
            $fields = $this->_getSearchableFields($area);
    
            $whereWords = array();
            foreach ($this->args['words'] as $word) {
    
                $whereFields = array();
    
                foreach ($fields as $fieldName => $fieldDescription) {
                    $whereFields[] = $fieldName .' LIKE '. $word;
                }
    
                $whereWords[] = '(' . implode( ') OR (', $whereFields ) . ')';
            }
    
            if (count($whereWords) > 1) {
                $whereQuery = '(' . implode(($this->args['phrase'] == 'all' ? ') AND (' : ') OR ('), $whereWords) . ')';
            } else {
                $whereQuery = '(' . $whereWords[0] . ')';
            }
    
            $query->where = array_unique(array_merge($query->where, array($whereQuery)));
    
            // Model specific restrictions
            $modelName  = KInflector::pluralize($area);
            $model      = KFactory::get('admin::com.'.$this->component.'.model.'.$modelName);
    
            if (method_exists($model, '_buildSearchQueryWhere')) {
                $model->_buildSearchQueryWhere($query);
            }
        }
    
        /**
         * Trim and cast the searchstring to array
         *
         * @param string $searchString
         * @param string $searchType Ideally it should be exact, all or any
         * @return array
         */
        protected function _getSearchWords($searchString, $searchType)
        {
            $searchString = trim($searchString);
    
            if ($searchString != '') {
    
                switch ($searchType) {
                    case 'exact':
                        $words = array($searchString);
                        break;
                    case 'all':
                    case 'any':
                    default:
                        $words = explode(' ', $searchString);
                        $words = array_unique($words); // no need to query the same word twice
                        break;
                }
    
                foreach ($words as $key => $word) {
                    $words[$key] = $this->_db->Quote('%'.$this->_db->getEscaped($word, true).'%', false);
                }
    
            } else {
                $words = '';
            }
    
            return $words;
        }
    
        /**
         * Initialize scope vars if they are passed as options in the constructor
         *
         * @param array $options
         */
        protected function _initializeScopeVars(array $options = array())
        {
            $scopeVars = array ('areas', 'searchableFieldTypes', 'searchableFields');
    
            foreach ($scopeVars as $var) {
                if (isset($options[$var]) && is_array($options[$var])) {
                    $this->$var = $options[$var];
                }
            }
        }
    
        protected function _shouldSearch()
        {
            if (!count($this->scope)) {
                return false;
            }
    
            if ($this->args['words'] == '') {
                return false;
            }
    
            return true;
        }
    
        /**
         * Scope is an array with the areas we will search through.
         *
         * @param array $areas
         */
        protected function _setSearchScope()
        {
            if ($this->args['areas'] === null) {
                // Search all areas
                $this->scope = array_keys($this->areas);
            } elseif (is_array($this->args['areas'])) {
                // Scope equals the intersection between the searched areas and the available areas
                $this->scope = array_intersect($this->args['areas'], array_keys($this->areas));
            } else {
                $this->scope = array();
            }
        }
    
        /**
         * Fieldtypes are the types of fields we can search
         *
         * @return <type>
         */
        protected function _getSearchableFieldTypes()
        {
            if (!isset($this->searchableFieldTypes)) {
                $this->searchableFieldTypes = array('string', 'text');
            }
    
            return $this->searchableFieldTypes;
        }
    
        /**
         * Returns a two-level array with overview of what table columns we can search in all of the
         * given areas (read: table) of the scope
         *
         * @return array
         */
        protected function _getSearchableFields($filterArea = null)
        {
            if (!isset($this->searchableFields)) {
    
                if (!isset($this->scope)) {
                    $this->_setSearchScope();
                }
    
                foreach ($this->scope as $area) {
                    $this->searchableFields[$area] = $this->_getSearchableFieldsFromTable($area);
                }
            }
    
            if ($filterArea === null) {
                return $this->searchableFields;
            } elseif (array_key_exists($filterArea, $this->searchableFields)) {
                return $this->searchableFields[$filterArea];
            } else {
                return false;
            }
        }
    
        /**
         * Collects all columns from a table and returns only those who area searchable
         *
         * @param string $area
         * @return array
         */
        protected function _getSearchableFieldsFromTable($area)
        {
            $modelName = KInflector::pluralize($area);
            $model     = KFactory::get('admin::com.'.$this->component.'.model.'.$modelName);
            $table     = $model->getTable();
    
            if (method_exists($table, 'getSearchableFields')) {
                $fields = array_flip($table->getSearchableFields());
            } else {
                $fields = $table->getFields();
                
                foreach ($fields as $name => $description) {
                    if (!in_array($fields[$name]->type, $this->_getSearchableFieldTypes())) {
                        unset($fields[$name]);
                    }
                }
            }
    
            return $fields;
        }
    
        protected function _getPluginParams()
        {
            if (!isset($this->params)) {
                $plugin       = JPluginHelper::getPlugin('search', $this->component);
                $this->params = new JParameter($plugin->params);
            }
            
            return $this->params;
        }
    }
    

    copy | embed

    0 comments - tagged in  posted by torkil on Jul 20, 2010 at 5:00 a.m. EDT
  • searchable class
    <?php
    
    Koowa::import('admin::com.author.models.search');
    
    class AuthorModelSearchable extends SearchModel
    {
        public function __construct()
        {
            // Object is constructed by Joomla, not Koowa, so we have to set some options manually
            $options = array(
                'base_path' => null,
                'name'      => array(
                    'prefix'    => 'author',
                    'base'      => 'model',
                    'suffix'    => 'searchable'
                ),
                'state'         => array()
            );
    
            // The searchable areas
            $options['areas'] = array (
                'pages'             => 'Innholdsartikler',
                'works'             => 'Bøker',
                'articles'          => 'Nyheter',
                'events'            => 'Aktivitetskalender',
                'topics'            => 'Nøkkelord',
                'externalarticles'  => 'Eksterne artikler'
            );
    
            parent::__construct($options);
        }
    }
    

    copy | embed

    0 comments - tagged in  posted by torkil on Jul 20, 2010 at 4:59 a.m. EDT
  • ComNinjaboardModelAttachments
    <?php
    /**
     * @version		$Id: attachments.php 443 2010-04-28 01:19:48Z stian $
     * @category	Ninjaboard
     * @copyright	Copyright (C) 2007 - 2010 NinjaForge. All rights reserved.
     * @license		GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
     * @link     	http://ninjaforge.com
     */
    
    /**
     * Ninjaboard Attachments model
     *
     * Fetches posts' attachments
     * 
     * @author Stian Didriksen <stian@ninjaforge.com>
     */
    class ComNinjaboardModelAttachments extends KModelTable
    {
    	
    	/**
    	 * Only attachments that are images
    	 *
    	 * @var array
    	 */
    	protected $_images = array();
    	
    	/**
    	 * Only attachments that are isn't images
    	 *
    	 * @var array
    	 */
    	protected $_files = array();
    
    	/**
    	 * Constructor
         *
         * @param	array An optional associative array of configuration settings.
    	 */
    	public function __construct(KConfig $options)
    	{
    		parent::__construct($options);
    
    		$this->_state
    						->insert('file', 'cmd')
    						->insert('post', 'int')
    						->insert('id'  , 'int');
    	}
    	
    	protected function _buildQueryWhere(KDatabaseQuery $query)
    	{
    		parent::_buildQueryWhere($query);
    
    		if($file = $this->_state->file) $query->where('tbl.file'	, '=', $file, 'and');
    		if($post = $this->_state->post) $query->where('tbl.post_id'	, '=', $post, 'and');
    	}
    	
    	public function getList()
    	{
    		if(!isset($this->_list))
    		{
    			require_once JPATH_ROOT.'/components/com_media/helpers/media.php';
    
    			foreach(parent::getList() as $item)
    			{
    				$item->type = MediaHelper::getTypeIcon($item->file);
    				if(MediaHelper::isImage($item->file))
    				{
    					$this->_images[] = $item;
    				}
    				else
    				{
    					$this->_files[] = $item;
    				}
    			}
    		}
    
    		return $this->_list;
    	}
    	
    	/**
    	 * Get only attachments that are images
    	 */
    	public function getImages()
    	{
    		if(!isset($this->_list)) $this->getList();
    
    		return $this->_images;
    	}
    	
    	/**
    	 * Get only attachments that isn't images
    	 */
    	public function getFiles()
    	{
    		if(!isset($this->_list)) $this->getList();
    
    		return $this->_files;
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by stipsan on Jun 08, 2010 at 9:59 a.m. EDT
  • Koowa sef patch
    --- /plugins/system/koowa.php	Fri Apr 30 02:50:24 2010
    +++ /plugins/system/koowa.php	Mon May 17 15:17:15 2010
    @@ -93,6 +93,43 @@
     	}
     	
     	/**
    +	 * Sets the GET request after route
    +	 *
    +	 * This is crucial for SEF mode compatibility.
    +	 * Unfortunately, when the routing is done, the parsed URI request is set in the $_REQUEST global,
    +	 * only some of the variables are set in the $_GET global. Important ones like the 'view' variable is not set in $_GET.
    +	 * 
    +	 * So in order to fix it, we do the following:
    +	 * 	1. get and clone the current JURI instance.
    +	 *	2. Fetch the router from the application instance.
    +	 *	3. Call the routers parse method on the JURI instance.
    +	 *	4. Set the result in the $_GET global, without overwriting the existing variables
    +	 *
    +	 * @see JApplication::route()
    +	 * @see JRequest::setVar()
    +	 * @see KDispatcherDefault::_actionDispatch() 
    +	 *
    +	 * @author Stian Didriksen <stian@nooku.org>
    +	 * @return void
    +	 */
    +	public function onAfterRoute()
    +	{
    +		$uri = clone(JURI::getInstance());
    +
    +		/**
    +		 * @TODO figure out how to use KRequest::url
    +		 * Currently a BadMethodCallException 'Call to undefined method :getPath' from /includes/router.php(50)
    +		 * is thrown if we try using it.
    +		 */
    +		//$uri = KRequest::url();
    +
    +		$router = KFactory::get('lib.koowa.application')->getRouter();
    +		$result = $router->parse($uri);
    +
    +		KRequest::set('get', KHelperArray::merge($result, KRequest::get('get', 'raw')));
    +	}
    +
    +	/**
     	 * Prettify the output using Tidy filter (if available) and debug has been
     	 * enabled
     	 *
    

    copy | embed

    0 comments - tagged in  posted by stipsan on May 17, 2010 at 9:20 a.m. EDT
  • Joomla! symlinker shell script #2
    #!/bin/bash
    
    # Copyright 2010 Gergo Erdosi. All rights reserved.
    # Licensed under the GNU General Public License v2.0.
    
    # Set source and target directories.
    SOURCE_DIR=${1%/}
    TARGET_DIR=${2%/}
    
    if [[ -z "$SOURCE_DIR" || -z "$TARGET_DIR" ]]
    then
      echo "Usage: sh ${0##*/} source_dir target_dir"
      exit
    fi
    
    # Function to symlink directories and files.
    function symlink() {
      # Set main directory variables.
      MAIN_DIR=$1
      MAIN_DIR_ALIAS=$2
    
      if [ -z "$MAIN_DIR_ALIAS" ]
      then
        MAIN_DIR_ALIAS="$MAIN_DIR"
      fi
    
      # If the source directory exists, symlink it.
      if [ -d "${SOURCE_DIR}/${MAIN_DIR}" ] && [ ! -L "${SOURCE_DIR}/${MAIN_DIR}" ]
      then
        # Iterate through the subdirectories.
        for SUB_DIR in $( ls "${SOURCE_DIR}/${MAIN_DIR}" )
        do
          # Create the target directory if not exists.
          if [ ! -d "${TARGET_DIR}/${MAIN_DIR_ALIAS}" ]; then
            mkdir "${TARGET_DIR}/${MAIN_DIR_ALIAS}"
          fi
    
          # Remove the target subdirectory if exists.
          if [ -d "${TARGET_DIR}/${MAIN_DIR_ALIAS}/${SUB_DIR}" ]; then
            rm -rf "${TARGET_DIR}/${MAIN_DIR_ALIAS}/${SUB_DIR}"
          fi
    
          # Create the symbolic link.
          ln -sf "${SOURCE_DIR}/${MAIN_DIR}/${SUB_DIR}" "${TARGET_DIR}/${MAIN_DIR_ALIAS}/${SUB_DIR}"
    
          # Display the linking information.
          echo "${SOURCE_DIR}/${MAIN_DIR}/${SUB_DIR}"
          echo "   --> ${TARGET_DIR}/${MAIN_DIR_ALIAS}/${SUB_DIR}"
          echo ""
        done
      fi
    }
    
    # Create symbolic link for these directories.
    symlink "administrator/components"
    symlink "administrator/language/en-GB"
    symlink "administrator/modules"
    symlink "components"
    symlink "language/en-GB"
    symlink "libraries"
    symlink "media"
    symlink "modules"
    symlink "plugins/authentication"
    symlink "plugins/content"
    symlink "plugins/editors"
    symlink "plugins/editors-xtd"
    symlink "plugins/koowa"
    symlink "plugins/search"
    symlink "plugins/system"
    symlink "plugins/user"
    symlink "plugins/xmlrpc"
    symlink "site/components" "components"
    symlink "site/language/en-GB" "language/en-GB"
    symlink "site/modules" "modules"
    

    copy | embed

    2 comments - tagged in  posted by gergoerdosi on Apr 07, 2010 at 5:54 a.m. EDT
  • Joomla! symlinker shell script
    #!/bin/bash
    
    # Copyright 2010 Gergo Erdosi. All rights reserved.
    # Licensed under the GNU General Public License v2.0.
    
    SOURCE_DIR=${1%/}
    TARGET_DIR=${2%/}
    
    if [[ ! $SOURCE_DIR || ! $TARGET_DIR ]]; then
      echo "Usage: sh ${0##*/} source_dir target_dir"
      exit
    fi
    
    DIRECTORIES=(
      "administrator/components"
      "administrator/language/en-GB"
      "administrator/modules"
      "components"
      "language/en-GB"
      "media"
      "modules"
      "plugins/authentication"
      "plugins/content"
      "plugins/editors"
      "plugins/editors-xtd"
      "plugins/koowa"
      "plugins/search"
      "plugins/system"
      "plugins/user"
      "plugins/xmlrpc"
    )
    
    for MAIN_DIR in ${DIRECTORIES[@]}
    do
      if [[ -d "${SOURCE_DIR}/${MAIN_DIR}" && ! -L "${SOURCE_DIR}/${MAIN_DIR}" ]]; then
        for SUB_DIR in $( ls "${SOURCE_DIR}/${MAIN_DIR}" );
        do
          if [ ! -d "${TARGET_DIR}/${MAIN_DIR}" ]; then
            mkdir "${TARGET_DIR}/${MAIN_DIR}"
          fi
          
          if [ -d "${TARGET_DIR}/${MAIN_DIR}/${SUB_DIR}" ]; then
            rm -rf "${TARGET_DIR}/${MAIN_DIR}/${SUB_DIR}"
          fi
          
          ln -sf "${SOURCE_DIR}/${MAIN_DIR}/${SUB_DIR}" "${TARGET_DIR}/${MAIN_DIR}/${SUB_DIR}"
          
          echo "${SOURCE_DIR}/${MAIN_DIR}/${SUB_DIR}"
          echo "  --> ${TARGET_DIR}/${MAIN_DIR}/${SUB_DIR}"
          echo ""
        done
      fi
    done
    

    copy | embed

    0 comments - tagged in  posted by gergoerdosi on Mar 22, 2010 at 12:41 p.m. EDT
  • Replace Mootools in Joomla! with a compressed copy from Google AJAX Libraries API
    <!-- The following code goes into your template's index.php <head> tags, right before the <jdoc:include type="head" /> code block -->
    <?php
    // Replace Mootools in Joomla! with a compressed copy from Google AJAX Libraries API
    $document =& JFactory::getDocument();
    unset($document->_scripts[$this->baseurl . '/media/system/js/mootools.js']);
    ?>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">google.load("mootools", "1.1.2");</script>
    

    copy | embed

    0 comments - tagged in  posted by fevangelou on Feb 28, 2010 at 8:42 p.m. EST
  • Prevent ?tp=1 module position exposure on Joomla! sites using PHP only
    <?php
    // Properly prevent ?tp=1 module position exposure on Joomla! sites using PHP only
    $currentURL = explode('?',substr(JURI::base(),0,-1).$_SERVER['REQUEST_URI']);
    if($_GET['tp']) header('Location: '.$currentURL[0]);
    
    // Same thing using the Joomla! API
    JRequest::setVar('tp',0);
    ?>
    

    copy | embed

    0 comments - tagged in  posted by fevangelou on Feb 28, 2010 at 7:46 p.m. EST
  • How to handle sessions into Joomla Framework
    <?php
    // Set session var
    $session =& JFactory::getSession();
    $value = "paris";
    $session->set('siteshop', $value);
    
    // Get session var
    $session =& JFactory::getSession();
    $mainframe->addCustomHeadTag('<META name="'.$session->get('siteshop').'" content="test"/>');
    ?>
    

    copy | embed

    0 comments - tagged in  posted by bmrateb on Feb 23, 2010 at 5:27 a.m. EST
  • AJAX in Joomla 1.5
    <?php
    	/*
    	/com_mycomponent
    	|-/views
    	|  |-/response
    	|     |-/tmpl
    	|     |  |-default.php
    	|     |  |-index.html
    	|     |-view.raw.php
    	*/
    ?>
    
    <?php
    	//default.php
    	defined('_JEXEC') or die('Restricted access');
    	echo $this->response;
    ?>
    
    <?php
    	//view.raw.php
    	defined('_JEXEC') or die('Restricted access');
    
    	jimport( 'joomla.application.component.view');
    
    	class MycomponentViewResponse extends JView{
    		public function plain($tpl=null){
    			$this->setLayout('default');
    			parent::display($tpl);
    		}
    		public function json($tpl=null){
    			$this->response = json_encode($this->response);
    			$this->setLayout('default');
    			parent::display($tpl);
    		}
    	}
    ?>
    
    
    <?php
    	//somewhere in a controller
    	public function check(){
    		$view = &$this->getView('response','raw');
    		$view->response = 'OK';
    		$view->plain();
    	}
    ?>
    
    In your ajax call use the following base URL:
    
    index.php?option=com_mycomponent&format=raw&
    
    Then append the right controller & task parameters to the url, like:
    
    index.php?option=com_mycomponent&format=raw&controller=mycontroller&task=check
    

    copy | embed

    0 comments - tagged in  posted by dukeofgaming on Jan 18, 2010 at 5:07 p.m. EST
  • Fade Joomla! Message
    <script type="text/javascript" >
     var tmjmosmsg,fx;
     function pload(){
     tmjmosmsg=$$('div.message');
     if($type(tmjmosmsg[0])=='element'){
     var el=tmjmosmsg[0];
     el.setStyle('overflow','hidden');
     var h=el.getSize().size.y;
     fx = new Fx.Styles(el, {duration:900, wait:false});
     //scrol to message
     winScroller = new Fx.Scroll(window);
     winScroller.toElement($('header'));//name of header div
     //delayed start, then remove the html element upon completion
     
    (function(){
     
    fx.start({
     
    'margin-top':-1*h.toInt(),
     
    opacity:0
     
     
    }).chain(function(){el.remove();});
    }).delay(2500);
     
     }
     
     };
     
     window.addEvent('load',function(){
     pload();
     }
     
     );
     </script>
    

    copy | embed

    0 comments - tagged in  posted by jameshafner on Dec 03, 2009 at 11:13 a.m. EST
  • JAccess
    <?php
    /**
     * @version		$Id: access.php 13317 2009-10-24 07:41:26Z eddieajau $
     * @package		Joomla.Framework
     * @subpackage	Access
     * @copyright	Copyright (C) 2005 - 2009 Open Source Matters, Inc. All rights reserved.
     * @license		GNU General Public License version 2 or later; see LICENSE.txt
     */
    
    defined('JPATH_BASE') or die;
    
    jimport('joomla.access.rules');
    jimport('joomla.database.query');
    
    /**
     * Class that handles all access authorization routines.
     *
     * @package 	Joomla.Framework
     * @subpackage	User
     * @since		1.6
     */
    class JAccess
    {
    	protected static $isRoot = null;
    	protected static $viewLevels = array();
    	protected static $assetRules = array();
    
    	/**
    	 * Method to check if a user is authorised to perform an action, optionally on an asset.
    	 *
    	 * @param	integer	Id of the user for which to check authorisation.
    	 * @param	string	The name of the action to authorise.
    	 * @param	mixed	Integer asset id or the name of the asset as a string.  Defaults to the global asset node.
    	 * @return	boolean	True if authorised.
    	 * @since	1.6
    	 */
    	public static function check($userId, $action, $asset = null)
    	{
    		if (self::$isRoot) {
    			return true;
    		}
    		else
    		{
    			// Sanitize inputs.
    			$userId = (int) $userId;
    
    			$action = strtolower(preg_replace('#[\s\-]+#', '.', trim($action)));
    			$asset  = strtolower(preg_replace('#[\s\-]+#', '.', trim($asset)));
    
    			// Default to the root asset node.
    			if (empty($asset)) {
    				$asset = 1;
    			}
    
    			// Get the rules for the asset recursively to root if not already retrieved.
    			if (empty(self::$assetRules[$asset])) {
    				self::$assetRules[$asset] = self::getAssetRules($asset, true);
    			}
    
    			// Get all groups against which the user is mapped.
    			$identities = self::getGroupsByUser($userId);
    			array_unshift($identities, $userId * -1);
    
    			// Make sure we only check for core.admin once during the run.
    			if (self::$isRoot === null)
    			{
    				if (self::getAssetRules(1)->allow('core.admin', $identities)) {
    					self::$isRoot = true;
    					return true;
    				}
    				else {
    					self::$isRoot = false;
    				}
    			}
    
    			return self::$assetRules[$asset]->allow($action, $identities);
    		}
    	}
    
    	/**
    	 * Method to return the JRules object for an asset.  The returned object can optionally hold
    	 * only the rules explicitly set for the asset or the summation of all inherited rules from
    	 * parent assets and explicit rules.
    	 *
    	 * @param	mixed	Integer asset id or the name of the asset as a string.
    	 * @param	boolean	True to return the rules object with inherited rules.
    	 * @return	object	JRules object for the asset.
    	 * @since	1.6
    	 */
    	public static function getAssetRules($asset, $recursive = false)
    	{
    		// Get the database connection object.
    		$db = JFactory::getDbo();
    
    		// Build the database query to get the rules for the asset.
    		$query	= new JQuery;
    		$query->select($recursive ? 'b.rules' : 'a.rules');
    		$query->from('#__assets AS a');
    
    		// If the asset identifier is numeric assume it is a primary key, else lookup by name.
    		if (is_numeric($asset)) {
    			$query->where('a.id = '.(int) $asset);
    		}
    		else {
    			$query->where('a.name = '.$db->quote($asset));
    		}
    
    		// If we want the rules cascading up to the global asset node we need a self-join.
    		if ($recursive)
    		{
    			$query->leftJoin('#__assets AS b ON b.lft <= a.lft AND b.rgt >= a.rgt');
    			$query->order('b.lft');
    		}
    
    		// Execute the query and load the rules from the result.
    		$db->setQuery($query);
    		$result	= $db->loadResultArray();
    
    		// Instantiate and return the JRules object for the asset rules.
    		$rules	= new JRules;
    		$rules->mergeCollection($result);
    
    		return $rules;
    	}
    
    	/**
    	 * Method to return a list of user groups mapped to a user.  The returned list can optionally hold
    	 * only the groups explicitly mapped to the user or all groups both explicitly mapped and inherited
    	 * by the user.
    	 *
    	 * @param	integer	Id of the user for which to get the list of groups.
    	 * @param	boolean	True to include inherited user groups.
    	 * @return	array	List of user group ids to which the user is mapped.
    	 * @since	1.6
    	 */
    	public static function getGroupsByUser($userId, $recursive = true)
    	{
    		// Get the database connection object.
    		$db = JFactory::getDbo();
    
    		// Build the database query to get the rules for the asset.
    		$query	= new JQuery;
    		$query->select($recursive ? 'b.id' : 'a.id');
    		$query->from('#__user_usergroup_map AS map');
    		$query->where('map.user_id = '.(int) $userId);
    		$query->leftJoin('#__usergroups AS a ON a.id = map.group_id');
    
    		// If we want the rules cascading up to the global asset node we need a self-join.
    		if ($recursive) {
    			$query->leftJoin('#__usergroups AS b ON b.lft <= a.lft AND b.rgt >= a.rgt');
    		}
    
    		// Execute the query and load the rules from the result.
    		$db->setQuery($query);
    		$result	= $db->loadResultArray();
    
    		// Clean up any NULL or duplicate values, just in case
    		JArrayHelper::toInteger($result);
    		if (empty($result)) {
    			$result = array('1');
    		}
    		else {
    			$result = array_unique($result);
    		}
    
    		return $result;
    	}
    
    	/**
    	 * Method to return a list of view levels for which the user is authorised.
    	 *
    	 * @param	integer	Id of the user for which to get the list of authorised view levels.
    	 * @return	array	List of view levels for which the user is authorised.
    	 * @since	1.6
    	 */
    	public static function getAuthorisedViewLevels($userId)
    	{
    		// Get all groups that the user is mapped to recursively.
    		$groups = self::getGroupsByUser($userId);
    
    		// Only load the view levels once.
    		if (empty(self::$viewLevels))
    		{
    			// Get a database object.
    			$db	= JFactory::getDBO();
    
    			// Build the base query.
    			$query	= new JQuery;
    			$query->select('id, rules');
    			$query->from('`#__viewlevels`');
    
    			// Set the query for execution.
    			$db->setQuery((string) $query);
    
    			// Build the view levels array.
    			foreach ($db->loadAssocList() as $level)
    			{
    				self::$viewLevels[$level['id']] = (array) json_decode($level['rules']);
    			}
    		}
    
    		// Initialize the authorised array.
    		$authorised = array(1);
    		$config = new JConfig;
    
    		// Find the authorized levels.
    		foreach (self::$viewLevels as $level => $rule)
    		{
    			foreach ($rule as $id)
    			{
    				if (($id < 0) && (($id * -1) == $userId))
    				{
    					$authorised[] = $level;
    					break;
    				}
    				// Check to see if the group is mapped to the level.
    				elseif (($id >= 0) && in_array($id, $groups))
    				{
    					$authorised[] = $level;
    					break;
    				}
    			}
    		}
    
    		return $authorised;
    	}
    
    	/**
    	 * Method to return a list of actions for which permissions can be set given a component and section.
    	 *
    	 * @param	string	The component from which to retrieve the actions.
    	 * @param	string	The name of the section within the component from which to retrieve the actions.
    	 * @return	array	List of actions available for the given component and section.
    	 * @since	1.6
    	 */
    	public static function getActions($component, $section = 'component')
    	{
    		$actions = array();
    
    		if (is_file(JPATH_ADMINISTRATOR.'/components/'.$component.'/access.xml'))
    		{
    			$xml = simplexml_load_file(JPATH_ADMINISTRATOR.'/components/'.$component.'/access.xml');
    
    			foreach ($xml->children() as $child)
    			{
    				if ($section == (string) $child['name'])
    				{
    					foreach ($child->children() as $action)
    					{
    						$actions[] = (object) array('name' => (string) $action['name'], 'title' => (string) $action['title'], 'description' => (string) $action['description']);
    					}
    
    					break;
    				}
    			}
    		}
    
    		return $actions;
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by stipsan on Oct 26, 2009 at 9:44 a.m. EDT
  • Joomla 1.5 Parameters
    <param name="myradiovalue" type="radio" default="0" label="Select an option" description="">
      <option value="0">1</option>
      <option value="1">2</option>
    </param>
    
    <param name="myfile" type="filelist" default="" label="Select a file" description="" directory="administrator" filter="" exclude="" stripext="" />
    
    <param name="calendar" type="calendar" default="5-10-2008" label="Select a date" description="" format="%d-%m-%Y" />
    
    <param name="category" type="category" label="Select a category" description="" section="3" />
    
    <param name="editor" type="editors" default="none" label="Select an editor" />
    
    <param name="folder" type="folderlist" default="" label="Select a folder" directory="administrator" filter="" exclude="" stripext="" />
    
    <param name="helpsite" type="helpsites" default="" label="Select a help site" description="" />
    
    <param name="secretvariable" type="hidden" default="" />
    
    <param name="image" type="imagelist" default="" label="Select an image" description="" directory="" exclude="" stripext="" />
    
    <param name="language" type="languages" client="site" default="en-GB" label="Select a language" description="" />
    
    <param name="listvalue" type="list" default="" label="Select an option" description="">
      <option value="0">Option 1</option>
      <option value="1">Option 2</option>
    </param>
    
    <param name="menu" type="menu" default="mainmenu" label="Select a menu" description="Select a menu" />
    
    <param name="menuitem" type="menuitem" default="45" label="Select a menu item" description="Select a menu item" />
    
    <param name="password" type="password" default="secret" label="Enter a password" description="" size="5" />
    
    <param name="section" type="section" default="" label="Select a section" description="" />
    
    <param type="spacer" default="Advanced parameters" />
    
    <param name="field" type="sql" default="10" label="Select an article" query="SELECT id, title FROM #__table" key_field=”id” value_field=”title” />
    
    <param name="textvalue" type="text" default="Some text" label="Enter some text" description="" size="10" />
    
    <param name="textarea" type="textarea" default="default" label="Enter some text" description="" rows="10" cols="5" />
    
    <param name="timezone" type="timezones" default="-10" label="Select a timezone" description="" />
    
    <param name="usergroups" type="usergroup" default="" label="Select a user group" description="" />
    

    copy | embed

    0 comments - tagged in  posted by jameshafner on Oct 23, 2009 at 2:40 p.m. EDT
  • modal popup autoresize in joomla
    {handler:'iframe',size:{x:window.getSize().scrollSize.x-80, y: window.getSize().size.y-80}, onShow:$('sbox-window').setStyles({'padding': 0})}
    

    copy | embed

    0 comments - tagged in  posted by stipsan on Oct 09, 2009 at 12:30 p.m. EDT
  • INI formatted parameters
    enable_filter=1
    latest_post_hours=8,12
    latest_post_days=1,2,3
    latest_post_weeks=1
    latest_post_months=1,6
    latest_post_years=1
    

    copy | embed

    0 comments - tagged in  posted by stipsan on Oct 08, 2009 at 7:54 p.m. EDT
  • Joomla module params groups
    <params>
    <!--"Module Parameters"-->
    </params>
    <params group="advanced">
    <!--"Advanced Parameters"-->
    </params>
    <params group="other">
    <!--"Other Parameters"-->
    </params>
    <params group="legacy">
    <!--"Legacy Parameters"-->
    </params>
    

    copy | embed

    0 comments - tagged in  posted by stipsan on Sep 09, 2009 at 7:00 p.m. EDT
  • Logout URL w/ Return to Index.php
    <a href="index.php?option=com_user&task=logout&return=aW5kZXgucGhw" title="Sign Out">Sign Out</a>
    

    copy | embed

    0 comments - tagged in  posted by jameshafner on Sep 09, 2009 at 5:49 p.m. EDT
  • Unsetting Mootools in J! Head
    $headerjs = $this -> getHeadData ( ) ; headerjs $ = $ this -> getHeadData ();
    reset ( $headerjs [ 'scripts' ] ) ; reset ($ headerjs [ 'scripts']);
    foreach ( $headerjs [ 'scripts' ] as $script => $type ) { foreach ($ headerjs [ 'scripts'] as $ script => $ type) (
     if ( ( strpos ( $script , 'mootools.js' ) ) or ( strpos ( $script , 'caption.js' ) ) ) { if ((strpos ($ script, 'mootools.js')) or (strpos ($ script, 'caption.js'))) (
     unset ( $headerjs [ 'scripts' ] [ $script ] ) ; unset ($ headerjs [ 'scripts'] [$ script]);
      } )
     } )
    $this -> setHeadData ( $headerjs ) ; $ this -> setHeadData ($ headerjs); 
    

    copy | embed

    0 comments - tagged in  posted by jameshafner on Aug 24, 2009 at 11:10 a.m. EDT
  • Joomla, Plesk Permissions
    #!/bin/bash
    # This script makes it easier to get domain directory permissions to work well with Joomla
    
    # First check that this is a valid username
    grep "^${1}:" /etc/passwd > /dev/null 2>&1
    if [ "$?" -ne "0" ]; then
    echo "Sorry, cannot find user ${1} in /etc/passwd or you didn't supply a username"
    echo "Usage: ${0} "
    
    exit 1
    fi
    
    userdir=`grep "^${1}:" /etc/passwd | cut -d: -f6`
    
    if [ -d ${userdir} ] ; then
    echo "Changing to directory ${userdir}"
    cd ${userdir} && chown -R ${1}:psacln httpdocs && chmod -R g+w httpdocs && find httpdocs -type d -exec chmod g+s {} \; && /etc/init.d/httpd reload
    fi
    

    copy | embed

    0 comments - tagged in  posted by bhubbard on Mar 17, 2009 at 10:07 a.m. EDT
  • Resets all article hits to 0.
    update jos_content set hits=0
    

    copy | embed

    0 comments - tagged in  posted by ploughansen on Feb 15, 2009 at 1:11 p.m. EST
Sign up to create your own snipts, or login.