<?php
#CMS - CMS Made Simple
#
# Type:		Tag
# Name:		jm_feu_user_props
# Purpose:	retrieve user properties from feu_users.
# Version:	1.0
# Date:		02 December 2011
# Author:	Fernando Morgado (JoMorg)
# Link:		NA
# Example:	{user_props}
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; version 2 of the License
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 /**
 * the input parameters are:
 * 
 *  - properties: the properties you want to get from FEU coma separated; REQUIRED!
 *  - username: the username you want to get the properties from; Optional.
 *  - uid: the user id  you want to get the properties from; Optional.
 * 
 *  (you can set one or the other or none, in which case the plugin tries to
 *   extract the username from the $_GET array. The plugin will work by priorities:
 *    1st- uid, 2nd- username, 3rd- $_GET array)
 *  - show_expired: default FALSE; Optional - set if you need to show expired accounts.
 *  - feu_group: filter user by group; Optional
 *  - if_property: use a FEU property to check for a value; Optional.
 *  - if_value: value of the if_property to compare to; REQUIRED if the if_property is set.
 *  - assign_error: if set you can get a message describing the error; Optional - for debug purposes!   
 *  - assign_error_id: if set you can get an error code (integer) and act on it; Optional - use assign_error to understand the error code;     
 *  - assign_result: should be set to get the result as an array. Optional......
 *      However ... (todo - explain better)
 * 
 * @param mixed $params
 * @param mixed $smarty
 */
function smarty_cms_function_jm_feu_user_props( $params, &$smarty )
{
    /**
    * $config['url_rewriting'] = 'mod_rewrite';

  #Extension to use if you're using mod_rewrite for pretty URLs.
  $config['page_extension'] = '/';

  #If you're using the internal pretty url mechanism or mod_rewrite, would you like to
  #show urls in their hierarchy?  (ex. http://www.mysite.com/parent/parent/childpage)
  $config['use_hierarchy'] = true;

  #If using none of the above options, what should we be using for the query string
  #variable?  (ex. http://www.mysite.com/index.php?page=somecontent)
  $config['query_var'] = 'page';
    */
    
    
    //helper - error function
    if (!function_exists(jm_errors))
    {
        function jm_errors(&$errorid, &$error, &$smarty, &$params)
        {
            //global $errorid, $error, $smarty, $params;
            if (isset($params['assign_error_id'])){$smarty->assign(trim($params['assign_error_id']),$errorid);}
            if (isset($params['assign_error'])){$smarty->assign(trim($params['assign_error']),$error);}
        }
    }
    
    // lets start by setting some defaults   
	$errorid = 0;
    $error = 'Apparantly no errors';
    $extra='';
	$result = '';    
    if (!isset( $params['expired']))
    {
        $params['show_expired'] = FALSE;
    }
    
    
	if (!isset( $params['properties']))  
    {
        $errorid = 1;
        $error = 'Properties parameter MUST be set!';
        jm_errors($errorid, $error, $smarty, $params);
        return;
    }                 
     
    // we have properties

    $properties = array_map('trim',explode(",",$params['properties']));
	$gCms = cmsms();
    $conf = $gCms->GetConfig();
    $feu = cms_utils::get_module('FrontEndUsers');
    
	if (!$feu)
	{
        $errorid = 2;
        $error = 'Cannot connect to FrontEndUsers module!';
        jm_errors($errorid, $error, $smarty, $params);
        return; 
    }
    // we have FEU Module
	
    if (isset($params['uid'])) // use ID
    {
        $uid = $params['uid']; 
        $username =  $feu->GetUserName($uid);
        if (!$username)
        {
            $errorid = 4;
            $error = 'User not found!';
            jm_errors($errorid, $error, $smarty, $params);
            return;
        }
    }
    elseif (isset($params['username']))    // use Username
    {
		$username = trim($params['username']);
        $uid = $feu->GetUserID($username);
        if (!$uid)
        {
            $errorid = 4;
            $error = 'User not found!';
            jm_errors($errorid, $error, $smarty, $params);
            return;
        }
	}
    else // use URL
    {
        $manager =& $gCms->GetHierarchyManager();
        $thisPage = $gCms->variables['content_id'];
        $currentNode = &$manager->sureGetNodeById($thisPage);
        $curcontent =& $currentNode->GetContent();
        $extra = str_replace($conf['page_extension'],'', ($_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']));
        $extra = preg_replace('%/\z|' . $conf['page_extension'] . '\z%', '', $extra);
        $filter = str_replace('http://','',str_replace($conf['page_extension'],'', $curcontent->getURL()));        
        $extra = str_replace($filter . '/', '', $extra);
        $extra = explode('/',$extra);
        $username = $extra[0];
        
        if (empty($username)) // the triage failed to produce a username or userid
        { 
            $errorid = 3;
            $error = 'Unable to extract a username or user id to compute!';
            jm_errors($errorid, $error, $smarty, $params); 
            return;              
        }

        $uid = $feu->GetUserID($username);
        if (!$uid)
        {
            $errorid = 4;
            $error = 'User not found!';
            jm_errors($errorid, $error, $smarty, $params);
            return;
        }
    }
    
    if (isset($params['feu_group']))
    {
        if (!$feu->GroupExistsByName($params['feu_group']))
        {
            $errorid = 6;
            $error = 'Group does not exist!';
            jm_errors($errorid, $error, $smarty, $params);
            return;   
        }
        
        // group exists  
    

    
        $gid = $feu->GetGroupID(trim($params['feu_group']));
        
        if (!$feu->MemberOfGroup($uid,$gid))
        {
            $errorid = 7;
            $error = 'User does not belong to this group!';
            jm_errors($errorid, $error, $smarty, $params);
            return;                       
        } 
    } 
    
    // cleared from group triage -> carry on!
    
    // now let's check for expired user
    if ($feu->IsAccountExpired( $uid ) && (!$params['show_expired']))
    {
        $errorid = 5;
        $error = 'This user account has expired!';
        jm_errors($errorid, $error, $smarty, $params);
        return;
    }
            
			
    if (isset($params['if_property']))
    {
      if (!isset($params['if_value']))
      {
          $errorid = 8;
          $error = 'When using if_property if_value must be used!';
          jm_errors($errorid, $error, $smarty, $params);
          return;                  
      }  
    }
               
	$feuproperties = $feu->GetUserProperties($uid);

	//echo var_dump(trim($params['if_property'])). '<br /\>';
	foreach($properties as $property)
	{
		foreach($feuproperties as $key=>$value)
		{
            if (($value["title"] == trim($params['if_property'])))
            {                
                if (!($value['data'] == trim($params['if_value'])))
                {
                    unset($result);
                    $errorid = 9;
                    $error = 'if_property does not match if_value!';
                    jm_errors($errorid, $error, $smarty, $params);
                    return;    
                }
            }
            
			if ($value["title"] == trim($property))
			{
                $result[$value["title"]] = $value['data'];
		    }
		}
	} // foreach($properties as $property) <- end

	

	if (isset($params['assign_result']))      
	{
		$smarty->assign(trim($params['assign_result']),$result);
        var_dump($result);
        jm_errors($errorid, $error, $smarty, $params);
		return;
	}
	jm_errors($errorid, $error, $smarty, $params);
	return implode('<br /\>', $result);
}

function smarty_cms_help_function_jm_feu_user_props()
{
?>
<h3>What does this do?</h3>
<p>This tag retrieves properties from FEU Module.<br />
The idea is to be able to retrieve an array filled with properties, and use them
anywere needed in a template or content block.<br />
One of the objectives was to be able to give my FE users the ability to have a
small page of their own, accessible through an unique URL they could give to their
potencial visitors:</p>
<p><big><code>http://www.<em>yourdomain</em>.com/<em>usergroup</em>/<em>username</em>.html</code></big></p>
<p>or</p>
<p><big><code>http://www.<em>yourdomain</em>.com/<em>users</em>/<em>username</em>.html</code></big></p>
<p>This does not replace CGUserDirectory although but doesn't require it.<br />
It has a different purpose than the CGUserDirectory module.<br />
This plugin <strong>requires</strong> FEU module, and is meant to be used with Pretty URL's
and the following configuration:</p>

<p><big><code> $config['url_rewriting'] = 'mod_rewrite';</code></big></p>

<h3>How do I use it?</h3>

<p>This is a basic example of how to use it:</p>

<p>Insert tag <strong>{jm_feu_user_props <em>[parameters]</em>}</strong>
in your <strong>Content</strong> textarea, <strong>Smarty data or logic that is specific to this page</strong> textarea, or template:<br /><br />
<big><code>{jm_feu_user_props properties='somefeuproperty1,somefeuproperty2,somefeuproperty3,...,somefeuproperty_n'}</code></big></p>
<p>This will return the following result:</p>
<p><big><code><strong>somefeuproperty1&ltbr /&gt;somefeuproperty2&ltbr /&gt;somefeuproperty3&ltbr /&gt;...&ltbr /&gt;somefeuproperty_n&ltbr /&gt;</strong></code></big></p>
<p>Not very usable but that's the basic...</p>
<p>Advanced use of this tag assumes that you pass some variable names to assign the different results:</p>
<p><big><code>{jm_feu_user_props properties='feuprop1,feuprop2,somefeuprop3'
assign_error_id='userprops_error_id' assign_result='user_props'
feu_group='feu_group' if_property='feuprop4' if_value='somevalue'}</code></big></p>
<p>This more advanced use has almost all parameters filled. The expected result are as follows:</p>
<p><strong>assign_result='user_props'</strong>: with this parameter set the plugin goes into <em>silent mode</em>,
meaning that the smarty variable user_props will hold an array with the values of the properties you wanted:<br /><br />
<big><code>
user_props array(4){ <br />
&nbsp;&nbsp;&nbsp;["feuprop1"]=> "value1" <br />
&nbsp;&nbsp;&nbsp;["feuprop2"]=> "value2" <br />
&nbsp;&nbsp;&nbsp;["feuprop3"]=> "value3" <br />
&nbsp;&nbsp;}
</code></big> <br />
So you can access them in your template like this:<br /> <br />
<big><code>
{$user_props.feuprop1}<br />
{$user_props.feuprop2}<br />
{$user_props.feuprop3}
</code></big></p>
<p><strong>OK, so where is the username coming from?</strong></p>
<p>from: <big><code><em>http://www.yourdomain.com/usergroup</em>/<strong>username</strong><em>.html</em></code></big><br />
or even: <big><code><em>http://www.yourdomain.com/usergroup</em>/<strong>username</strong><em>/</em></code></big></p>
<p>By default the username is captured from the URL, except when the parameters <strong><code>username</code></strong> or <strong><code>uid</code></strong> are used.<br />
These override by priorities: <strong><code>uid</code></strong> overrides <strong><code>username</code></strong> which in turn overrides the URL capture.</p>
<p>Also, in the previous example you get this:<br />
a) if the user doesn't belong to <strong><code>feu_group='feu_group'</code></strong> the properties array is NULL;<br />
b) if the <strong><code>if_property='somefeuprop'</code></strong> value doesn't match the
<strong><code>if_value='somevalue'</code></strong> the properties array is NULL;<br />
c) if you use <strong><code>if_property='somefeuprop'</code></strong>, you <strong>MUST</strong> use
<strong><code>if_value='somevalue'</code></strong> otherwise the properties array is NULL no matter what;<br />
d) The plugin generates error codes, assign to <strong><code>assign_error_id='userprops_error_id'</code></strong>
 giving you the chance to use some <big>if...then...else</big> logic with Smarty</p>

<p>Although you can use the plugin tag inside your template or content block,
it makes sense if you use it inside the <strong>Smarty data or logic that is specific to this page</strong> textarea as
it enables you to use any of the variables (the one, for instance, that holds the full User Name
or the 1st and last names) in the Page title.</p>
<p><strong>Errors and Error Codes</strong></p>
<p><small><strong>Error Code</strong></small> - Explanation</p>
<p>
<strong>0</strong> - No error;<br />
<strong>1</strong> - <strong><code>properties parameter</code></strong> <strong>MUST</strong> be set!<br />
<strong>2</strong> - Cannot connect to FrontEndUsers module!<br />
<strong>3</strong> - Unable to extract a username or user id to compute!<br />
<strong>4</strong> - User not found!<br />
<strong>5</strong> - This user account has expired!<br />
<strong>6</strong> - Group does not exist!<br />
<strong>7</strong> - User does not belong to this group!<br />
<strong>8</strong> - When using <strong><code>if_property</code></strong>, <strong><code>if_value</code></strong> must be used!<br />
<strong>9</strong> - <strong><code>if_property</code></strong> does not match <strong><code>if_value</code></strong>!<br />
</p>




<h3>What parameters does it take?</h3>

<ul>
    <li><em>(required)</em> <tt>properties</tt>: a property or a comma separated list of properties you wish to retrieve from FEU.</li>
    <li><em>(optional)</em> <tt>username</tt>: the username you want to get the properties from.</li>
    <li><em>(optional)</em> <tt>uid</tt>: the user id  you want to get the properties from.</li>
    <li><em>(optional)</em> <tt>show_expired</tt>: set if you need to show expired accounts. Default <tt>FALSE</tt>.</li>
    <li><em>(optional)</em> <tt>feu_group</tt>: filter user by group.</li>
    <li><em>(optional)</em> <tt>if_property</tt>: use a FEU property to check for a value. If there is no match just returns an error.</li>
    <li><em>(optional)</em> <tt>if_value</tt>: value of the if_property to compare to; <strong><tt>REQUIRED</tt></strong> if the <tt>if_property</tt> is set.</li>
    <li><em>(optional)</em> <tt>assign_error</tt>: Smarty variable to be assigned with a message describing the error; for debug purposes!</li>
    <li><em>(optional)</em> <tt>assign_error_id</tt>: Smarty variable to be assigned with an error code (integer) and act on it; Optional use assign_error to understand the error code;</li>
    <li><em>(optional)</em> <tt>assign_result</tt>: Smarty variable to be assigned with an array containing the result. If set there will be no other output (silent mode).</li>
</ul>
<?php
}

function smarty_cms_about_function_jm_feu_user_props()
{
?>
<p>Author: Fernando Morgado (JoMorg)</p>
<p>Version: 1.0</p>
<p>Change History:<br />
1.0 - Initial release<br />
</p>
<?php
}
?>