<?php
#BEGIN_LICENSE
#-------------------------------------------------------------------------
# Module: MAMS (c) 2020-2021 by CMS Made Simple Foundation
#  An add-on module for CMS Made Simple to provide useful functions
#  and commonly used gui capabilities to other modules.
#-------------------------------------------------------------------------
# A fork of:
#
# Module: FrontEndUsers (c) 2008-2014 by Robert Campbell
#         (calguy1000@cmsmadesimple.org)
#
#-------------------------------------------------------------------------
#
# CMSMS - CMS Made Simple is (c) 2006 - 2021 by CMS Made Simple Foundation
# CMSMS - CMS Made Simple is (c) 2005 by Ted Kulp (wishy@cmsmadesimple.org)
# Visit the CMSMS Homepage at: http://www.cmsmadesimple.org
#
#-------------------------------------------------------------------------
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# However, as a special exception to the GPL, this software is distributed
# as an addon module to CMS Made Simple.  You may not use this software
# in any Non GPL version of CMS Made simple, or in any version of CMS
# Made simple that does not indicate clearly and obviously in its admin
# section that the site was built with CMS Made simple.
#
# 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
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
#END_LICENSE
if( !defined('CMS_VERSION') ) { exit; }

$_SESSION['mams']['errorid'] = 0;
$can_changepasswd = TRUE;
$consumer         = mams_utils::get_auth_consumer();
$can_changepasswd = $consumer->has_capability(mams_auth_consumer::CAPABILITY_CHANGEPASSWD);

$uid = $this->LoggedInId();

if($uid < 1)
{
  $_SESSION['mamscs']['errorid'] = 1;
  $_SESSION['mamscs']['error'] = 'not_logged_in_or_nonexistent';
  $_SESSION['mamscs']['error_message'] = 'You are not logged in.';
  return;
}

$result = $this->GetUserInfo($uid);

if(!$result[0])
{
  // user isn't logged in
  $_SESSION['mamscs']['errorid'] = 2;
  $_SESSION['mamscs']['error'] = 'not_logged_in_or_account_expired';
  $_SESSION['mamscs']['error_message'] = 'You are not logged in.';
  $this->_DisplayErrorPage($id, $params, $returnid, $result[1]);
  
  return;
}

if($consumer->has_capability(mams_auth_consumer::CAPABILITY_CHANGESETTINGS))
{
  // the consumer provides the login capabilities
  echo $consumer->get_changesettings_display($id, $returnid, $params);
  
  return;
}

if(!$consumer->has_capability(mams_auth_consumer::CAPABILITY_USESTDCHANGESETTINGS)) { return; }

$uinfo = $result[1];

// get the users member groups
$groups = $this->GetMemberGroupsArray($uid);

//if(!$groups)
//{
//  // this user is not a member of any gruops...
//  // handle this later todo
//  $this->_DisplayErrorPage($id, $params, $returnid, $this->Lang('error_nogroups'));
//
//  return;
//}

// now we have the groups, we build a union of all of the groups properties
$properties = [];

foreach($groups as $grprecord)
{
  $gid           = $grprecord['groupid'];
  $proprelations = $this->GetGroupPropertyRelations($gid);
  
  if(is_array($proprelations) && count($proprelations) == 2 && $proprelations[0] === FALSE) { continue; }
  
  if(count($properties))
  {
    $properties = \MAMS\RRUtils::array_merge_by_name_required($properties, $proprelations);
  }
  else
  {
    $properties = $proprelations;
  }
}

uasort($properties, array('xt_array', 'compare_elements_by_sortorder_key'));

if(count($properties) == 0 && 0) # mandatory properties per group will be a preference (JM)
{
  if($this->GetPreference('require_onegroup') == 1)
  {
    // this user is not a member of any groups...
    // handle this later todo
    
    $this->_DisplayErrorPage($id, $params, $returnid, $this->Lang('error_onegrouprequired'));
    
    return;
  }
}

// now we're ready to populate the template
// first we put in stuff that is required (username, password, etc, etc)
$rowarray = [];

// make sure username is in there
// we can hide it in the template.
$val                = $uinfo['username'];
$onerow             = new StdClass();
$onerow->name       = 'username';
$onerow->type       = ($this->GetPreference('username_is_email')) ? 2 : 0;
$onerow->color      = $this->GetPreference('required_field_color', 'blue');
$onerow->marker     = $this->GetPreference('required_field_marker', '*');
$onerow->required   = 1;
$onerow->prompt     = $consumer->get_username_prompt();
$onerow->value      = $val;
$onerow->input_id   = 'mams_input_username';
$onerow->input_name = $id . $onerow->input_id;
$onerow->length     = $this->GetPreference('usernamefldlength', 40);
$onerow->maxlength  = $this->GetPreference('max_usernamelength', 80);
$onerow->readonly   = (!$consumer->has_capability(mams_auth_consumer::CAPABILITY_CHANGEUSERNAME));

$tmp = 'disabled="disabled"';

if($consumer->has_capability(mams_auth_consumer::CAPABILITY_CHANGEUSERNAME)) { $tmp = ''; }

$onerow->control         = $this->CreateInputText(
  $id, 'mams_input_username', $val, $onerow->length, $onerow->maxlength, $tmp
);

$rowarray[$onerow->name] = $onerow;

if($can_changepasswd)
{
  // and password
  $val = '';
  if(isset($params['mams_input_password']))
  {
    $val = $params['mams_input_password'];
  }
  
  $onerow           = new StdClass();
  $onerow->name     = 'password';
  $onerow->type     = 'password';
  $onerow->color    = NULL;
  $onerow->required = ($uinfo['force_newpw']) ? 1 : 0;
  $onerow->marker   = NULL;
  
  if($onerow->required)
  {
    $onerow->color  = $this->GetPreference('required_field_color', 'blue');
    $onerow->marker = $this->GetPreference('required_field_marker', '*');
  }
  
  $onerow->prompt          = $this->Lang('password');
  $onerow->control         = $this->CreateInputPassword(
    $id, 'mams_input_password', $val,
    $this->GetPreference('passwordfldlength'),
    $this->GetPreference('max_passwordlength')
  );
  
  $onerow->addtext         = $this->Lang('info_emptypasswordfield');
  $onerow->value           = NULL;
  $onerow->input_id        = 'mams_input_password';
  $onerow->input_name      = $id . $onerow->input_id;
  $onerow->length          = $this->GetPreference('passwordfldlength');
  $onerow->maxlength       = $this->GetPreference('max_passwordlength');
  $onerow->readonly        = FALSE;
  $rowarray[$onerow->name] = $onerow;
  
  // and make him repeat the password
  $val = '';
  
  if(isset($params['mams_input_repeatpassword']))
  {
    $val = $params['mams_input_repeatpassword'];
  }
  
  $onerow           = new StdClass();
  $onerow->name     = 'repeat_password';
  $onerow->type     = 'password';
  $onerow->color    = NULL;
  $onerow->marker   = NULL;
  $onerow->required = ($uinfo['force_newpw']) ? 1 : 0;
  
  if($onerow->required)
  {
    $onerow->marker = $this->GetPreference('required_field_marker', '*');
    $onerow->color  = $this->GetPreference('required_field_color', 'blue');
  }
  
  $onerow->prompt          = $this->Lang('repeatpassword');
  $onerow->control         = $this->CreateInputPassword(
    $id, 'mams_input_repeatpassword', $val,
    $this->GetPreference('passwordfldlength'),
    $this->GetPreference('max_passwordlength')
  );
  
  $onerow->addtext         = $this->Lang('info_emptypasswordfield');
  $onerow->value           = NULL;
  $onerow->input_id        = 'mams_input_repeatpassword';
  $onerow->input_name      = $id . $onerow->input_id;
  $onerow->length          = $this->GetPreference('passwordfldlength');
  $onerow->maxlength       = $this->GetPreference('max_passwordlength');
  $onerow->readonly        = FALSE;
  $rowarray[$onerow->name] = $onerow;
}

$encrypt_color  = $this->GetPreference('secure_field_color', 'yellow');
$encrypt_marker = $this->GetPreference('secure_field_marker', '^^');


// now for the properties
foreach($properties as $prop)
{
  // get the property definition
  $defn = $this->GetPropertyDefn($prop['name']);
  
  if($prop['required'] == 3){continue;} // hidden.
  
  $onerow             = new StdClass();
  $onerow->name       = $prop['name'];
  $onerow->propname   = $prop['name'];
  $onerow->input_id   = 'mams_input_' . $onerow->propname;
  $onerow->input_name = $id . $onerow->input_id;
  $val                = $this->GetUserPropertyFull($prop['name'], $uid);
  
  if(isset($params[$onerow->input_id]))
  {
    $val = $params[$onerow->input_id];
  }
  
  // begin building the object that contains data for building the fields.
  $onerow->type      = $defn['type'];
  $onerow->encrypted = $defn['encrypt'];
  $onerow->required  = ($prop['required'] == 2);
  $onerow->readonly  = ($prop['required'] == 4);
  $onerow->status    = $prop['required'];
  $onerow->color     = NULL;
  $onerow->marker    = NULL;;
  $onerow->value     = $val;
  $onerow->length    = $defn['length'];
  $onerow->maxlength = $defn['maxlength'];
  $onerow->prompt    = $defn['prompt'];
  
  if($defn['encrypt'])
  {
    $onerow->color  = $encrypt_color;
    $onerow->marker = $encrypt_marker;
  }
  else if($onerow->required)
  {
    $onerow->color  = $this->GetPreference('required_field_color', 'blue');
    $onerow->marker = $this->GetPreference('required_field_marker', '*');
  }
  
  switch($defn['type'])
  {
    case 0: // text
      $onerow->control = $this->CreateInputText($id, $onerow->input_name, $val, $defn['length'], $defn['maxlength']);
    break;
    
    case 1: // checkbox
      $onerow->control = $this->CreateInputHidden($id, $onerow->input_name, 0);
      $onerow->control .= \MAMS\RRUtils::myCreateInputCheckbox($id, $onerow->input_name, 1, $val);
    break;
    
    case 2: // email
      $onerow->control = $this->CreateInputText($id, $onerow->input_name, $val, $defn['length'], $defn['maxlength']);
    break;
    
    case 3: // textarea
      $flag = FALSE;
      if(isset($defn['attribs']) && !empty($defn['attribs']))
      {
        $attribs = unserialize($defn['attribs']);
        if(is_array($attribs) && isset($attribs['wysiwyg']))
        {
          $flag = $attribs['wysiwyg'];
        }
      }
      $onerow->wysiwyg = $flag;
      $onerow->control = $this->CreateTextArea($flag, $id, $val, $onerow->input_name);
    break;
    
    case 4: // dropdown
      $opts            = $this->GetSelectOptions($defn['name']);
      $onerow->options = array_flip($opts);
      $onerow->control = $this->CreateInputDropdown($id, $onerow->input_name, $opts, -1, $val);
    break;
    
    case 5: // multiselect
      $opts             = $this->GetSelectOptions($defn['name']);
      $onerow->options  = array_flip($opts);
      
      # just in case, make sure we have a comma separated list
      if(is_array($val)) { $val = implode(',', $val); }
      
      $onerow->selected = explode(',', $val);
      $onerow->control  = $this->CreateInputSelectList(
        $id, $onerow->input_name . '[]', $opts, $onerow->selected, $defn['length']
      );
    break;
    
    case 6: // image
      $config = cmsms()->GetConfig();
      $destDir1 = $config['uploads_path'] . DIRECTORY_SEPARATOR;
      $destDir1 .= $this->GetPreference('image_destination_path', 'mams') . DIRECTORY_SEPARATOR;
      $destDir2 = $config['uploads_url'] . '/';
      $destDir2 .= $this->GetPreference('image_destination_path', 'mams') . '/';
      $file1    = $destDir1 . $val;
      $file2    = $destDir2 . $val;
      
      if(is_readable($file1) && is_file($file1))
      {
        $onerow->image_url = $file2;
        $onerow->image     = '<img src="' . $file2 . '" alt="' . $val . '"/>';
        if(!$onerow->required)
        {
          $onerow->prompt2     = $this->Lang('prompt_clear');
          $onerow->input_name2 = $onerow->input_name . '_clear';
          $onerow->control2    = $this->CreateInputCheckbox($id, $onerow->input_name . '_clear', 'clear', '');
        }
      }
      $onerow->control = $this->CreateInputHidden($id, $onerow->input_name, $val) .
                         $this->CreateFileUploadInput($id, 'mams_' . $onerow->input_name, '', $defn['length']);
    break;
    
    case '7': // radio group
      $opts            = $this->GetSelectOptions($defn['name']);
      $onerow->options = array_flip($opts);
      $onerow->control = $this->CreateInputRadioGroup($id, $onerow->input_name, $opts, $val, '', '<br/>');
    break;
    
    case '8': // date
      $parms           = array();
      $parms['prefix'] = $onerow->input_id;
      if($val)
      {
        $parms['time'] = $val;
      }
      $parms['start_year'] = "-5";
      $parms['end_year']   = "+10";
      
      if(isset($defn['attribs']) && !empty($defn['attribs']))
      {
        $attribs = unserialize($defn['attribs']);
        if(isset($attribs['startyear']) && !empty($attribs['startyear']))
        {
          $parms['start_year'] = $attribs['startyear'];
        }
        if(isset($attribs['endyear']) && !empty($attribs['endyear']))
        {
          $parms['end_year'] = $attribs['endyear'];
        }
      }
      
      $rel_to_abs_year = function($str){
        if(startswith($str, '-'))
        {
          $v    = (int)substr($str, 1);
          $year = date('Y') - $v;
          
          return $year;
        }
        else if(startswith($str, '+'))
        {
          $v    = (int)substr($str, 1);
          $year = date('Y') + $v;
          
          return $year;
        }
        
        return (int)$str;
      };
      
      $str = '{html_select_date ';
      foreach($parms as $key => $value)
      {
        $str .= $key . '="' . $value . '" ';
      }
      $str                .= '}';
      $onerow->control    = $this->ProcessTemplateFromData($str);
      $onerow->start_year = $rel_to_abs_year($parms['start_year']);
      $onerow->end_year   = $rel_to_abs_year($parms['end_year']);
    
    break;
  }
  $rowarray[$prop['name']] = $onerow;
}

// fill in the variables for the template
$thetemplate = \mams_utils::get_template($params, 'changesettingstemplate', 'MAMS::chsettings form');
$tpl         = $this->CreateSmartyTemplate($thetemplate);

if(isset($params['error']))
{
  $tpl->assign('error', $params['error']);
}

if(isset($params['message']))
{
  $tpl->assign('message', $params['message']);
}

$tpl->assign('title', $this->Lang('user_settings')); // deprecated
$tpl->assign('startform', $this->XTCreateFormStart($id, 'do_userchangesettings', $returnid));
$tpl->assign('endform', $this->CreateFormEnd());
$tpl->assign('submit', $this->CreateInputSubmit($id, 'mams_submit', $this->Lang('submit'))); // deprecated

if(isset($params['returnto']))
{
  $tpl->assign('hidden', $this->CreateInputHidden($id, 'mams_returnto', $params['returnto']));
}

$tpl->assign('formid', $id);
$tpl->assign('controls', $rowarray);
$tpl->assign('controlcount', count($rowarray));
$tpl->display();

// EOF
