###
###
#
# GETFUNCTIONSHASH() is used for checking whether this file has been played properly in DatabaseUpdate.php
#
DROP FUNCTION IF EXISTS GETFUNCTIONSHASH;
CREATE FUNCTION GETFUNCTIONSHASH()
    RETURNS TEXT
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    RETURN '%%FUNCTIONSHASH%%';
END;



###
#
# QMORE(input, maxlen)
# inserts a span into `input` after `maxlen` number of characters and returns it.
#
DROP FUNCTION IF EXISTS QMORE;
CREATE FUNCTION QMORE(input TEXT, maxlen INT)
    RETURNS TEXT
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    IF maxlen < 1 THEN
        SET maxlen = 1;
    END IF;
    IF CHAR_LENGTH(input) > maxlen THEN
        SET output = CONCAT(INSERT(input, maxlen, 0, '<span class="qfq-more-text">'), '</span>');
    ELSE
        SET output = input;
    END IF;
    RETURN output;
END;


###
#
# QBAR(input)
# replaces '|' in `input` with '\|'
#
DROP FUNCTION IF EXISTS QBAR;
CREATE FUNCTION QBAR(input TEXT)
    RETURNS TEXT
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output = REPLACE(input, '|', '\\|');
    RETURN output;
END;

###
#
# QCC(input)
# replaces ':' (colon) and ',' (coma)  in `input` with '\:' and '\,'
#
DROP FUNCTION IF EXISTS QCC;
CREATE FUNCTION QCC(input TEXT)
    RETURNS TEXT
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output = REPLACE(REPLACE(input, ':', '\\:'), ',', '\\,');
    RETURN output;
END;

###
#
# QNL2BR(input)
# replaces '|' in `input` with '\|'
#
DROP FUNCTION IF EXISTS QNL2BR;
CREATE FUNCTION QNL2BR(input TEXT)
    RETURNS TEXT
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output = REPLACE(REPLACE(input, CHAR(13), ''), CHAR(10), '<br>');
    RETURN output;
END;

###
#
# QNBSP(input)
# replaces ' ' in `input` with '&nbsp'
#
DROP FUNCTION IF EXISTS QNBSP;
CREATE FUNCTION QNBSP(input TEXT)
    RETURNS TEXT
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output = REPLACE(input, ' ', '&nbsp;');
    RETURN output;
END;

###
#
# QIFEMPTY(input, token)
# If 'input' is empty|0|0000-00-00|0000-00-00 00:00:00, replace by 'token'
#
DROP FUNCTION IF EXISTS QIFEMPTY;
CREATE FUNCTION QIFEMPTY(input TEXT, token TEXT)
    RETURNS TEXT
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output =
            IF(ISNULL(input) OR input = '' OR input = '0' OR input = '0000-00-00' OR input = '0000-00-00 00:00:00',
               token,
               input);
    RETURN output;
END;

###
#
# strip_tags(input) - copied from https://stackoverflow.com/questions/2627940/remove-html-tags-from-record
#
DROP FUNCTION IF EXISTS strip_tags;
CREATE FUNCTION `strip_tags`(str TEXT)
    RETURNS TEXT
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE start, end INT DEFAULT 1;
    LOOP
        SET start = LOCATE("<", str, start);
        IF (!start) THEN RETURN str; END IF;
        SET end = LOCATE(">", str, start);
        IF (!end) THEN SET end = start; END IF;
        SET str = INSERT(str, start, end - start + 1, '');
    END LOOP;
END;

###
#
# QDATE_FORMAT(timestamp)
#
DROP FUNCTION IF EXISTS QDATE_FORMAT;
CREATE FUNCTION `QDATE_FORMAT`(ts DATETIME)
    RETURNS TEXT
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output = IF(ts = 0, '-', DATE_FORMAT(ts, "%d.%m.%Y %H:%i"));
    RETURN output;
END;

###
#
# QSLUGIFY(string)
#

/*
The MIT License (MIT)
Copyright (c) 2014 jose reis<jose.reis@artbit.pt>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Credits:
- http://stackoverflow.com/questions/5409831/mysql-stored-function-to-create-a-slug
*/

DROP FUNCTION IF EXISTS `QSLUGIFY`;
CREATE FUNCTION `QSLUGIFY`(dirty_string varchar(255)) RETURNS varchar(255) CHARSET utf8
    DETERMINISTIC
BEGIN
    DECLARE x, y , z , k INT;
    DECLARE temp_string, new_string, accents, noAccents VARCHAR(255);
    DECLARE is_allowed BOOL;
    DECLARE c, check_char VARCHAR(1);

    -- IF NULL DO NOT PROCEED
    If dirty_string IS NULL Then
        return dirty_string;
    End If;

    set temp_string = LOWER(dirty_string);

    -- REPLACE ACCENTS
    -- WITH CAPS
    -- set accents = 'ŠšŽžÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝŸÞàáâãäåæçèéêëìíîïñòóôõöøùúûüýÿþƒ';
    -- set noAccents = 'SsZzAAAAAAACEEEEIIIINOOOOOOUUUUYYBaaaaaaaceeeeiiiinoooooouuuuyybf';
    -- ONLY SMALL CAPS
    set accents = 'šžàáâãäåæçèéêëìíîïñòóôõöøùúûüýÿþƒ';
    set noAccents = 'szaaaaaaaceeeeiiiinoooooouuuuyybf';
    set k = CHAR_LENGTH(accents);

    while k > 0
        do
            set temp_string = REPLACE(temp_string, SUBSTRING(accents, k, 1), SUBSTRING(noAccents, k, 1));
            set k = k - 1;
        end while;

    -- CONVERT & TO EMPTY SPACE
    Set temp_string = REPLACE(temp_string, '&', '');

    -- REPLACE ALL UNWANTED CHARS
    Select temp_string REGEXP ('[^a-z0-9\-]+') into x;
    If x = 1 then
        set z = 1;
        set k = CHAR_LENGTH(temp_string);
        While z <= k
            Do
                Set c = SUBSTRING(temp_string, z, 1);
                Set is_allowed = FALSE;
                If !((ascii(c) = 45) or (ascii(c) >= 48 and ascii(c) <= 57) or
                     (ascii(c) >= 97 and ascii(c) <= 122)) Then
                    Set temp_string = REPLACE(temp_string, c, '-');
                End If;
                set z = z + 1;
            End While;
    End If;

    Select temp_string REGEXP ("^-|-$|'") into x;
    If x = 1 Then
        Set temp_string = Replace(temp_string, "'", '');
        Set z = CHAR_LENGTH(temp_string);
        Set y = CHAR_LENGTH(temp_string);
        Dash_check:
        While z > 1
            Do
                If STRCMP(SUBSTRING(temp_string, -1, 1), '-') = 0 Then
                    Set temp_string = SUBSTRING(temp_string, 1, y - 1);
                    Set y = y - 1;
                Else
                    Leave Dash_check;
                End If;
                Set z = z - 1;
            End While;
    End If;

    Repeat
        Select temp_string REGEXP ("--") into x;
        If x = 1 Then
            Set temp_string = REPLACE(temp_string, "--", "-");
        End If;
    Until x <> 1 End Repeat;

    If LOCATE('-', temp_string) = 1 Then
        Set temp_string = SUBSTRING(temp_string, 2);
    End If;

    Return temp_string;
END;

###
# QENT_SQUOTE(text)
# Replaces single tick by html entity &apos;
#
DROP FUNCTION IF EXISTS `QENT_SQUOTE`;
CREATE FUNCTION `QENT_SQUOTE`(`input` TEXT) RETURNS text CHARSET utf8
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output = REPLACE(input, "'", '&apos;');
    RETURN output;
End;

###
# QENT_DQUOTE(text)
# Replaces double tick by html entity &quot;
#
DROP FUNCTION IF EXISTS `QENT_DQUOTE`;
CREATE FUNCTION `QENT_DQUOTE`(`input` TEXT) RETURNS text CHARSET utf8
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output = REPLACE(input, '"', '&quot;');
    RETURN output;
END;

###
# QESC_SQUOTE(text)
# Replaces double tick by html entity &quot;
#
DROP FUNCTION IF EXISTS `QESC_SQUOTE`;
CREATE FUNCTION `QESC_SQUOTE`(`input` TEXT) RETURNS text CHARSET utf8
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output = REPLACE(REPLACE(input, "'", "\\'"), "\\\\'", "\\'");
    RETURN output;
END;


###
# QESC_DQUOTE(text)
# Replaces double tick by html entity &quot;
#
DROP FUNCTION IF EXISTS `QESC_DQUOTE`;
CREATE FUNCTION `QESC_DQUOTE`(`input` TEXT) RETURNS text CHARSET utf8
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    DECLARE output TEXT;
    SET output = REPLACE(REPLACE(input, '"', '\\"'), '\\\\"', '\\"');
    RETURN output;
END;