<?php
// $HeadURL: http://joomlacode.org/svn/joomgallery/JG-1.5/Plugins/JoomContentPlu/trunk/joomplu.php $
// $Id: joomplu.php 380 2009-02-17 13:07:20Z locutus $
/******************************************************************************\
**   JoomGallery Content Plugin 'JoomPlu' 1.5 BETA2                           **
**   By: JoomGallery::ProjectTeam                                             **
**   Copyright (C) 2009  Patrick Alt                                          **
**   Released under GNU GPL Public License                                    **
**   License: http://www.gnu.org/copyleft/gpl.html                            **
\******************************************************************************/
/** ### Original Copyright: ###
 * @copyright  Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license  GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 */

// Check to ensure this file is included in Joomla!
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

/**
 * JoomGallery Plugin
 *
 * Shows images from JoomGallery in content articles
 *
 * @package     Joomla
 * @subpackage  Content
 * @since       1.5
 */
class plgContentJoomPlu extends JPlugin
{

  /**
   * Constructor
   *
   * For php4 compatability we must not use the __constructor as a constructor for plugins
   * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
   * This causes problems with cross-referencing necessary for the observer design pattern.
   *
   * @param object $subject The object to observe
   * @param object $params  The object that holds the plugin parameters
   * @since 1.5
   */
  function plgContentJoomPlu( &$subject, $params )
  {
    parent::__construct( $subject, $params );

    // load the language file
    $this->loadLanguage('', JPATH_ADMINISTRATOR);
  }

  /**
   * JoomPlu prepare content method
   *
   * Method is called by the view
   *
   * @param 	object		The article object.  Note $article->text is also available
   * @param 	object		The article params
   * @param 	int			  The 'page' number
   */
  function onPrepareContent( &$article, &$params, $limitstart )
  {
    // simple performance check to determine whether bot should process further
    if ( strpos( $article->text, '{joomplu' ) === false ) {
      return true;
    }

    // regular expression
    $regex = '/\{joomplu:([0-9]+)([a-z, ]*)\}/';

    // don't go further, if we haven't any matches
    if(!preg_match_all($regex, $article->text, $matches, PREG_SET_ORDER))
      return true;

    #echo '<pre>';print_r($matches);echo '</pre>'; // for debug

    // check existence of JoomGallery and include the interface class
    if(!file_exists(JPATH_ROOT.DS.'components'.DS.'com_joomgallery'.DS.'classes'.DS.'interface.class.php')) {
      $output         = '<p><b>'.JText::_('JCP_JG_NOT_INSTALLED').'</b></p>';
      $article->text  = preg_replace($regex, $output, $article->text);
      return true;
    }
    require_once(JPATH_ROOT.DS.'components'.DS.'com_joomgallery'.DS.'classes'.DS.'interface.class.php');

    // get user object
    $user = &JFactory::getUser();

    // create interface object
    $jinterface = new joominterface;

    // include necessary style sheets
    $jinterface->getPageHeader();

    // main task
    foreach($matches as $match) {

      // get image object
      $pic_obj = $jinterface->getPicture($match[1], $user->get('aid'));
      if(!is_null($pic_obj)) {  // image found

        // linked
        if(strpos($match[2], 'not linked') === false) {
          $linked = true;
        } else {
          $linked = false;
        }

        // align
        if(strpos($match[2], 'right') === false) {
          if(strpos($match[2], 'left') === false) {
            $extra = null;
          } else {
            $extra = 'jg_floatleft';#$extra = 'align="left"';
          }
        } else {
          $extra = 'jg_floatright';#$extra = 'align="right"';
        }

        // detail image or thumbnail
        if(strpos($match[2], 'detail') === false) {
          $output = $jinterface->displayThumb($pic_obj, $linked, $extra);
        } else {
          $output = $jinterface->displayDetail($pic_obj, $linked, $extra);
        }

      } else {  // image not found

        $output = ''; //'<p><b>'.JText::_('JCP_IMAGE_NOT_DISPLAYABLE').'</b></p>';
        // send system message if configured
        if($this->params->get('msg', 0)) {
          $this->sendMessages($match[1], $article->id, $article->title);
        }
      }

      $regex = '/\{joomplu:'.$match[1].'[^}]*\}/';
      $article->text = preg_replace($regex, $output, $article->text, 1);
    }
  }

  /**
   * JoomPlu message sending method
   *
   * Method sends system messages to configured users
   * is called when an invalid image id was found in the article
   *
   * @param   int     The image id
   * @param   int     The article id
   * @param   string  The article title
   */
  function sendMessages($pic_id, $article_id, $article_title)
  {
    $db = &JFactory::getDBO();

    // include messages class
    require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_messages'.DS.'tables'.DS.'message.php');

    // create messages object
    $msg = new TableMessage($db);

    // find users who want to receive messages
    if(!$this->params->get('msg_to', 0)) {

      $query = 'SELECT id' .
              ' FROM #__users' .
              ' WHERE sendEmail = 1';
      $db->setQuery($query);
      $user_ids = $db->loadResultArray();
    } else {
      $user_ids = explode(',',$this->params->get('msg_to', 0));
    }

    foreach ($user_ids as $user_id) {

      $user_to = &JFactory::getUser($user_id);

      // ensure that a valid user was selected
      if(is_object($user_to) AND $user_to->get('gid') > 22) {

        $message = sprintf(JText::_('JCP_MESSAGE_TEXT'), $pic_id, $article_id, $article_title);

        // check whether message was already sent
        $query = 'SELECT message FROM #__messages
                  WHERE user_id_to = '.$user_id;
        $db->setQuery($query);
        $messages = $db->loadResultArray();
        $sent = false;
        foreach($messages as $sent_message) {
          if($sent_message == $message) {
            $sent = true;
            break;  // breaks foreach because we have what we wanted
          }
        }
        if($sent) {
          continue; // next loop
        }

        // send message
        $msg->send($user_id, $user_id, JText::_('JCP_MESSAGE_SUBJECT'), $message);
      }
    }
  }
}