<?php
/**
 * @version		1.0.0
 * @package		SWFModule
 * @copyright	Copyright (C) 2009 webconstruction.ch. All rights reserved.
 * @license		GNU/GPL, see LICENSE.txt
 * @contact		info@webconstruction.ch
 * @website		www.webconstruction.ch
 **/

// no direct access
defined('_JEXEC') or die ('Restricted access');

class modSWFModuleHelper
{
    function _getParams($paramString, $getSpecial = false)
    {
        $params = $this->_getDefinitions($paramString);
        foreach ($params as $key=>$value)
        {
            if ($getSpecial == false && ($key == 'name' || $key == 'width' || $key == 'height' || $key == 'cabversion' || $key == 'align' || $key == 'id' || $key == 'class' || $key == 'objectid' || $key == 'dfv' || $key == 'uei'))
            {
                unset ($params[$key]);
            }
        }
        if (!$getSpecial)
        {
            $ret = array ();
            $ret[0] = $this->_createHTML($params, '<param name="{key}" value="{value}" />'."\n");
            $ret[1] = $this->_createHTML($params, ' {key}="{value}" ');
        } else
        {
            $ret = $params;
        }
        return $ret;
    }

    function renderSWF($content, $pluginParams, $moduleid)
    {
        //Get params

        $enabled = intval($pluginParams->get('enabled', 1));

        //added to version 2.2
        $flashAltHTML = $pluginParams->get('flashAltHTML', '<a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>');
        $useSwfobject = intval($pluginParams->get('useSwfobject', 1));
        $defdfv = $pluginParams->get('dfv', '10.0.0');
        $defuei = intval($pluginParams->get('uei', 1));
        if ($defuei == 1)
        {
            $defuei = "true";
        } else
        {
            $defuei = "false";
        }
        $defobjectid = $pluginParams->get('objectid', 'flashobject{modid}');

        //--------------

        $defCabversion = $pluginParams->get('cabversion', '10,0,32,18');
        $defParams = $pluginParams->get('defaultParams', 'wmode=transparent');
        $tmp = $this->_getParams($defParams);
        $defaultParamsTags = $tmp[0];
        $defaultParamAttributes = $tmp[1];
        $defName = $pluginParams->get('name', 'swfname{modid}');
        $defAlign = $pluginParams->get('align', 'middle');
        $defWidth = $pluginParams->get('width', '100%');
        $defHeight = $pluginParams->get('height', '150px');
        $defClass = $pluginParams->get('class', '');
        $defId = $pluginParams->get('id', '');

        if (!(strpos('@'.$content, "{swf") > 0))
        {
            return; //Return if no swf placeholders
        }

        $swfPlaceHolders = $this->_getPlaceHolders($content, '{swf', '}');

        if ($enabled == 0)
        {
            for ($i = 0; $i < count($swfPlaceHolders); $i++)
            {
                $content = str_replace($swfPlaceHolders[$i], '', $content);
            }
            $article->text = $content;
            return;
        }
        $objectidcounter = 0;

	    $document = & JFactory::getDocument();

        for ($i = 0; $i < count($swfPlaceHolders); $i++)
        {
            $legacy = false;
            if (!(strpos($swfPlaceHolders[$i], '[') > 0) && preg_match('={swf;(.*);(.*);(.*)}=i', $swfPlaceHolders[$i], $legacyTmp))
            {
                $legacy = true;
            } elseif (preg_match('={swf:(.*):(.*):(.*)}=i', $swfPlaceHolders[$i], $legacyTmp))
            {
                $legacy = true;
            }

            if ($legacy)
            {
                $width = $legacyTmp[2];
                $height = $legacyTmp[3];
                $align = $defAlign;
                $name = $defName;
                $class = $defClass;
                $id = $defId;
                $paramTags = $defaultParamsTags;
                $paramAttributes = $defaultParamAttributes;
                $cabversion = $defCabversion;
                $src = $legacyTmp[1];

                //added in version 2.2
                $dfv = $defdfv;
                $objectid = $defobjectid;
                $uei = $defuei;
            }
            if ($legacy == false)
            {
                //added in version 2.2
                $dfv = $defdfv;
                $objectid = $defobjectid;
                $uei = $defuei;

                $paramTags = '';
                $paramAttributes = '';
                $align = $defAlign;
                $width = $defWidth;
                $height = $defHeight;
                $name = $defName;
                $class = $defClass;
                $id = $defId;
                $cabversion = $defCabversion;
                $srce = $this->_getPlaceHolders($swfPlaceHolders[$i], '{swf;', ';[', true);
                if (! isset ($srce[0]))
                {
                    $srce = $this->_getPlaceHolders($swfPlaceHolders[$i], '{swf;', '}', true);
                }
                $src = $srce[0];
                $src = str_replace(';', '', $src);
                $src = trim($src, "\xc2\xa0");
                $src = trim($src);
		        $src = trim($src, "\xc2\xa0");
                $paramTags = $defaultParamsTags;
                $paramAttributes = $defaultParamAttributes;
            }
			$name = str_replace('{modid}', $moduleid, $name);
			$objectid = str_replace('{modid}', $moduleid, $objectid);
            $divStart = '';
            $divEnd = '';
            $htmlclass = '';
            $htmlid = '';
            if (trim($class) != '')
            {
                $htmlclass = 'class="'.$class.'" ';
            }
            if (trim($id) != '')
            {
                $htmlid = ' id="'.$id.'" ';
            }
            if ($htmlid != '' or $htmlclass != '')
            {
                $divStart = '<div'.$htmlid.' '.$htmlclass.'>';
                $divEnd = '</div>';
            }
            if ($align == "middle")
            {
                $divStart = '<div'.$htmlid.' '.$htmlclass.'style="text-align:center">';
                $divEnd = '</div>';
            }

            //Number adds for id and name

            $objectidadd = '';
          
            if ($useSwfobject == 0)
            {
                //Standard embedding

                $html = $divStart.'
				<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='.$cabversion.'" width="'.$width.'" height="'.$height.'" align="'.$align.'">
				'.$paramTags.'
				<param name="movie" value="'.$src.'" />
				<embed src="'.$src.'" '.$paramAttributes.' width="'.$width.'" height="'.$height.'" name="'.$name.$objectidadd.'" align="'.$align.'" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />
				</object>'.$divEnd;
            } else
            {
                //SWFObject static embedding

                if ($uei == 'true')
                {
                    $expressInstallStr = ' , "plugins/content/swfcontent/expressInstall.swf"';
                } else
                {
                    $expressInstallStr = '';
                }
                $js = 'swfobject.registerObject("'.$objectid.$objectidadd.'", "'.$dfv.'"'.$expressInstallStr.');';
				$document->addScriptDeclaration($js);
                $html = $divStart.'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'.$width.'" height="'.$height.'" name="'.$name.''.$objectidadd.'" id="'.$objectid.''.$objectidadd.'">
'.$paramTags.'
	<param name="movie" value="'.$src.'" />
		<!--[if !IE]>-->
		<object type="application/x-shockwave-flash" data="'.$src.'" width="'.$width.'" height="'.$height.'">
		'.$paramTags.'
		<!--<![endif]-->
		'.$flashAltHTML.'
		<!--[if !IE]>-->
		</object>
		<!--<![endif]-->
	</object>'.$divEnd;
            }
            $content = $this->_str_replaceFirst($swfPlaceHolders[$i], $html, $content);
        }
        return $content;
    }
    function _str_replaceFirst($s, $r, $str)
    {
        $l = strlen($str);
        $a = strpos($str, $s);
        $b = $a+strlen($s);
        $temp = substr($str, 0, $a).$r.substr($str, $b, ($l-$b));
        return $temp;
    }

    function _getBBCODE($content, $BBCode)
    {
        $content = $this->_getPlaceHolders($content, '['.$BBCode.']', '[/'.$BBCode.']', true);
        if ( isset ($content[0]))
        {
            $ret = trim($content[0]);
        } else
        {
            $ret = '';
        }
        if ($ret == '')
        {
            $ret = null;
        }
        return $ret;
    }

    function _getPlaceHolders($content, $start, $end, $bbcode = false)
    {
        $pos = 0;
        $oldpos = 0;
        $found = array ();
        $a = 0;
        $curpos = 0;
        while ($a < 100)
        {
            $pos = strpos("@".$content, $start, $curpos);
            $curpos = $pos+1;
            if (!($pos > 0)) return $found;
            $length = strpos(substr($content, $pos-1), $end);
            if (!($length > 0)) return $found;
            if ($bbcode)
            {
                $found[] = substr($content, $pos-1+strlen($start), $length-strlen($start));
            } else
            {
                $found[] = substr($content, $pos-1, $length+1);
            }
            $a++;
        }
        return $found;
    }

    function _getDefinitions($definitions)
    {
        $definitions = str_replace("\n", ';', $definitions);
        $definitions = str_replace("\r", ';', $definitions);
        $tmpArray = explode(';', trim($definitions));
        if ($tmpArray[0] == '' && count($tmpArray) == 1)
        {
            return;
        }
        $retDefinitions = array ();
        for ($i = 0; $i < count($tmpArray); $i++)
        {
            if (strpos($tmpArray[$i], '=') > 0)
            {
                $tmpArray2 = explode('=', $tmpArray[$i],2);
                $tmpArray2[0] = trim($tmpArray2[0], "\xc2\xa0");
                $tmpArray2[1] = trim($tmpArray2[1], "\xc2\xa0");
                $retDefinitions[trim($tmpArray2[0])] = trim($tmpArray2[1]);
            }
        }
        return $retDefinitions;
    }

    function _createHTML($array, $template)
    {
        $retArray = array ();
        $counter = 0;
        foreach ($array as $key=>$value)
        {
            $tmp = str_replace('{key}', $key, $template);
            $tmp = str_replace('{value}', $value, $tmp);
            $retArray[] = $tmp;
            $counter++;
        }
        if ($counter == 0)
            return '';
        $retString = implode("", $retArray);
    return $retString;
}
}
