<?php
// +---------------------------------------------+
// |     Copyright 2008 - 2018 weenCompany |
// |     http://www.weentech.com               |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

// this file contains functions that are used in both the front and backend of weenCompany

if(!defined('IN_WEENCOMPANY'))
  die('·Ç·¨½øÈë!');



// ############################# STRIPSLASHES ARRAY ##############################
// weencompany needs to remove slashes that PHP might have added if magic quotes was turned on

function StripSlashesArray($data)
{
  if(is_array($data))
  {
    foreach($data as $key => $val)
    {
      $return[$key] = StripSlashesArray($val);
    }
    return ($return);
  }
  else
  {
    return (stripslashes($data));
  }
}



// ############################# ADDSLASHES ARRAY ##############################
// the weencompany core will addslashes to all $_POST, $_GET, and $_COOKIE data
// in the admin panel. This isn't done in the frontend becuase weencompany converts
// quotes to their html entities.

function AddSlashesArray($data)
{
  if(is_array($data))
  {
    foreach($data as $key => $val)
    {
      $return[$key] = AddSlashesArray($val);
    }
    return ($return);
  }
  else
  {
    return (addslashes($data));
  }
}



// ############################ UNHTMLSPECIALCHARS #############################
// this is exactly like PHP's html_entity_decode
// however html_entity_decode only works on PHP > 4.3.0 or 5

function unhtmlspecialchars($string)
{
  // special character handling
  // utf8_decode and reconvert HTML entities (e.g. &uuml; ==> ?
  $trans = get_html_translation_table(HTML_ENTITIES);

  // ipb uses different (or old) entities, so lets fix em to our style!
  $string = str_replace('&#39;', '&#039;', $string);
  $string = str_replace('&#33;', '&#033;', $string);

  // some versions of PHP match single quotes to &#39;
  $trans["'"] = '&#039;';
  $trans["!"] = '&#033;';
  $trans["$"] = '&#036;';

  $trans = array_flip ($trans);

  return strtr($string, $trans);
}



// ############################### GET USER INFO ###############################

function GetUserInfo($user)
{
  global $DB, $usersystem;

  // load guest usergroup at the end of this function unless this var turns true
  $userinfocreated = false;

  // usergroupids that were filled in the usersystem file, needs to be an array
  $usergroupids = is_array($user['usergroupids']) ? $user['usergroupids'] : array($user['usergroupids']);

  // if integrating with a forum, then the usergroupids in $user are from a forum database and not weencompany
  $usergroupidcolumn = $usersystem['name'] == 'weenCompany' ? 'usergroupid' : 'forumusergroupid';

  // start building empty array
  $userinfo                          = array();
  $userinfo['usergroupids']          = array();

  $userinfo['userid']                = $user['userid'];
  $userinfo['username']              = $user['username'];
  $userinfo['email']                 = $user['email'];
  $userinfo['loggedin']              = $user['loggedin'];
  $userinfo['sessionurl']            = $user['sessionurl'];

  $userinfo['adminaccess']           = 0;
  $userinfo['commentaccess']         = 0;
  $userinfo['offlinecategoryaccess'] = 0;

  $userinfo['categoryviewids']       = array();
  $userinfo['categorymenuids']       = array();
  $userinfo['moduleviewids']         = array();
  $userinfo['modulesubmitids']       = array();
  $userinfo['moduledownloadids']     = array();
  $userinfo['modulecommentids']      = array();
  $userinfo['moduleadminids']        = array();
  $userinfo['custommoduleviewids']   = array();
  $userinfo['custommoduleadminids']  = array();

  for($i = 0; $i < count($usergroupids); $i++)
  {
    if($usergroupids[$i] != 0 AND $usergroup = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "usergroups WHERE " . $usergroupidcolumn . " = " . $usergroupids[$i]))
    {
      $userinfocreated = true;

      $userinfo['usergroupids'][]        = $usergroup['usergroupid'];

      // overide only if new setting is 1, otherwise revert back to previous loop value or default setting of 0
      $userinfo['adminaccess']           = $usergroup['adminaccess']           ? $usergroup['adminaccess']           : $userinfo['adminaccess'];
      $userinfo['commentaccess']         = $usergroup['commentaccess']         ? $usergroup['commentaccess']         : $userinfo['commentaccess'];
      $userinfo['offlinecategoryaccess'] = $usergroup['offlinecategoryaccess'] ? $usergroup['offlinecategoryaccess'] : $userinfo['offlinecategoryaccess'];

      // the following are arrays, so add arrays together for multiple usergroup support
      $userinfo['categoryviewids']       = $usergroup['categoryviewids']       ? array_unique(array_merge($userinfo['categoryviewids'],      explode(',', $usergroup['categoryviewids'])))      : $userinfo['categoryviewids'];
      $userinfo['categorymenuids']       = $usergroup['categorymenuids']       ? array_unique(array_merge($userinfo['categorymenuids'],      explode(',', $usergroup['categorymenuids'])))      : $userinfo['categorymenuids'];
      $userinfo['moduleviewids']         = $usergroup['moduleviewids']         ? array_unique(array_merge($userinfo['moduleviewids'],        explode(',', $usergroup['moduleviewids'])))        : $userinfo['moduleviewids'];
      $userinfo['modulesubmitids']       = $usergroup['modulesubmitids']       ? array_unique(array_merge($userinfo['modulesubmitids'],      explode(',', $usergroup['modulesubmitids'])))      : $userinfo['modulesubmitids'];
      $userinfo['moduledownloadids']     = $usergroup['moduledownloadids']     ? array_unique(array_merge($userinfo['moduledownloadids'],    explode(',', $usergroup['moduledownloadids'])))    : $userinfo['moduledownloadids'];
      $userinfo['modulecommentids']      = $usergroup['modulecommentids']      ? array_unique(array_merge($userinfo['modulecommentids'],     explode(',', $usergroup['modulecommentids'])))     : $userinfo['modulecommentids'];
      $userinfo['moduleadminids']        = $usergroup['moduleadminids']        ? array_unique(array_merge($userinfo['moduleadminids'],       explode(',', $usergroup['moduleadminids'])))       : $userinfo['moduleadminids'];
      $userinfo['custommoduleviewids']   = $usergroup['custommoduleviewids']   ? array_unique(array_merge($userinfo['custommoduleviewids'],  explode(',', $usergroup['custommoduleviewids'])))  : $userinfo['custommoduleviewids'];
      $userinfo['custommoduleadminids']  = $usergroup['custommoduleadminids']  ? array_unique(array_merge($userinfo['custommoduleadminids'], explode(',', $usergroup['custommoduleadminids']))) : $userinfo['custommoduleadminids'];
    }
  }

  // if a usergroup hasn't been created (most likely because an admin hasn't associated a forum usergroup to the weencompany usergroup), then load a guest usergroup:
  if(!$userinfocreated)
  {
    $usergroup = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "usergroups WHERE usergroupid = 4");
    $userinfo['usergroupids'][]        = $usergroup['usergroupid'];

    // overide only if new setting is 1, otherwise revert back to previous loop value or default setting of 0
    $userinfo['adminaccess']           = $usergroup['adminaccess']           ? $usergroup['adminaccess']           : $userinfo['adminaccess'];
    $userinfo['commentaccess']         = $usergroup['commentaccess']         ? $usergroup['commentaccess']         : $userinfo['commentaccess'];
    $userinfo['offlinecategoryaccess'] = $usergroup['offlinecategoryaccess'] ? $usergroup['offlinecategoryaccess'] : $userinfo['offlinecategoryaccess'];

    // the following are arrays, so add arrays together for multiple usergroup support
    $userinfo['categoryviewids']       = $usergroup['categoryviewids']       ? array_unique(array_merge($userinfo['categoryviewids'],      explode(',', $usergroup['categoryviewids'])))      : $userinfo['categoryviewids'];
    $userinfo['categorymenuids']       = $usergroup['categorymenuids']       ? array_unique(array_merge($userinfo['categorymenuids'],      explode(',', $usergroup['categorymenuids'])))      : $userinfo['categorymenuids'];
    $userinfo['moduleviewids']         = $usergroup['moduleviewids']         ? array_unique(array_merge($userinfo['moduleviewids'],        explode(',', $usergroup['moduleviewids'])))        : $userinfo['moduleviewids'];
    $userinfo['modulesubmitids']       = $usergroup['modulesubmitids']       ? array_unique(array_merge($userinfo['modulesubmitids'],      explode(',', $usergroup['modulesubmitids'])))      : $userinfo['modulesubmitids'];
    $userinfo['moduledownloadids']     = $usergroup['moduledownloadids']     ? array_unique(array_merge($userinfo['moduledownloadids'],    explode(',', $usergroup['moduledownloadids'])))    : $userinfo['moduledownloadids'];
    $userinfo['modulecommentids']      = $usergroup['modulecommentids']      ? array_unique(array_merge($userinfo['modulecommentids'],     explode(',', $usergroup['modulecommentids'])))     : $userinfo['modulecommentids'];
    $userinfo['moduleadminids']        = $usergroup['moduleadminids']        ? array_unique(array_merge($userinfo['moduleadminids'],       explode(',', $usergroup['moduleadminids'])))       : $userinfo['moduleadminids'];
    $userinfo['custommoduleviewids']   = $usergroup['custommoduleviewids']   ? array_unique(array_merge($userinfo['custommoduleviewids'],  explode(',', $usergroup['custommoduleviewids'])))  : $userinfo['custommoduleviewids'];
    $userinfo['custommoduleadminids']  = $usergroup['custommoduleadminids']  ? array_unique(array_merge($userinfo['custommoduleadminids'], explode(',', $usergroup['custommoduleadminids']))) : $userinfo['custommoduleadminids'];
  }

  return $userinfo;
}



// ############################### DISPLAY DATE ################################

function DisplayDate($gmepoch, $dateformat = '')
{
  global $sdlanguage;

  // check if user has format, timezone, and dst set
  // if not then use the settings from the weencompany admin panel

  // for now weencompany doesn't check user info, so lets just grab the admin settings

  if(defined('IN_ADMIN'))
  {
    global $DB;

    if(!strlen($dateformat))
    {
      $getdateformat = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'dateformat'");
      $dateformat = $getdateformat['value'];
    }

    $gettimezoneoffset = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'timezoneoffset'");
    $getdaylightsavings = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'daylightsavings'");


    $timezoneoffset  = $gettimezoneoffset['value'];
    $daylightsavings = $getdaylightsavings['value'];
  }
  else
  {
    global $mainsettings;

    if(!strlen($dateformat))
    {
      $dateformat = $mainsettings['dateformat'];
    }

    $timezoneoffset = $mainsettings['timezoneoffset'];
    $daylightsavings = $mainsettings['daylightsavings'];
  }

  // automatic detection (not yet built in)
  // $dst = date('I', $gmepoch) * 3600;

  if($daylightsavings == 1)
  {
    $dst = $daylightsavings == 1 ? 3600 : 0;
  }

  // return a date if a date exists
  return $gmepoch ?  strtr(@gmdate($dateformat, $gmepoch + (3600 * $timezoneoffset + $dst)), $sdlanguage) : '';
}

// ########################## DISPLAY READABLE FILESIZE ############################

function DisplayReadableFilesize($filesize)
{
  global $language;

  $kb = 1024;         // Kilobyte
  $mb = 1048576;      // Megabyte

  if($filesize < $kb)
  {
    $size = $filesize . ' B';
  }
  else if($filesize < $mb)
  {
    $size = round($filesize/$kb,2) . ' KB';
  }
  else
  {
    $size = round($filesize/$mb,2) . ' MB';
  }

  return (isset($size) AND $size != ' B') ? $size : '';
}

// #################################### IIF ####################################

function iif($expression, $returntrue, $returnfalse = '')
{
  if($expression == 0)
  {
    return $returnfalse;
  }
  else
  {
    return $returntrue;
  }
}



// ############################### GET LANGUAGE ################################

function GetLanguage($moduleid)
{
  global $DB;

  $getlanguage = $DB->query("SELECT * FROM " . TABLE_PREFIX . "phrases WHERE moduleid = '$moduleid'");

  while($languagearray = $DB->fetch_array($getlanguage))
  {
    // start building the font tags
    $fontstart = '<font style="';
    $fontend   = '</font>';

    if($languagearray['font'])
      $fontstart .= 'font-family: ' . $languagearray['font']  . '; ';

    if($languagearray['size'])
      $fontstart .= 'font-size: '   . $languagearray['size']  . 'px; ';

    if($languagearray['color'])
      $fontstart .= 'color: '       . $languagearray['color'] . '; ';

    if($languagearray['bold'])
      $fontstart .= 'font-weight: bold; ';

    if($languagearray['italic'])
      $fontstart .= 'font-style: italic; ';

    if($languagearray['underline'])
      $fontstart .= 'text-decoration: underline; ';

    // close the first font tag
    $fontstart .= '">';

    // don't add a style if there isn't any
    // this is to prevent conflict with existing css
    if($fontstart == '<font style="">')
    {
      $fontstart = '';
      $fontend   = '';
    }

    if($languagearray['customphrase']){
		if(trim($languagearray['customphrase']) AND trim($languagearray['customphrase']) != '&nbsp'){
			  $language[$languagearray['varname']] = $fontstart . $languagearray['customphrase']  . $fontend;
		}else{
			  $language[$languagearray['varname']] = '';
		}
    }else{
      $language[$languagearray['varname']] = $fontstart . $languagearray['defaultphrase'] . $fontend;
	}
  }

  return $language;
}



// ################################ ADD SMILIES ################################

function AddSmilies($phrase)
{
  global $smilieimagetexts, $smilieimagepaths;

  return $newphrase = @preg_replace($smilieimagetexts, $smilieimagepaths, $phrase);
}



// ############################### LOAD SMILIES ################################

function LoadSmilies($usersystem)
{
  global $DB, $weenurl, $dbname, $smilieimagetexts, $smilieimagepaths;

  // select smilie system
  $smiliesystem = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'smiliesystem'");

  if($smiliesystem['value'] == 'weenCompany')
  {
    $getsmilies = $DB->query("SELECT * FROM " . TABLE_PREFIX . "smilies");
    $smiliepath = 'images/smilies/';
  }
  else
  {
    // using forum smilies
    if($dbname != $usersystem['dbname'])
    {
      $DB->select_db($usersystem['dbname']);
    }

    if($usersystem['name'] == 'Discuz5')
    {
      $getsmilies = $DB->query("SELECT code AS text, url AS image FROM " . $usersystem['tblprefix'] . "smilies");
      $smiliepath = $usersystem['folderpath'] . 'images/smilies/';
    }
    else if($usersystem['name'] == 'vBulletin 2')
    {
      $getsmilies = $DB->query("SELECT smilietext AS text, smiliepath AS image FROM " . $usersystem['tblprefix'] . "smilie");
      $smiliepath = $usersystem['folderpath'];
    }
    else if($usersystem['name'] == 'vBulletin 3')
    {
      $getsmilies = $DB->query("SELECT smilietext AS text, smiliepath AS image FROM " . $usersystem['tblprefix'] . "smilie");
      $smiliepath = $usersystem['folderpath'];
    }
    else if($usersystem['name'] == 'phpBB2')
    {
      $getsmilies = $DB->query("SELECT code AS text, smile_url AS image FROM " . $usersystem['tblprefix'] . "smilies");
      $smiliepath = $usersystem['folderpath'] . 'images/smiles/';
    }
    else if($usersystem['name'] == 'Invision Power Board 2')
    {
      $getsmilies = $DB->query("SELECT typed AS text, image FROM " . $usersystem['tblprefix'] . "emoticons");
      $smiliepath = $usersystem['folderpath'] . 'style_emoticons/default/';
    }
    else if($usersystem['name'] == 'Simple Machines Forum 1')
    {
      $getsmilies = $DB->query("SELECT code AS text, filename AS image FROM " . $usersystem['tblprefix'] . "smileys");
      $smiliepath = $usersystem['folderpath'] . 'Smileys/default/';
    }

    // switch back to weencompany database
    if($dbname != $usersystem['dbname'])
    {
      $DB->select_db($dbname);
    }
  }

  while($smilie = $DB->fetch_array($getsmilies))
  {
    $smilieimagetexts[] = '/' . preg_quote($smilie['text']) . '/';
    $smilieimagepaths[] = '<img src="' . $weenurl . $smiliepath . $smilie['image'] . '" alt="" border="0" />';
  }
}



function CreateThumbnail($imagefile, $thumbnailfile, $maxwidth, $maxheight, $squareoff)
{
  // check if gd is installed
  if(!function_exists('imagetypes'))
  {
    $errormsg = 'The GD image library needs to be installed to create thumbnails, please contact your server administrator.';
  }
  else
  {
    // gd is installed, get image information
    $imageinfo = getImageSize($imagefile) ;

    $imagewidth  = $imageinfo[0];
    $imageheight = $imageinfo[1];

    switch($imageinfo['mime'])
    {
      case 'image/gif':
        if(imagetypes() & IMG_GIF)
        {
          $source_handle = imageCreateFromGIF($imagefile);
          $function_to_write = 'ImageGif';
        }
        else
          $errormsg = 'GIF images are not supported<br />';
      break;

      case 'image/jpeg':
        if(imagetypes() & IMG_JPG)
        {
          $source_handle = imageCreateFromJPEG($imagefile);
          $function_to_write = 'ImageJpeg';
        }
        else
          $errormsg = 'JPEG images are not supported<br />';
      break;

      case 'image/png':
        if(imagetypes() & IMG_PNG)
        {
          $source_handle = imageCreateFromPNG($imagefile);
          $function_to_write = 'ImagePng';
        }
        else
          $errormsg = 'PNG images are not supported<br />';
      break;

      case 'image/wbmp':
        if(imagetypes() & IMG_WBMP)
        {
          $source_handle = imageCreateFromWBMP($imagefile) ;
          $function_to_write = 'ImageWbmp';
        }
        else
          $errormsg = 'WBMP images are not supported<br />';
      break;

      default:
        $errormsg = $image_info['mime'].' images are not supported<br />';
      break;
    }

    if(!isset($errormsg))
    {
      if(!is_numeric($maxwidth))
        $maxwidth = 100;

      if(!is_numeric($maxheight))
        $maxheight = 100;

      // If the size suggested is larger than the current image
      // make the new size the same as the current one
      if($maxwidth > $imagewidth)
      {
              $maxwidth = $imagewidth;
      }

      if($maxheight > $imageheight)
      {
              $maxheight = $imageheight;
      }

      if($squareoff)
      {
        // Figure out which is the shorter side and resize the thumbs to that size
        if($imagewidth > $imageheight)
        {
          $thumbnail_width = $thumbnail_height = $maxwidth;
        }
        else
        {
          $thumbnail_width = $thumbnail_height = $maxheight;
        }
      }
      else
      {
        if($imagewidth > $imageheight)
        {
          $thumbnail_width = $maxwidth;
          $thumbnail_height = (int)($maxwidth * $imageheight / $imagewidth);
        }
        else
        {
          $thumbnail_height = $maxheight;
          $thumbnail_width = (int)($maxheight * $imagewidth / $imageheight);
        }
      }

      // Build Thumbnail with GD2
      if(function_exists('ImageCreateTrueColor'))
      {
        // create a blank image for the thumbnail
        $destination_handle = ImageCreateTrueColor($thumbnail_width, $thumbnail_height);

        // resize it
        ImageCopyResampled($destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $imagewidth, $imageheight);
      }
      else if(function_exists('imagecreate'))
      {
        // Build Thumbnail with GD1

        // create a blank image for the thumbnail
        $destination_handle = ImageCreate($thumbnail_width, $thumbnail_height );

        // resize it
        ImageCopyResized($destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $imagewidth, $imageheight);
      }
      else
      {
        $errormsg = 'The GD image library needs to be installed to create thumbnails, please contact your server administrator.';
      }

      if(!isset($errormsg))
      {
        // Let's save the thumbnail
        $function_to_write($destination_handle, $thumbnailfile);
        ImageDestroy($destination_handle);
      }
    }
  }

  return isset($errormsg) ? $errormsg : NULL;
}

// ########################## CREATE A GUID #############################

function CreateGuid()
{
   if (function_exists('com_create_guid'))
   {
     $uuid = com_create_guid();
         $uuid = str_replace('{', '', $uuid);
     $uuid = str_replace('}', '', $uuid);
         return $uuid;
   }
   else
   {
       mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
       $charid = strtoupper(md5(uniqid(rand(), true)));
       $hyphen = chr(45);// "-"
       $uuid = substr($charid, 0, 8).$hyphen
               .substr($charid, 8, 4).$hyphen
               .substr($charid,12, 4).$hyphen
               .substr($charid,16, 4).$hyphen
               .substr($charid,20,12);
       return $uuid;
   }
}

// ############################# CALCULATE THE EXECUTION TIME  ##############################

function ExecutionTime()
{
  global $time_start;

  $time_end = microtime(true);
  return round(($time_end - $time_start), 3);
}

// ############################# NEW FUNCTIONS  ##############################

function sqlsafefilter( $source )
{
	$entities_match		= array(',',';','$','!','@','#','%','^','&','*','_','(',')','+','{','}','|',':','"','<','>','?','[',']','\\',"'",'.','/','*','+','~','`','=');
	return str_replace($entities_match, '', trim($source));
}


function isEmail($email)
{
	return preg_match("/^[a-z0-9]+[.a-z0-9_-]*@[a-z0-9]+[.a-z0-9_-]*\.[a-z0-9]+$/i", $email);
}


function isName($name)
{
	$entities_match		= array(',',';','$','!','@','#','%','^','&','*','_','(',')','+','{','}','|',':','"','<','>','?','[',']','\\',"'",'.','/','*','+','~','`','=');
	for ($i = 0; $i<count($entities_match); $i++) {
	     if(strpos($name, $entities_match[$i])){
               return false;
		 }
	}
   return true;
}

function isPass($pass)
{
   return preg_match("/^[[:alnum:]]+$/", $pass);
}

function passwdGen($length = 8)
{
	$str = 'abcdefghijkmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	for ($i = 0, $passwd = ''; $i < $length; $i++)
		$passwd .= substr($str, mt_rand(0, strlen($str) - 1), 1);
	return $passwd;
}

?>