<?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


/**
 * @deprecated
 */
final class mams_utils
{
    private static $_mod;
    private static $_userfiles;

    private function __construct() {}
  
  /**
   * @param $method
   * @param $args
   *
   * @return mixed|void
   * @throws \MAMS\DeprecatedMethodException
   */
  public static function __callStatic($method, $args)
  {
    if(method_exists(\MAMS\utils::class, $method))
    {
      return forward_static_call_array([\MAMS\utils::class, $method], $args);
    }
    // Trigger a custom exception for deprecated methods
    throw new \MAMS\DeprecatedMethodException($method);
  }
  
  
  /**
   * We keep this until we can get rid of it.
   * __callStatic doesn't support passing arguments by reference
   * this will be removed as soon as possible
   *
   * @param $filter
   * @param $offset
   * @param $total_matches
   * @deprecated
   * @see \MAMS\utils::get_users_from_filter
   *
   * @return array
   * @throws \CmsException
   */
  public static function get_users_from_filter($filter, $offset, &$total_matches)
  {
    $limit          = $filter['limit'];
    $groupid        = $filter['group'];
    $userregex      = $filter['regex'];
    $property       = $filter['propsel'];
    $propregex      = $filter['propval'];
    $loggedinonly   = $filter['loggedinonly'];
    $sort           = $filter['sortby'];
    $disabledstatus = $filter['disabledstatus'] ?? NULL;
    
    // todo: this should go into the consumer.
    $query = new \mams_user_query();
    $query->set_result_type(\mams_user_query::RESULT_TYPE_FULL);
    
    if((int)$limit > 0) { $query->set_pagelimit($limit); }
    
    if((int)$offset > 0) { $query->set_offset($offset); }
    
    if($groupid > 0)
    {
      $query->add_and_opt(\mams_user_query_opt::MATCH_GROUPID, $groupid);
    }
    
    if($userregex)
    {
      $query->add_and_opt(\mams_user_query_opt::MATCH_USERNAME_RE, $userregex);
    }
    
    if($property)
    {
      $defn = self::get_mod()->GetPropertyDefn($property);
      $obj  = NULL;
      
      # changed recently keep an eye on this
      if(($defn['type'] == \MAMS::FIELDTYPE_CHECKBOX) && '0' === \trim($propregex))
      {
        // need to test if the property is NOT set
        $obj = new \mams_user_query_opt(\mams_user_query_opt::MATCH_NOTHASPROPERTY, $property);
      }
      
      if(!$obj && $propregex)
      {
        $obj = new \mams_user_query_opt(\mams_user_query_opt::MATCH_PROPERTY_RE, $property, $propregex);
      }
      
      if($obj) { $query->add_and_opt_obj($obj); }
    }
    
    if($loggedinonly)
    {
      $query->add_and_opt(\mams_user_query_opt::MATCH_LOGGEDIN, 1);
    }
    
    switch($disabledstatus)
    {
      case 'en':
        $query->add_and_opt(\mams_user_query_opt::MATCH_NOTDISABLED);
      break;
      case 'dis':
        $query->add_and_opt(\mams_user_query_opt::MATCH_DISABLED);
      break;
    }
    
    switch($sort)
    {
      case 'username':
      case 'username asc':
        $query->set_sortby(\mams_user_query::RESULT_SORTBY_USERNAME);
        $query->set_sortorder(\mams_user_query::RESULT_SORTORDER_ASC);
      break;
      case 'username desc':
        $query->set_sortby(\mams_user_query::RESULT_SORTBY_USERNAME);
        $query->set_sortorder(\mams_user_query::RESULT_SORTORDER_DESC);
      break;
      case 'createdate':
      case 'createdate asc':
        $query->set_sortby(\mams_user_query::RESULT_SORTBY_CREATED);
        $query->set_sortorder(\mams_user_query::RESULT_SORTORDER_ASC);
      break;
      case 'createdate desc':
        $query->set_sortby(\mams_user_query::RESULT_SORTBY_CREATED);
        $query->set_sortorder(\mams_user_query::RESULT_SORTORDER_DESC);
      break;
      case 'expires':
      case 'expires asc':
        $query->set_sortby(\mams_user_query::RESULT_SORTBY_EXPIRES);
        $query->set_sortorder(\mams_user_query::RESULT_SORTORDER_ASC);
      break;
      case 'expires desc':
        $query->set_sortby(\mams_user_query::RESULT_SORTBY_EXPIRES);
        $query->set_sortorder(\mams_user_query::RESULT_SORTORDER_DESC);
      break;
    }
    
    $rs            = $query->execute();
    $total_matches = $rs->get_found_rows();
    $data          = [];
    while(!$rs->EOF)
    {
      $data[] = $rs->fields;
      $rs->MoveNext();
    }
    
    return $data;
  }
  
  
    /***
     * temporary functions
     */
  
  
    /**
     * Returns the xhtml equivalent of a textarea.	Also takes WYSIWYG preference into consideration if it's called from the admin side.
     *
     * @param bool   $enablewysiwyg Should we try to create a WYSIWYG for this textarea?
     * @param string $id The id given to the module on execution
     * @param string $text The text to display in the textarea's content
     * @param string $name The html name of the textarea
     * @param string $classname The CSS class to associate this textarea to
     * @param string $htmlid The html id to give to this textarea
     * @param string $encoding The encoding to use for the content
     * @param string $stylesheet The text of the stylesheet associated to this content.	 Only used for certain WYSIWYGs
     * @param string $cols The number of characters wide (columns) the resulting textarea should be
     * @param string $rows The number of characters high (rows) the resulting textarea should be
     * @param string $forcewysiwyg The wysiwyg-system to be forced even if the user has chosen another one
     * @param string $wantedsyntax The language the content should be syntaxhightlighted as
     * @param string $addtext Any additional text to include with the textarea field.
     * @return string
     *
     * @see CmsFormUtils::create_textarea
     */
    static function CreateTextArea($enablewysiwyg, $id, $text, $name, $classname='', $htmlid='', $encoding='', $stylesheet='', $cols='', $rows='',$forcewysiwyg='',$wantedsyntax='',$addtext='')
    {
      $parms = array();
      $parms['enablewysiwyg'] = $enablewysiwyg;
      $parms['name'] = $id.$name;
      if( $classname ) $parms['class'] = $classname;
      if( $htmlid ) $parms['id'] = $htmlid;
      if( $encoding ) $parms['encoding'] = $encoding;
      if( $stylesheet ) $parms['stylesheet'] = $stylesheet;
      if( $cols ) $parms['cols'] = $cols;
      if( $rows ) $parms['rows'] = $rows;
      if( $text ) $parms['text'] = $text;
      if( $forcewysiwyg ) $parms['forcemodule'] = $forcewysiwyg;
      if( $wantedsyntax ) $parms['wantedsyntax'] = $wantedsyntax;
      if( $addtext ) $parms['addtext'] = $addtext;
  
      try {
        return self::create_textarea($parms);
      }
      catch( CmsException $e ) {
        return '';
      }
    }
  
    /**
     * A method to create a text area control.
     * parameters:
     *   name          = (required string) name attribute for the text area element.
     *   id            = (optional string) id attribute for the text area element.  If not specified, name is used.
     *   class/classname = (optional string) class attribute for the text area element.  Some values will be added to this string.
     *                   default is cms_textarea
     *   forcemodule   = (optional string) used to specify the module to enable.  If specified, the module name will be added to the
     *                   class attribute.
     *   enablewysiwyg = (optional boolan) used to specify wether a wysiwyg textarea is required.  sets the language to html.
     *   wantedsyntax  = (optional string) used to specify the language (html,css,php,smarty) to use.  If non empty indicates that a
     *                   syntax hilighter module is requested.
     *   cols/width    = (optional integer) columns of the text area (css or the syntax/wysiwyg module may override this)
     *   rows/height   = (optional integer) rows of the text area (css or the syntax/wysiwyg module may override this)
     *   maxlength     = (optional integer) maxlength attribute of the text area (syntax/wysiwyg module may ignore this)
     *   required      = (optional boolean) indicates a required field.
     *   placeholder   = (optional string) placeholder attribute of the text area (syntax/wysiwyg module may ignore this)
     *   value/text    = (optional string) default text for the text area, will undergo entity conversion.
     *   encoding      = (optional string) default utf-8 encoding for entity conversion.
     *   addtext       = (optional string) additional text to add to the textarea tag.
     *   cssname       = (optional string) Pass this stylesheet name to the WYSIWYG area if any.
     *
     * note: if wantedsyntax is empty, AND enablewysiwyg is false, then just a plain text area is creeated.
     *
     * @param array $parms An associative array with parameters.
     * @return string
     */
    public static function create_textarea($parms)
    {
      // todo: rewrite me with var args... to accept a numeric array of arguments, or a hash.
      $haveit = FALSE;
      $result = '';
      $uid = get_userid(false);
      $attribs = array();
      $module = null;
      $attribs['name'] = get_parameter_value($parms,'name');
      if( !$attribs['name'] ) throw new CmsInvalidDataException('"name" is a required parameter"');
      $attribs['id'] = get_parameter_value($parms,'id',$attribs['name']);
      $attribs['class'] = get_parameter_value($parms,'class','cms_textarea');
      $attribs['class'] = get_parameter_value($parms,'classname',$attribs['class']); // classname param can override class.
  
      $forcemodule = get_parameter_value($parms,'forcemodule');
      $enablewysiwyg = cms_to_bool(get_parameter_value($parms,'enablewysiwyg',false)); // if true, we want a wysiwyg area
      $wantedsyntax = get_parameter_value($parms,'wantedsyntax'); // if not null, and no wysiwyg found, use a syntax area.
      $wantedsyntax = get_parameter_value($parms,'type',$wantedsyntax);
      $attribs['class'] .= ' '.$attribs['name']; // make sure the name is one of the classes.
      foreach( $parms as $key => $val ) {
        if( startswith( $key, 'data-') ) $attribs[$key] = $val;
      }
  
      if( $enablewysiwyg ) {
        // we want a wysiwyg
        $appendclass = 'cmsms_wysiwyg';
        $module = ModuleOperations::get_instance()->GetWYSIWYGModule($forcemodule);
        if( $module && $module->HasCapability(CmsCoreCapabilities::WYSIWYG_MODULE) ) {
          $appendclass = $module->GetName();
          $attribs['data-cms-lang'] = 'html';
          $css_name = get_parameter_value($parms,'cssname',self::NONE);
          self::_add_wysiwyg($module->GetName(),$attribs['id'],$css_name);
        } else {
          // just incase forced module is not a wysiwyg module.
          $module = null;
        }
        $attribs['class'] .= ' '.$appendclass;
      }
  
      if( !$module && $wantedsyntax ) {
        $attribs['data-cms-lang'] = trim($wantedsyntax);
        $module = ModuleOperations::get_instance()->GetSyntaxHighlighter($forcemodule);
        if( $module && $module->HasCapability(CmsCoreCapabilities::SYNTAX_MODULE) ) {
          $attribs['class'] .= ' '.$module->GetName();
          self::_add_syntax($module->GetName());
        } else {
          // wanted a syntax module, but couldn't find one...
          $module = null;
        }
      }
  
      $required = cms_to_bool(get_parameter_value($parms,'required','false'));
      if( $required ) $attribs['required'] = 'required';
      $attribs['cols'] = get_parameter_value($parms,'cols');
      $attribs['cols'] = get_parameter_value($parms,'width',$attribs['cols']);
      if( $attribs['cols'] <= 0 || $attribs['cols'] == '') $attribs['cols'] = 20;
      $attribs['rows'] = get_parameter_value($parms,'rows');
      $attribs['rows'] = get_parameter_value($parms,'height',$attribs['rows']);
      if( $attribs['rows'] <= 0 || $attribs['cols'] == '' ) $attribs['rows'] = 5;
      $attribs['maxlength'] = get_parameter_value($parms,'maxlength');
      if( $attribs['maxlength'] <= 0 ) $attribs['maxlength'] = '';
      $attribs['placeholder'] = get_parameter_value($parms,'placeholder');
  
      $addtext = get_parameter_value($parms,'addtext');
      $text = get_parameter_value($parms,'value');
      $text = get_parameter_value($parms,'text',$text);
  
      $result = '<textarea';
      foreach( $attribs as $key => $val ) {
        if( $val != '' && $key != '' ) {
          $key = trim($key);
          $val = trim($val);
          $result .= " {$key}=\"{$val}\"";
        }
      }
      if( !empty( $addtext ) ) $result .= ' '.$addtext;
      //$result .= '>'.cms_htmlentities($text,ENT_NOQUOTES,CmsNlsOperations::get_encoding()).'</textarea>';
      $result .= '>'. $text .'</textarea>';
      return $result;
    }
  
} // class

#
# EOF
#
