Location: PHPKode > projects > Yupi cms > yupi-cms/include/functions.php
<?php
/**
 * Gets time as float
*/
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
/**
 * add prefix to table base name
*/
function get_table($name)
{
    global $DB_PREFIX; # this is table prefix not db prefix - wrong variable name
    return $DB_PREFIX . $name;
}

/**
 * Gets user ip
 */
function getUserIp()
{
    $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;
}


/**
 * Check if value contains any value in the list
 */
function listMatch($value, $list)
{
    $value = strtolower($value);
    #remove new line from string
    $list = str_replace("\n", " ", $list);
    $list = split(",", $list);

    foreach ($list as $val)
    {
        $val = trim(strtolower($val));
        if ($val == "")
            continue;
        $pos = strpos($value, $val);
        if ($pos !== false)
        {
            return false;
        }
    }
    return true;
}
/**
 * Splits text by space  and returns true if len(word) > len 
 */
function testWordLength($text, $len)
{
    $list = split(' ', $text);
    foreach ($list as $val)
    {
        if (strlen($val) > $len)
            return true;
    }
    return false;
}


/**
 * Retrives link to module from base url
 */
function get_base_url()
{
    global $Confing;
    $arr = func_get_args();

    if (is_array($arr[0]))
    {
        $args = $arr[0];
    }
    else
    {
        $args = func_get_args();
    }

    $url = "";

    $n = count($args);
    for ($i = 0; $i < $n; $i++)
    {
        if ($args[$i] != "")
        {
            $url .= "/" . $args[$i];
        }
    }
    $admin = "";
    $index = "index.php";
    if ($Confing->RemoveIndex)
    {
        $url = controler_url($admin . $url);
    }
    else
    {
        $url = controler_url($index . $admin . $url);
    }
    return strtolower($url);
}

/**
 * Retrives url from base url adding "admin" to url path for admin modules 
 */
function get_url()
{
    global $Confing;
    $arr = func_get_args();

    if (is_array($arr[0]))
    {
        $args = $arr[0];
    }
    else
    {
        $args = func_get_args();
    }

    $url = "";

    $n = count($args);
    for ($i = 0; $i < $n; $i++)
    {
        if ($args[$i] != "")
        {
            $url .= "/" . $args[$i];
        }
    }
    $admin = "";
    $index = "index.php/";
    if ($Confing->Admin)
    {
        $admin = "/admin";
    }
    if ($Confing->RemoveIndex)
    {
        $url = controler_url($admin . $url);
    }
    else
    {
        $url = controler_url($index . $admin . $url);
    }

    return $url;
}

/**
 * Redirect to url , pass parameters as "controler", ["action", "param1", "param2"....]
 */
function redirect()
{
    $url = get_url(func_get_args());
    header("Location:$url");
    exit;
}
/**
 * Redirect to fully specified url (with http://...)
 */
function redirect_to($url)
{
    header("Location:$url");
    exit;
}

/**
 * Trim text to specified size and adds tree dots
 */
function trimToSize($str, $size = 100)
{
    if (strlen($str) < $size)
    {
        return $str;
    }
    else
    {
        return substr($str, 0, $size) . "...";
    }
}

/**
 * Write debug info to debug array
 */
function Debug($str)
{
    $page = Yc_Page::getInstance();
    $page->Debug[] = $str;
}

/**
 * Saves panel data to databse
 */

function SavePanelData($id, StdClass$data)
{
    $f['data'] = ObjectToStr($data);

    $id = (int)$id;
    Update(SC_TABLE_PANELS, $f, "id=$id");
}

/**
 * Reads panel data from database
 */
function GetPanelData($id)
{
    $id = (int)$id;
    $data = SelectValue('data', SC_TABLE_PANELS, "id=$id");
    return StrToObject($data);
}

/**
 * Saves theme settings array to yaml file 
*/

function SaveThemeData($theme, $array)
{
   $file = php_file("theme/$theme/settings.yml");
   $data = Spyc::YAMLDump($array);
   file_put_contents($file, $data);
}

/**
 * Load theme data from yaml file into array
 */
function LoadThemeData($theme)
{
   $file = php_file("theme/$theme/settings.yml");
   if (!file_exists($file))
   {
      return null;
   }
   return Spyc::YAMLLoad($file);
}

/**
 * Gets panels html by place
 */
function GetPanelsHtml($place)
{
    Panels::LoadPanels($place);

    global $PANELS;

    $arr = &$PANELS[$place];

    $html = "";
    if (is_array($arr))
    {
        $level = 0;
        $close = 0;
        $n = sizeof($arr);
        for ($i = 0; $i < $n; $i++)
        {
            $val = $arr[$i];
            $name = $val['info']['name'];
            $width = $val['info']['width'];
            $inline = $val['info']['inline'];
            $att = "";
            if ($width != "")
                $att = " width='$width'";

            if (($inline == 1) and ($i < $n - 1))
            {
                $level++;
                $close = 1;
            }
            else
            {
                if ($level > 0)
                    $close = 2;
                $level = 0;
            }
            $format = trim($val['info']['format']);
            if ($format != "")
            {
                $val['html'] = str_replace("{html}", $val['html'], $format);
            }
            /**/
            if ($level == 1)
            {
                $out = "<table cellpading='0' cellspacing='0' width='100%' valign=top><tr><td{$att}>" .
                    $val['html'] . "</td>";
            }
            if ($level > 1)
            {
                $out = "<td{$att} valign='top'>" . $val['html'] . "</td>";
            }

            if (($level == 0) and ($close == 2))
            {

                $out = "<td{$att} valign='top'>" . $val['html'] . "</td></tr></table>";
            }
            else
                if ($level == 0)
                {
                    $out = $val['html'];
                }
            /**/

            $html .= $out;

        }
    }
    return $html;
}

/**
 * Converts object to string using serialize function
 */
function ObjectToStr($obj)
{
    return serialize($obj);
}

/**
 * Restores object from string 
 */
function StrToObject($str)
{
    $obj = @unserialize($str);
    return $obj;
}

/**
 * Checks is value is checked
 */
function IsChecked($value)
{
    if ($value == 'on')
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

/**
 * Add sql slashes to value or array 
 */
function SqlSlashes($var)
{
    if (is_array($var))
    {
        foreach ($var as $key => $val)
        {
            $x[$key] = SqlEscapeString($val);
        }
        return $x;
    }
    else
    {
        $var = SqlEscapeString($var);
        return $var;
    }
}

/**
 * Returns current url
 */
function GetCurrentUrl()
{
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on")
    {
        $pageURL .= "s";
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80")
    {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    }
    else
    {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}


/**
 * Not used  any more - to do:check source and remove usage of lang
 */
function Lang($key)
{
    return $key;
}

/**
 * Not used any more - to do: check source and remove 
 */
function IncludeLanguage($module)
{
    global $LOCALE;
    global $LANG;

    $LngFile = SC_ROOT_PATH . "/lang/$module/{$LANG}.php";
    if (file_exists($LngFile))
    {
        include $LngFile;
    }
    else
    {
        $LngFile = SC_ROOT_PATH . "/lang/$module/language.php";
        if (file_exists($LngFile))
        {
            include $LngFile;
        }
    }
}

/**
 * Retrives list of parents for specifed ID and TABLE , table must contain ( id and parent fieldnames )
 */
function GetParents($id, $table = SC_TABLE_MENU)
{
    if ($id < 1)
        $id = 0;

    $sql = 'Select * From ' . $table . " Where ID = $id";
    $row = SqlGetArray($sql);

    $item[] = $row;

    while ($row != false)
    {
        $id = (int)$row['parent'];
        $sql = 'Select * From ' . $table . " Where ID = $id";
        $row = SqlGetArray($sql);
        $item[] = $row;
    }
    return $item;
}

/**
 * this function replaces tags in menu link according global variable $MENU_TAGS
 */
function ReplaceMenuTags($link)
{
    global $MENU_TAGS;

    if (is_array($MENU_TAGS))
    {
        foreach ($MENU_TAGS as $key => $value)
        {
            $link = str_replace("{" . $key . "}", $value, $link);
        }
    }
    return $link;
}

/**
 * connects $path and $file checking for backslash
 */
function BuildPath($path, $file)
{
    $last = substr($path, -1);

    if (($last == '\\') || ($last == '/'))
    {
        $path = $path . $file;
    }
    else
    {
        $path = $path . '/' . $file;
    }
    return $path;
}

/**
 * Executes Sql using current database and returns array
 */
function SqlToArray($sql)
{
    $r = dbQuery($sql);
    $rs = CreateRecordset($r);
    while ($row = $rs->Next())
    {
        $rows[] = $row;
    }
    return $rows;
}

/**
 * Retrives value from $_GET or $_POST array or returns $def value if value not set
 * To do: remove $_GET 
 */
function GetVar($name, $def = "")
{
    if (isset($_GET[$name]))
    {
        return $_GET[$name];
    }
    else
        if (isset($_POST[$name]))
        {
            return $_POST[$name];
        }
        else
        {
            return $def;
        }
}

/**
 * Retrives integer value from $_POST or $_GET
 */
function GetInt($name, $def = "")
{
    $var = GetVar($name, $def);
    return (int)$var;
}

/**
 * Retrives $true part if $cond if true 
 */
function GetOne($cond, $true, $false)
{
    if ($cond)
    {
        return $true;
    }
    else
    {
        return $false;
    }
}


/**
 * Checks if value is empty
 */
function IsEmpty($str)
{
    if (trim($str) == '')
    {
        return true;
    }
    else
    {
        return false;
    }
}

function FormatDate($int, $format = '')
{
    if ($format == '')
        $format = 'd.m.y';
    return date($format, $int);
}

function GetDateInt($value)
{
    list($d, $m, $y) = split("/", $value);

    if (trim($d) == '')
        return null;
    if (trim($m) == '')
        return null;
    if (trim($y) == '')
        return null;

    $value = mktime(0, 0, 0, $m, $d, $y);
    return $value;
}

function SqlMaxValue($table, $field, $where = "")
{
    if ($where != "")
        $where = " Where $where";
    $sql = "SELECT max($field) As max_value FROM $table $where";
    return SqlGetValue($sql);
}

function SqlGetValue($sql)
{
    $r = dbQuery($sql);
    $rs = new Recordset($r);
    $val = $rs->Next();
    $val = $val[0];
    return $val;
}
function SqlGetArray($sql)
{
    $r = dbQuery($sql);
    $rs = new Recordset($r);
    $val = $rs->Next();
    return $val;
}

function SqlRowCount($table, $where = "")
{
    if ($where != "")
        $where = " WHERE $where";
    $sql = "Select Count(*) From $table $where";
    return SqlGetValue($sql);
}

function BitArrayToInt($boolArray)
{
    $val = 0;
    if (is_array($boolArray))
    {
        for ($i = 0; $i < sizeof($boolArray); $i++)
        {
            $k = pow(2, $i);
            if (isset($boolArray[$i]))
            {
                if (($boolArray[$i] == "on") or ($boolArray[$i] == 1) or ($boolArray[$i] == true))
                {
                    $val |= $k;
                }
            }
        }
        return $val;
    }
    else
    {
        return 0;
    }
}

function IsBitSet($value, $pos)
{
    $k = pow(2, $pos);
    if (($k & $value) == $k)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function MakeInsertParams($arr = null)
{
    $params = array();

    global $_POST;


    if (is_null($arr))
    {
        $arr = $_POST;
    }
    /*unset($arr[page]);*/

    if (!is_array($arr))
        return "";

    foreach ($arr as $key => $value)
    {
        if (substr($key, 0, 1) == "f")
        {
            $k = substr($key, 1);
            $params[$k] = $value;
        }
    }
    return $params;
}
//make update from array
function MakeUpdate($tabela, $arr, $where)
{
    $update = "";
    foreach ($arr as $key => $value)
    {
        $update .= "$key = '" . SqlEscapeString($value) . "' , ";
    }
    $update = substr($update, 0, -2);
    $update = "UPDATE $tabela SET $update WHERE $where";
    return $update;
}

//make insert from array
function MakeInsert($tabela, $arr)
{
    $fields = "";
    $values = "";

    foreach ($arr as $key => $value)
    {
        $fields .= $key . ",";
        $values .= "'" . SqlEscapeString($value) . "',";
    }

    $fields = substr($fields, 0, -1);
    $values = substr($values, 0, -1);
    return "INSERT INTO $tabela ($fields) VALUES ($values)";
}


/* Send mail */
function SendMail($from, $to, $subject, $body, $na)
{
    $headers = "MIME-Version: 1.0\n";
    $headers .= "Content-type: text/html; charset=windows-1250\n";
    $headers .= "From:<$from>\n";

    $result = mail($to, $subject, $body, $headers);
    if ($result)
        return true;
    else
        return false;
}
/**
 *Returns a simple list of direcory names
 */
function GetDirList(&$dirList, $directory, $recursive = false, $dirOnly = false)
{
    if (!is_array($dirList))
        $dirList = array();
    //$directory  = realpath($directory);
    $handler = opendir($directory);
    while ($file = readdir($handler))
    {
        // if $file isn't this directory or its parent,
        // add it to the results array
        if (($file != '.') && ($file != '..'))
        {
            $new_dir = BuildPath($directory, $file);

            if ($dirOnly == true)
            {
                if (is_dir($new_dir))
                {
                    $dirList[] = $new_dir;
                }
            }
            else
            {
                $dirList[] = $new_dir;
            }
            if ($recursive)
            {
                if (is_dir($new_dir))
                {
                    GetDirList($dirList, $new_dir, $recursive, $dirOnly);
                }
            }
        }
    }
    closedir($handler);
}

/**
 *Returns a simple list of file names
 */
function GetFileList(&$dirList, $directory, $recursive = false)
{
    if (!is_array($dirList))
        $dirList = array();
    $handler = opendir($directory);
    while ($file = readdir($handler))
    {
        // if $file isn't this directory or its parent,
        // add it to the results array
        if (($file != '.') && ($file != '..'))
        {
            $new_dir = $directory . '\\' . $file;

            if (is_file($new_dir))
            {
                $dirList[] = $new_dir;
            }
            #add files from subfolders
            if ($recursive)
            {
                if (is_dir($new_dir))
                {
                    GetDirList($dirList, $new_dir, $recursive, $dirOnly);
                }
            }
        }
    }
    closedir($handler);
}

?>
Return current item: Yupi cms