Example #1
0
function aSpecialGetMenu($param)
{
    global $Permissions;
    $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_PAGES . "` WHERE ((`key`='" . $param . "') AND (`subversion` = 0))";
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
    $row = mysql_fetch_assoc($sql);
    $param = $row['id'];
    global $aTree;
    global $aOutTree;
    if (MENU_GEN or !file_exists(FILE_CACHE_TREE)) {
        if (!$Permissions->bIsAdmin()) {
            $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_PAGES . "` WHERE ((`key` != 'cms') AND (`subversion` = 0)) ORDER BY `order`";
        } else {
            $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_PAGES . "` WHERE (`subversion` = 0) ORDER BY `order`";
        }
        $sql = mysql_query($sql);
        if (false == $sql) {
            my_die();
        }
        $aTree = array();
        while ($row = mysql_fetch_assoc($sql)) {
            $row['title'] = str_replace(' ', ' ', $row['title']);
            $aTree[$row['id']] = $row;
        }
        $aOutTree = array();
        DendroId($param, array());
        safewrite(FILE_CACHE_TREE, serialize($aOutTree));
    } else {
        $aOutTree = unserialize(file_get_contents(FILE_CACHE_TREE));
    }
    return $aOutTree;
}
Example #2
0
function group_del($group_id)
{
    // Находим все подгруппы и рекурсивно удаляем
    $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_GROUPS . "` WHERE `parent` = " . $group_id;
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
    $aList = array();
    while ($row = mysql_fetch_assoc($sql)) {
        $aList[] = $row;
    }
    foreach ($aList as $v) {
        group_del($v['id']);
    }
    // Удаляем все продукты группы
    $sql = "DELETE FROM `" . DB_PREFIX . DB_TBL_PRODUCTS . "` WHERE `group` = " . $group_id;
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
    // Удаляем запись группы в базе данных
    $sql = "DELETE FROM `" . DB_PREFIX . DB_TBL_GROUPS . "` WHERE `id` = " . $group_id;
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
}
Example #3
0
 function DelPage($nPageId)
 {
     $sql = "DELETE FROM `" . DB_PREFIX . DB_TBL_CACHE . "` WHERE `page` = '{$nPageId}'";
     $sql = mysql_query($sql);
     if (false == $sql) {
         my_die();
     }
 }
Example #4
0
 function send($from, $to, $message, $title)
 {
     $sql = "INSERT INTO `" . DB_PREFIX . DB_TBL_MAILS . "` (`from_id`, `to_id`, `message`, `title`) VALUES (\n\t\t\t'" . mysql_escape_string($from) . "',\n\t\t\t'" . mysql_escape_string($to) . "',\n\t\t\t'" . mysql_escape_string($message) . "',\n\t\t\t'" . mysql_escape_string($title) . "'\n\t\t)";
     $sql = mysql_query($sql);
     if (false == $sql) {
         my_die();
     }
     return true;
 }
Example #5
0
function getPage($m)
{
    global $xmlrpcerruser;
    global $xmlrpcString;
    $file_uri = $m->getParam(0);
    $file_uri = $file_uri->scalarval();
    $aRequest = explode('/', $file_uri);
    // Processing
    $aProcess = array();
    $bFlag404 = false;
    $nParent = 0;
    foreach ($aRequest as $nLevel => $sKey) {
        $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_PAGES . "` \n\t\t\t\tWHERE ( (`parent`={$nParent}) AND (`key`='{$aRequest[$nLevel]}') AND (`subversion` = 0) )";
        $sql = mysql_query($sql);
        if (false == $sql) {
            my_die();
        }
        $sql = mysql_fetch_assoc($sql);
        if (false === $sql) {
            $bFlag404 = true;
            $nLevel--;
            break;
        } else {
            $nParent = $sql['id'];
            $aProcess[$sql['id']] = $sql;
        }
    }
    // Versioning
    $aProcessVersions = array();
    foreach ($aProcess as $k => $v) {
        if ($v['draft'] == 0) {
            $aProcessVersions[$k] = $v;
        } else {
            $aTree = array();
            getSubVersionsRecursive($k);
            foreach ($aTree as $kk => $vv) {
                if ($vv['draft'] == 0) {
                    $aProcessVersions[$kk] = $vv;
                    break;
                }
            }
        }
    }
    $aProcess = $aProcessVersions;
    // Set Last Id
    end($aProcess);
    $bFlagLastModule = false;
    $nLastId = key($aProcess);
    reset($aProcess);
    if ($bFlag404) {
        return new xmlrpcresp(0, $xmlrpcerruser, 'page not found');
    }
    $response = base64_encode(serialize($aProcess[$nLastId]));
    return new xmlrpcresp(new xmlrpcval($response), $xmlrpcString);
}
Example #6
0
function setOrder($param)
{
    $aGroup = getChildsGroup($param);
    foreach ($aGroup as $k => $v) {
        $sql = "UPDATE `" . DB_PREFIX . DB_TBL_GROUPS . "` SET `order` = '" . ($k + 1) . "' WHERE `id` = " . $v['id'];
        $sql = mysql_query($sql);
        if (false == $sql) {
            my_die();
        }
        setOrder($v['id']);
    }
}
Example #7
0
function StandartPreWrap($sText)
{
    $sResult = $sText;
    // Замена идентификаторов изображений на пути к ним
    $aMatches = array();
    $aReplaces = array();
    $nMatches = preg_match_all('/\\[(big|normal|min|link)(\\d*)\\]/', $sResult, $aMatches);
    if ($nMatches != 0) {
        for ($i = 0; $i < $nMatches; $i++) {
            // Префикс адреса
            $sPrefix = '';
            switch ($aMatches[1][$i]) {
                case 'big':
                    $sPrefix = IMG_BIG_ADDR;
                    break;
                case 'normal':
                    $sPrefix = IMG_NORMAL_ADDR;
                    break;
                case 'min':
                    $sPrefix = IMG_THUMBNAIL_ADDR;
                    break;
                case 'link':
                    $sPrefix = 'link';
                    break;
            }
            // Имя файла изображения
            $sql = "SELECT `file` FROM `" . DB_PREFIX . "img` WHERE `id` = " . $aMatches[2][$i];
            $sql = mysql_query($sql);
            if (false == $sql) {
                my_die();
            }
            $aImgFile = current(mysql_fetch_assoc($sql));
            if ('link' != $sPrefix) {
                $aReplaces[] = '<img src="' . $sPrefix . '/' . $aImgFile . '" />';
            } else {
                $aReplaces[] = '<a href="' . IMG_BIG_ADDR . '/' . $aImgFile . '" target="_blank"><img src="' . IMG_THUMBNAIL_ADDR . '/' . $aImgFile . '"  border="0" /></a>';
            }
        }
        $sResult = str_replace($aMatches[0], $aReplaces, $sResult);
    }
    // Замена идентификаторов файлов на ссылки на файлы
    $aMatches = array();
    $aReplaces = array();
    $nMatches = preg_match_all('/\\[(file=")([\\w_\\d\\.]*)"\\]/', $sResult, $aMatches);
    if ($nMatches != 0) {
        $sResult = str_replace($aMatches[0][0], '<img src="/img/file.gif">&nbsp;<a href="/files/' . $aMatches[2][0] . '">' . $aMatches[2][0] . '</a>', $sResult);
    }
    // Замена переводов строк на <br>
    if (false === strpos($sResult, '<table') && false === strpos($sResult, '<br')) {
        $sResult = trim(str_replace("\n", '<br />', $sResult));
    }
    return $sResult;
}
Example #8
0
 function _getAccounts()
 {
     $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_USERS . "`";
     $sql = mysql_query($sql);
     if (false == $sql) {
         my_die();
     }
     $this->aAccounts = array();
     while ($row = mysql_fetch_assoc($sql)) {
         $this->aAccounts[] = $row;
     }
 }
Example #9
0
 function create($message, $seg, $off, $user_id = false)
 {
     global $Permissions;
     if ($user_id === false) {
         $user_id = $Permissions->getLoggedUserId();
     }
     $sql = "INSERT INTO `" . DB_PREFIX . DB_TBL_WALLS . "` (`message`, `seg`, `off`, `user_id`) VALUES (\n\t\t\t'{$message}',\n\t\t\t'{$seg}',\n\t\t\t'{$off}',\n\t\t\t'{$user_id}'\n\t\t)";
     //		dbg($sql);
     $sql = mysql_query($sql);
     if (false == $sql) {
         my_die();
     }
     return true;
 }
Example #10
0
 function get()
 {
     global $Permissions;
     global $sRequest;
     $tpl = new KTemplate();
     $_s = file_get_contents(__FILE__);
     $_s = substr($_s, strpos($_s, '?' . '>') + 2);
     $tpl->loadTemplateContent($_s);
     $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_COMMENTS . "` WHERE `url`='" . $sRequest . "'";
     $sql = mysql_query($sql);
     if (false == $sql) {
         my_die();
     }
     $aList = array();
     while ($row = mysql_fetch_assoc($sql)) {
         $aList[] = $row;
     }
     //		dbg($aList);
     if (empty($aList)) {
         $tpl->assign('Comment', 'Нет комментариев');
     }
     foreach ($aList as $v) {
         $sql = "SELECT * FROM. `" . DB_PREFIX . DB_TBL_USERS . "` WHERE `id`=" . $v['user_id'];
         $sql = mysql_query($sql);
         if (false == $sql) {
             my_die();
         }
         $aUser = array();
         while ($row = mysql_fetch_assoc($sql)) {
             $aUser = $row;
         }
         //			dbg($aUser);
         $v = array_merge($v, $aUser);
         //			dbg($v);
         $tplComment = $tpl->fetchBlock('Comment');
         $tplComment->assign($v);
         $tpl->assign('Comment', $tplComment);
         $tplComment->reset();
     }
     if ($Permissions->bIsLogged()) {
         $tpl->assign('CommentForm', $tpl->fetchBlock('CommentForm'));
     } else {
         $tpl->assign('CommentForm', 'Войдите, чтобы оставить комментарий');
     }
     return $tpl->get();
 }
Example #11
0
function del_comment($id)
{
    $sql = 'SELECT `id` FROM `' . DB_PREFIX . DB_TBL_COMMENTS . '` WHERE `parent` = ' . $id;
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
    $aChilds = array();
    while ($row = mysql_fetch_assoc($sql)) {
        $aChilds[] = current($row);
    }
    foreach ($aChilds as $v) {
        del_comment($v);
    }
    $sql = "DELETE FROM `" . DB_PREFIX . DB_TBL_COMMENTS . "` WHERE `id` = " . $id;
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
}
Example #12
0
 /**
  * Выдать текущий item коллекции, а потом передвинуть указатель на значение
  * параметра (по умолчанию = 1). Можно задавать ноль (итератор не двигается).
  * Возвращает false в случае если старый итератор не указывает 
  * на item (итератор вышел за границы коллекции)
  */
 function each($cnt = 1)
 {
     // Принимаем необязательный параметр, регулирующий шаг итератора
     if ($cnt < 0) {
         my_die('cCollection::each - Wrong iterator');
     }
     // Если не нашли элемент - пытаемся подгрузить из базы
     if (!isset($this->aMemo[$this->iterator])) {
         if (empty($this->table)) {
             my_die('cCollection::each - Таble not found');
         }
         $sql .= $this->sql . "LIMIT  " . $this->iterator . ", " . $this->limit_size;
         //dbg($sql);
         global $uniter;
         $uniter = $this->iterator;
         global $Db;
         $aTmp = $Db->query($sql, 'global $uniter; $aList[$uniter] = $row; $uniter++;');
         // Правильно сливаем массивы (array_merge не подходит, потому что добавляет
         // элементы с числовыми ключами)
         foreach ($aTmp as $k => $v) {
             $this->aMemo[$k] = $v;
         }
         //dbg($sql, 'cCollection::each() - db loading');
     }
     // Если элемент не найден несмотря на то что мы пытались подгрузить - значит все
     // Если нашли элемент, то отдаем его и двигаем итератор
     if (!isset($this->aMemo[$this->iterator])) {
         end($this->aMemo);
         $this->iterator = key($this->aMemo);
         reset($this->aMemo);
         return false;
     } else {
         $result = $this->aMemo[$this->iterator];
         $this->iterator = $this->iterator + $cnt;
         return $result;
     }
 }
Example #13
0
 function validator_login($value)
 {
     // Не пустой
     $filled = $this->validator_filled($value);
     if (is_array($filled)) {
         return $filled;
     }
     // Только английские строчные буквы, цифры, тире и знак подчеркивания
     $s = 'qwertyuiopasdfghjklzxcvbnm1234567890_-';
     $a = array();
     for ($i = 0; $i < strlen($s); $i++) {
         $a[$s[$i]] = $s[$i];
     }
     for ($i = 0; $i < strlen($value); $i++) {
         if (!isset($a[$value[$i]])) {
             return array('Только английские строчные буквы, цифры, тире и знак подчеркивания!');
         }
     }
     // Незарегистрированный логин
     $sql = "SELECT `login` FROM `" . DB_PREFIX . DB_TBL_USERS . "`";
     $sql = mysql_query($sql);
     if (false == $sql) {
         my_die();
     }
     $aAccounts = array();
     while ($row = mysql_fetch_assoc($sql)) {
         $aAccounts[] = current($row);
     }
     //dbg($aAccounts);
     foreach ($aAccounts as $v) {
         if ($v == $value) {
             return array('Такой логин уже зарегистрирован!');
         }
     }
     return true;
 }
Example #14
0
<?php

// this gets us around Chrome's issues with AJAX requests from file://
header('Access-Control-Allow-Origin: *');
function my_die($msg)
{
    header("HTTP/1.1 500 Internal Server Error");
    die($msg);
}
if (isset($_POST) && isset($_POST['source'])) {
    if ($_POST['pw'] != 'coffee') {
        my_die("Invalid password.");
    } else {
        preg_match('/(?:class|interface)\\s+(\\w+)/', $_POST['source'], $matches) or my_die("Couldn't parse a class name");
        $classname = $matches[1];
        $fh = fopen("{$classname}.java", 'w') or my_die("Can't open '{$classname}.java' for writing");
        fwrite($fh, $_POST['source']);
        fclose($fh);
        $errors = shell_exec("javac {$classname}.java 2>&1");
        unlink("{$classname}.java");
        readfile("{$classname}.class") or my_die("Failed to compile class {$classname}:\n{$errors}");
        unlink("{$classname}.class");
    }
} else {
    echo "POST a 'source' java string to compile it.";
}
Example #15
0
function ExceptionHandler($errmess, $e)
{
    echo $errmess . ': ' . $e->getMessage();
    dbg($e->getTrace(), '<pre>' . my_exeption_trace($e) . '</pre>');
    my_die($e);
}
Example #16
0
 function updatePhoto($id, $aParam = array())
 {
     $set = '';
     if (!empty($aParam)) {
         foreach ($aParam as $key => $v) {
             $set .= "`" . $key . "`='" . mysql_escape_string($v) . "', ";
         }
         $set = substr($set, 0, -2);
     }
     if (!empty($set)) {
         $sql = "UPDATE `" . DB_PREFIX . DB_TBL_IMGS . "` SET \t\t\n\t\t" . $set . "\n\t\tWHERE `id`='" . mysql_escape_string($id) . "';";
         $sql = mysql_query($sql);
         if (false == $sql) {
             my_die();
         }
         return true;
     } else {
         return false;
     }
 }
function CACF_CreateFolderAuditDataAndWriteToCsv(&$db, &$CACFconstants, &$altiumUserNamesByGuid, &$altiumFoldersByGuid, &$altiumFolderUserParmValuesByGuid, &$altiumUserParmNames, &$altiumAclDataByObjectGuid)
{
    /* Retrieve necessary global constants. */
    $ofs = $CACFconstants["ofs"];
    $constNamingScheme = $CACFconstants["constNamingScheme"];
    $constAbsent = $CACFconstants["constAbsent"];
    $auditFoldersFileName = $CACFconstants["auditFoldersFileName"];
    /** Modify $altiumUserParmNames to add one FOLDER level special parameter string. **/
    /* WARNING:  Do not move this code block above the audit components operation located above here! */
    $altiumUserParmNames[$constNamingScheme] = 1;
    /* Re-sort all Altium user parameter names stored in the array, by array key. */
    $rc = ksort($altiumUserParmNames);
    if ($rc == FALSE) {
        my_die("ksort() failed!");
    }
    /** Open audit folders file for writing. **/
    $auditFoldersFile = my_fopen($auditFoldersFileName);
    /** Output column headers. **/
    $line = "";
    $line = $line . "FOLDERGUID" . $ofs . "DESCRIPTION" . $ofs . "FOLDERTYPE" . $ofs . "FOLDERPATH" . $ofs . "CREATEDBY" . $ofs . "CREATEDAT" . $ofs . "LASTMODIFIEDBY" . $ofs . "LASTMODIFIEDAT";
    /* Get a random array slice to know what fields exist. */
    $slice = array_slice($altiumAclDataByObjectGuid, 0, 1);
    //echo "slice is:\n";
    //print_r($slice);
    /* Output an ordered list of all the permission fields that exist. */
    foreach ($slice as $key => $value) {
        foreach ($slice[$key] as $PERMNAME => $value2) {
            /* Output $PERMNAME. */
            $line = $line . $ofs . $PERMNAME;
        }
        /* end foreach */
    }
    /* end foreach */
    /* Output an ordered list of all the Altium user parameters that exist in our universe as columns in the csv file. */
    foreach ($altiumUserParmNames as $PARAMETERNAME => $value) {
        /* Output $PARAMETERNAME. */
        $line = $line . $ofs . $PARAMETERNAME;
    }
    /* end foreach */
    //  echo "altiumAclDataByObjectGuid is:\n";
    //  print_r($altiumAclDataByObjectGuid);
    /* Write line to file.  Note:  explicitly use DOS (CR/LF) \r\n line endings! */
    fputs($auditFoldersFile, $line . "\r\n");
    /** Create array to temporarily hold all lines that we generate, since we need to sort before writing to file. **/
    $auditFoldersLines = array();
    /* Setup query SQL commands. */
    $queryText = '
SELECT FOLDER.GUID AS FOLDERGUID, FOLDER.HRID, FOLDER.CREATEDBYGUID, FOLDER.LASTMODIFIEDBYGUID, FOLDER.CREATEDAT, FOLDER.LASTMODIFIEDAT, FOLDER.PARENTFOLDERGUID, FOLDER.DESCRIPTION, FT.HRID AS FOLDERTYPE
FROM ALU_FOLDER FOLDER
LEFT JOIN ALU_FOLDERTYPE FT ON FOLDER.FOLDERTYPEGUID = FT.GUID
;
';
    echo date('H:i:s') . " Begin query to read in all folder info from Vault database...\n";
    /* Execute SQL query. */
    $resultHandle = odbc_exec($db, $queryText);
    /* Loop over all rows returned by SQL query. */
    while (odbc_fetch_row($resultHandle)) {
        /* Extract the fields of interest from this query result. */
        $FOLDERGUID = odbc_result($resultHandle, "FOLDERGUID");
        $DESCRIPTION = odbc_result($resultHandle, "DESCRIPTION");
        $FOLDERTYPE = odbc_result($resultHandle, "FOLDERTYPE");
        $CREATEDBYGUID = odbc_result($resultHandle, "CREATEDBYGUID");
        $LASTMODIFIEDBYGUID = odbc_result($resultHandle, "LASTMODIFIEDBYGUID");
        $CREATEDAT = odbc_result($resultHandle, "CREATEDAT");
        $LASTMODIFIEDAT = odbc_result($resultHandle, "LASTMODIFIEDAT");
        /* Lookup the usernames of the person to create and last modify this folder. */
        $CREATEDBY = CACF_LookupUsername($altiumUserNamesByGuid, $CREATEDBYGUID);
        $LASTMODIFIEDBY = CACF_LookupUsername($altiumUserNamesByGuid, $LASTMODIFIEDBYGUID);
        /* Lookup the full path of this folder, based on cached data from having already read in this table once already. */
        $FOLDERPATH = CACF_TraceFolderPath($CACFconstants, $altiumFoldersByGuid, $FOLDERGUID);
        /** Output actual data. **/
        $line = "";
        $line = $line . "{$FOLDERGUID}" . $ofs . "{$DESCRIPTION}" . $ofs . "{$FOLDERTYPE}" . $ofs . "{$FOLDERPATH}" . $ofs . "{$CREATEDBY}" . $ofs . "{$CREATEDAT}" . $ofs . "{$LASTMODIFIEDBY}" . $ofs . "{$LASTMODIFIEDAT}";
        /** Output an ordered list of all the Altium user parameters that exist in our universe as columns in the csv file.
            If this part has a given parameter, list its value. **/
        /* Get all the permission fields that exist for this folder. */
        foreach ($altiumAclDataByObjectGuid[$FOLDERGUID] as $PERMNAME => $PERMVALUE) {
            /* Output $PERMVALUE. */
            $line = $line . $ofs . $PERMVALUE;
        }
        /* end foreach */
        /* Loop over all the defined Altium user parameter names. */
        foreach ($altiumUserParmNames as $PARAMETERNAME => $value) {
            /* Unconditionally print out a field separator. */
            $line = $line . $ofs;
            /* If this component has a stored folder user parameter named $PARAMETERNAME, then output it. */
            if (isset($altiumFolderUserParmValuesByGuid[$FOLDERGUID][$PARAMETERNAME])) {
                $line = $line . $altiumFolderUserParmValuesByGuid[$FOLDERGUID][$PARAMETERNAME];
            } else {
                $line = $line . $constAbsent;
            }
        }
        /* end foreach */
        /* Store this line in an in-memory array, so we can sort it all just before writing to disk. */
        $auditFoldersLines[$FOLDERPATH] = $line;
    }
    /* endwhile */
    /* Free memory that was holding query results. */
    odbc_free_result($resultHandle);
    /* Sort all output lines here by folder path (key). */
    $rc = ksort($auditFoldersLines);
    if ($rc == FALSE) {
        my_die("ksort() failed!");
    }
    /* Loop over all lines in what will be our output file. */
    foreach ($auditFoldersLines as $key => $line) {
        /* Write line to file.  Note:  explicitly use DOS (CR/LF) \r\n line endings! */
        fputs($auditFoldersFile, $line . "\r\n");
    }
    /* endforeach */
    /** Clear array that held all lines prior to writing to file. **/
    $auditFoldersLines = array();
    /** Close the audit output file. **/
    fclose($auditFoldersFile);
    echo date('H:i:s') . " Done writing audit folders file \"{$auditFoldersFileName}.\"\n";
}
Example #18
0
 function upload($index, $album_id = false, $album = '', $title = '', $descr = '')
 {
     if (!isset($_FILES[$index])) {
         return 'uploading error: file not found';
     }
     if (0 != $_FILES[$index]['error']) {
         return 'uploading error: #' . $_FILES[$index]['error'] . ' - ' . $this->error_code_decrypt($_FILES[$index]['error']);
     }
     //		if ('image/jpeg' != $_FILES[$index]['type']) {
     //			return 'uploading error: format not supported';
     //		}
     if (false === strpos($_FILES[$index]['type'], 'jpeg')) {
         return 'uploading error: format not supported';
     }
     $filename = get_uniq() . '.jpg';
     //		dbg($filename);
     // Save BIG picture
     if (move_uploaded_file($_FILES[$index]["tmp_name"], FLGR_PHOTOS_BIGS . '/' . $filename)) {
         // Processed
         // Открываем файл
         $rImg = imagecreatefromjpeg(FLGR_PHOTOS_BIGS . '/' . $filename);
         // Получаем размеры
         $nWidth = imagesx($rImg);
         $nHeight = imagesy($rImg);
         // Определяем, горизонтальный он или вертикальный
         $orientation = $this->get_orientation($nWidth, $nHeight);
         // normal
         if ($orientation == ORIENTATION_HORIZONTAL) {
             $nPixLimit = 604;
         } else {
             $nPixLimit = 480;
         }
         list($nX, $nY) = $this->get_proportional_scale($orientation, $nPixLimit, $nWidth, $nHeight);
         // Масштабируем
         $rNewImg = imagecreatetruecolor($nX, $nY);
         imagecopyresampled($rNewImg, $rImg, 0, 0, 0, 0, $nX, $nY, $nWidth, $nHeight);
         // Сохраняем
         imagejpeg($rNewImg, FLGR_PHOTOS_BIGS . '/' . $filename);
         // thumbnail
         $nPixLimit = 100;
         list($nX, $nY) = $this->get_proportional_scale($orientation, $nPixLimit, $nWidth, $nHeight);
         // Масштабируем
         $rNewImg = imagecreatetruecolor($nX, $nY);
         imagecopyresampled($rNewImg, $rImg, 0, 0, 0, 0, $nX, $nY, $nWidth, $nHeight);
         // Сохраняем
         imagejpeg($rNewImg, FLGR_PHOTOS_THUMBNAILS . '/' . $filename);
     }
     // Save to bd
     // get album id
     //		dbg($album_id);
     if ($album_id == false) {
         $sql = "SELECT `id` FROM `" . DB_PREFIX . DB_TBL_ALBUMS . "` WHERE \n\t\t\t\t`name` = '" . mysql_escape_string($album) . "'";
         $sql = mysql_query($sql);
         if (false == $sql) {
             my_die();
         }
         $album_id = mysql_fetch_assoc($sql);
         if (!empty($album_id)) {
             $album_id = current($album_id);
         }
     }
     if (!is_numeric($album_id)) {
         return 'upload error: album not found';
     }
     $sql = "INSERT INTO `" . DB_PREFIX . DB_TBL_PHOTOS . "` (`seg`, `off`, `filename`) VALUES (\n\t\t\t'album', \n\t\t\t'" . mysql_escape_string($album_id) . "', \n\t\t\t'{$filename}'\n\t\t\t)";
     $this->query($sql);
     // Return
     return true;
 }
Example #19
0
function getSubVersionsRecursive($nId)
{
    global $aTree;
    if (!isset($aTree[$nId])) {
        $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_PAGES . "` \n\t\tWHERE (`id` = '{$nId}')";
        $sql = mysql_query($sql);
        if (false == $sql) {
            my_die();
        }
        while ($row = mysql_fetch_assoc($sql)) {
            $aTree[$row['id']] = $row;
        }
    }
    $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_PAGES . "` \n\t\t\tWHERE ((`parent` = '{$nId}') AND (`subversion` = 1)) \n\t\t\tORDER BY `order`";
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
    while ($row = mysql_fetch_assoc($sql)) {
        $aTree[$nId]['childs'][] = $row['id'];
        $aTree[$row['id']] = $row;
        getSubVersionsRecursive($row['id']);
    }
}
Example #20
0
function nGetCountComments_FromPostId($nId)
{
    $sql = 'SELECT count(*) FROM `' . DB_PREFIX . DB_TBL_COMMENTS . '` WHERE `post` = ' . $nId;
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
    return current($row = mysql_fetch_assoc($sql));
}
Example #21
0
        $message = 'You must first delete texts, archived texts and words with this language!';
    } else {
        $message = runsql('delete from ' . $tbpref . 'languages where LgID = ' . $_REQUEST['del'], "Deleted");
        adjust_autoincr('languages', 'LgID');
    }
} elseif (isset($_REQUEST['op'])) {
    // INSERT
    if ($_REQUEST['op'] == 'Save') {
        $message = runsql('insert into ' . $tbpref . 'languages (LgName, LgDict1URI, LgDict2URI, LgGoogleTranslateURI, LgExportTemplate, LgTextSize, LgCharacterSubstitutions, LgRegexpSplitSentences, LgExceptionsSplitSentences, LgRegexpWordCharacters, LgRemoveSpaces, LgSplitEachChar, LgRightToLeft) values(' . convert_string_to_sqlsyntax($_REQUEST["LgName"]) . ', ' . convert_string_to_sqlsyntax($_REQUEST["LgDict1URI"]) . ', ' . convert_string_to_sqlsyntax($_REQUEST["LgDict2URI"]) . ', ' . convert_string_to_sqlsyntax($_REQUEST["LgGoogleTranslateURI"]) . ', ' . convert_string_to_sqlsyntax($_REQUEST["LgExportTemplate"]) . ', ' . $_REQUEST["LgTextSize"] . ', ' . convert_string_to_sqlsyntax_notrim_nonull($_REQUEST["LgCharacterSubstitutions"]) . ', ' . convert_string_to_sqlsyntax($_REQUEST["LgRegexpSplitSentences"]) . ', ' . convert_string_to_sqlsyntax_notrim_nonull($_REQUEST["LgExceptionsSplitSentences"]) . ', ' . convert_string_to_sqlsyntax($_REQUEST["LgRegexpWordCharacters"]) . ', ' . $_REQUEST["LgRemoveSpaces"] . ', ' . $_REQUEST["LgSplitEachChar"] . ', ' . $_REQUEST["LgRightToLeft"] . ')', 'Saved');
    } elseif ($_REQUEST['op'] == 'Change') {
        // Get old values
        $sql = "select * from " . $tbpref . "languages where LgID=" . $_REQUEST["LgID"];
        $res = do_mysql_query($sql);
        $record = mysql_fetch_assoc($res);
        if ($record == FALSE) {
            my_die("Cannot access language data: {$sql}");
        }
        $oldCharacterSubstitutions = $record['LgCharacterSubstitutions'];
        $oldRegexpSplitSentences = $record['LgRegexpSplitSentences'];
        $oldExceptionsSplitSentences = $record['LgExceptionsSplitSentences'];
        $oldRegexpWordCharacters = $record['LgRegexpWordCharacters'];
        $oldRemoveSpaces = $record['LgRemoveSpaces'];
        $oldSplitEachChar = $record['LgSplitEachChar'];
        mysql_free_result($res);
        $needReParse = convert_string_to_sqlsyntax_notrim_nonull($_REQUEST["LgCharacterSubstitutions"]) != convert_string_to_sqlsyntax_notrim_nonull($oldCharacterSubstitutions) || convert_string_to_sqlsyntax($_REQUEST["LgRegexpSplitSentences"]) != convert_string_to_sqlsyntax($oldRegexpSplitSentences) || convert_string_to_sqlsyntax_notrim_nonull($_REQUEST["LgExceptionsSplitSentences"]) != convert_string_to_sqlsyntax_notrim_nonull($oldExceptionsSplitSentences) || convert_string_to_sqlsyntax($_REQUEST["LgRegexpWordCharacters"]) != convert_string_to_sqlsyntax($oldRegexpWordCharacters) || $_REQUEST["LgRemoveSpaces"] != $oldRemoveSpaces || $_REQUEST["LgSplitEachChar"] != $oldSplitEachChar;
        $needReParse = $needReParse ? 1 : 0;
        $message = runsql('update ' . $tbpref . 'languages set ' . 'LgName = ' . convert_string_to_sqlsyntax($_REQUEST["LgName"]) . ', ' . 'LgDict1URI = ' . convert_string_to_sqlsyntax($_REQUEST["LgDict1URI"]) . ', ' . 'LgDict2URI = ' . convert_string_to_sqlsyntax($_REQUEST["LgDict2URI"]) . ', ' . 'LgGoogleTranslateURI = ' . convert_string_to_sqlsyntax($_REQUEST["LgGoogleTranslateURI"]) . ', ' . 'LgExportTemplate = ' . convert_string_to_sqlsyntax($_REQUEST["LgExportTemplate"]) . ', ' . 'LgTextSize = ' . $_REQUEST["LgTextSize"] . ', ' . 'LgCharacterSubstitutions = ' . convert_string_to_sqlsyntax_notrim_nonull($_REQUEST["LgCharacterSubstitutions"]) . ', ' . 'LgRegexpSplitSentences = ' . convert_string_to_sqlsyntax($_REQUEST["LgRegexpSplitSentences"]) . ', ' . 'LgExceptionsSplitSentences = ' . convert_string_to_sqlsyntax_notrim_nonull($_REQUEST["LgExceptionsSplitSentences"]) . ', ' . 'LgRegexpWordCharacters = ' . convert_string_to_sqlsyntax($_REQUEST["LgRegexpWordCharacters"]) . ', ' . 'LgRemoveSpaces = ' . $_REQUEST["LgRemoveSpaces"] . ', ' . 'LgSplitEachChar = ' . $_REQUEST["LgSplitEachChar"] . ', ' . 'LgRightToLeft = ' . $_REQUEST["LgRightToLeft"] . ' where LgID = ' . $_REQUEST["LgID"], 'Updated');
        if ($needReParse) {
            $id = $_REQUEST["LgID"] + 0;
            runsql('delete from ' . $tbpref . 'sentences where SeLgID = ' . $id, "Sentences deleted");
            runsql('delete from ' . $tbpref . 'textitems where TiLgID = ' . $id, "Text items deleted");
Example #22
0
function check_update_db()
{
    global $debug, $tbpref;
    $tables = array();
    $res = do_mysql_query(str_replace('_', "\\_", "SHOW TABLES LIKE " . convert_string_to_sqlsyntax_nonull($tbpref . '%')));
    while ($row = mysql_fetch_row($res)) {
        $tables[] = $row[0];
    }
    mysql_free_result($res);
    $count = 0;
    // counter for cache rebuild
    // Rebuild Tables if missing (current versions!)
    if (in_array($tbpref . 'archivedtexts', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding archivedtexts</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "archivedtexts ( AtID int(11) unsigned NOT NULL AUTO_INCREMENT, AtLgID int(11) unsigned NOT NULL, AtTitle varchar(200) NOT NULL, AtText text NOT NULL, AtAnnotatedText longtext NOT NULL, AtAudioURI varchar(200) DEFAULT NULL, AtSourceURI varchar(1000) DEFAULT NULL, PRIMARY KEY (AtID), KEY AtLgID (AtLgID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if (in_array($tbpref . 'languages', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding languages</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "languages ( LgID int(11) unsigned NOT NULL AUTO_INCREMENT, LgName varchar(40) NOT NULL, LgDict1URI varchar(200) NOT NULL, LgDict2URI varchar(200) DEFAULT NULL, LgGoogleTranslateURI varchar(200) DEFAULT NULL, LgExportTemplate varchar(1000) DEFAULT NULL, LgTextSize int(5) unsigned NOT NULL DEFAULT '100', LgCharacterSubstitutions varchar(500) NOT NULL, LgRegexpSplitSentences varchar(500) NOT NULL, LgExceptionsSplitSentences varchar(500) NOT NULL, LgRegexpWordCharacters varchar(500) NOT NULL, LgRemoveSpaces int(1) unsigned NOT NULL DEFAULT '0', LgSplitEachChar int(1) unsigned NOT NULL DEFAULT '0', LgRightToLeft int(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (LgID), UNIQUE KEY LgName (LgName) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if (in_array($tbpref . 'sentences', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding sentences</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "sentences ( SeID int(11) unsigned NOT NULL AUTO_INCREMENT, SeLgID int(11) unsigned NOT NULL, SeTxID int(11) unsigned NOT NULL, SeOrder int(11) unsigned NOT NULL, SeText text, PRIMARY KEY (SeID), KEY SeLgID (SeLgID), KEY SeTxID (SeTxID), KEY SeOrder (SeOrder) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
        $count++;
    }
    if (in_array($tbpref . 'settings', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding settings</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "settings ( StKey varchar(40) NOT NULL, StValue varchar(40) DEFAULT NULL, PRIMARY KEY (StKey) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if (in_array($tbpref . 'textitems', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding textitems</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "textitems ( TiID int(11) unsigned NOT NULL AUTO_INCREMENT, TiLgID int(11) unsigned NOT NULL, TiTxID int(11) unsigned NOT NULL, TiSeID int(11) unsigned NOT NULL, TiOrder int(11) unsigned NOT NULL, TiWordCount int(1) unsigned NOT NULL, TiText varchar(250) NOT NULL, TiTextLC varchar(250) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, TiIsNotWord tinyint(1) NOT NULL, PRIMARY KEY (TiID), KEY TiLgID (TiLgID), KEY TiTxID (TiTxID), KEY TiSeID (TiSeID), KEY TiOrder (TiOrder), KEY TiTextLC (TiTextLC), KEY TiIsNotWord (TiIsNotWord) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
        $count++;
    }
    if (in_array($tbpref . 'texts', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding texts</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "texts ( TxID int(11) unsigned NOT NULL AUTO_INCREMENT, TxLgID int(11) unsigned NOT NULL, TxTitle varchar(200) NOT NULL, TxText text NOT NULL, TxAnnotatedText longtext NOT NULL, TxAudioURI varchar(200) DEFAULT NULL, TxSourceURI varchar(1000) DEFAULT NULL, PRIMARY KEY (TxID), KEY TxLgID (TxLgID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if (in_array($tbpref . 'words', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding words</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "words ( WoID int(11) unsigned NOT NULL AUTO_INCREMENT, WoLgID int(11) unsigned NOT NULL, WoText varchar(250) NOT NULL, WoTextLC varchar(250) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, WoStatus tinyint(4) NOT NULL, WoTranslation varchar(500) NOT NULL DEFAULT '*', WoRomanization varchar(100) DEFAULT NULL, WoSentence varchar(1000) DEFAULT NULL, WoCreated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, WoStatusChanged timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', WoTodayScore double NOT NULL DEFAULT '0', WoTomorrowScore double NOT NULL DEFAULT '0', WoRandom double NOT NULL DEFAULT '0', PRIMARY KEY (WoID), UNIQUE KEY WoLgIDTextLC (WoLgID,WoTextLC), KEY WoLgID (WoLgID), KEY WoStatus (WoStatus), KEY WoTextLC (WoTextLC), KEY WoTranslation (WoTranslation(333)), KEY WoCreated (WoCreated), KEY WoStatusChanged (WoStatusChanged), KEY WoTodayScore (WoTodayScore), KEY WoTomorrowScore (WoTomorrowScore), KEY WoRandom (WoRandom) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if (in_array($tbpref . 'tags', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding tags</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "tags ( TgID int(11) unsigned NOT NULL AUTO_INCREMENT, TgText varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, TgComment varchar(200) NOT NULL DEFAULT '', PRIMARY KEY (TgID), UNIQUE KEY TgText (TgText) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if (in_array($tbpref . 'wordtags', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding wordtags</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "wordtags ( WtWoID int(11) unsigned NOT NULL, WtTgID int(11) unsigned NOT NULL, PRIMARY KEY (WtWoID,WtTgID), KEY WtTgID (WtTgID), KEY WtWoID (WtWoID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if (in_array($tbpref . 'tags2', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding tags2</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "tags2 ( T2ID int(11) unsigned NOT NULL AUTO_INCREMENT, T2Text varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, T2Comment varchar(200) NOT NULL DEFAULT '', PRIMARY KEY (T2ID), UNIQUE KEY T2Text (T2Text) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if (in_array($tbpref . 'texttags', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding texttags</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "texttags ( TtTxID int(11) unsigned NOT NULL, TtT2ID int(11) unsigned NOT NULL, PRIMARY KEY (TtTxID,TtT2ID), KEY TtTxID (TtTxID), KEY TtT2ID (TtT2ID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if (in_array($tbpref . 'archtexttags', $tables) == FALSE) {
        if ($debug) {
            echo '<p>DEBUG: rebuilding archtexttags</p>';
        }
        runsql("CREATE TABLE IF NOT EXISTS " . $tbpref . "archtexttags ( AgAtID int(11) unsigned NOT NULL, AgT2ID int(11) unsigned NOT NULL, PRIMARY KEY (AgAtID,AgT2ID), KEY AgAtID (AgAtID), KEY AgT2ID (AgT2ID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8", '');
    }
    if ($count > 0) {
        // Rebuild Text Cache if cache tables new
        if ($debug) {
            echo '<p>DEBUG: rebuilding cache tables</p>';
        }
        reparse_all_texts();
    }
    // DB Version
    $currversion = get_version_number();
    $res = mysql_query("select StValue as value from " . $tbpref . "settings where StKey = 'dbversion'");
    if (mysql_errno() != 0) {
        my_die('There is something wrong with your database ' . $dbname . '. Please reinstall.');
    }
    $record = mysql_fetch_assoc($res);
    if ($record) {
        $dbversion = $record["value"];
    } else {
        $dbversion = 'v001000000';
    }
    mysql_free_result($res);
    // Do DB Updates if tables seem to be old versions
    if ($dbversion < $currversion) {
        if ($debug) {
            echo "<p>DEBUG: do DB updates: {$dbversion} --&gt; {$currversion}</p>";
        }
        runsql("ALTER TABLE " . $tbpref . "words ADD WoTodayScore DOUBLE NOT NULL DEFAULT 0, ADD WoTomorrowScore DOUBLE NOT NULL DEFAULT 0, ADD WoRandom DOUBLE NOT NULL DEFAULT 0", '', $sqlerrdie = FALSE);
        runsql("ALTER TABLE " . $tbpref . "words ADD INDEX WoTodayScore (WoTodayScore), ADD INDEX WoTomorrowScore (WoTomorrowScore), ADD INDEX WoRandom (WoRandom)", '', $sqlerrdie = FALSE);
        runsql("ALTER TABLE " . $tbpref . "languages ADD LgRightToLeft INT(1) UNSIGNED NOT NULL DEFAULT  0", '', $sqlerrdie = FALSE);
        runsql("ALTER TABLE " . $tbpref . "texts ADD TxAnnotatedText LONGTEXT NOT NULL AFTER TxText", '', $sqlerrdie = FALSE);
        runsql("ALTER TABLE " . $tbpref . "archivedtexts ADD AtAnnotatedText LONGTEXT NOT NULL AFTER AtText", '', $sqlerrdie = FALSE);
        runsql("ALTER TABLE " . $tbpref . "tags CHANGE TgComment TgComment VARCHAR(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''", '', $sqlerrdie = FALSE);
        runsql("ALTER TABLE " . $tbpref . "tags2 CHANGE T2Comment T2Comment VARCHAR(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''", '', $sqlerrdie = FALSE);
        runsql("ALTER TABLE " . $tbpref . "languages CHANGE LgGoogleTTSURI LgExportTemplate VARCHAR(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL", '', $sqlerrdie = FALSE);
        runsql("ALTER TABLE " . $tbpref . "texts ADD TxSourceURI VARCHAR(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL", '', $sqlerrdie = FALSE);
        runsql("ALTER TABLE " . $tbpref . "archivedtexts ADD AtSourceURI VARCHAR(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL", '', $sqlerrdie = FALSE);
        // set to current.
        saveSetting('dbversion', $currversion);
        saveSetting('lastscorecalc', '');
        // do next section, too
    }
    // Do Scoring once per day, clean Word/Texttags, and optimize db
    $lastscorecalc = getSetting('lastscorecalc');
    $today = date('Y-m-d');
    if ($lastscorecalc != $today) {
        if ($debug) {
            echo '<p>DEBUG: Doing score recalc. Today: ' . $today . ' / Last: ' . $lastscorecalc . '</p>';
        }
        runsql("UPDATE " . $tbpref . "words SET " . make_score_random_insert_update('u'), '');
        runsql("DELETE " . $tbpref . "wordtags FROM (" . $tbpref . "wordtags LEFT JOIN " . $tbpref . "tags on WtTgID = TgID) WHERE TgID IS NULL", '');
        runsql("DELETE " . $tbpref . "wordtags FROM (" . $tbpref . "wordtags LEFT JOIN " . $tbpref . "words on WtWoID = WoID) WHERE WoID IS NULL", '');
        runsql("DELETE " . $tbpref . "texttags FROM (" . $tbpref . "texttags LEFT JOIN " . $tbpref . "tags2 on TtT2ID = T2ID) WHERE T2ID IS NULL", '');
        runsql("DELETE " . $tbpref . "texttags FROM (" . $tbpref . "texttags LEFT JOIN " . $tbpref . "texts on TtTxID = TxID) WHERE TxID IS NULL", '');
        runsql("DELETE " . $tbpref . "archtexttags FROM (" . $tbpref . "archtexttags LEFT JOIN " . $tbpref . "tags2 on AgT2ID = T2ID) WHERE T2ID IS NULL", '');
        runsql("DELETE " . $tbpref . "archtexttags FROM (" . $tbpref . "archtexttags LEFT JOIN " . $tbpref . "archivedtexts on AgAtID = AtID) WHERE AtID IS NULL", '');
        optimizedb();
        saveSetting('lastscorecalc', $today);
    }
}
Example #23
0
            $lang = $record['TiLgID'];
        } else {
            my_die("Cannot access Term and Language in edit_word.php");
        }
        mysql_free_result($res);
        $termlc = mb_strtolower($term, 'UTF-8');
        $wid = get_first_value("select WoID as value from " . $tbpref . "words where WoLgID = " . $lang . " and WoTextLC = " . convert_string_to_sqlsyntax($termlc));
    } else {
        $sql = 'select WoText, WoLgID from ' . $tbpref . 'words where WoID = ' . $wid;
        $res = do_mysql_query($sql);
        $record = mysql_fetch_assoc($res);
        if ($record) {
            $term = $record['WoText'];
            $lang = $record['WoLgID'];
        } else {
            my_die("Cannot access Term and Language in edit_word.php");
        }
        mysql_free_result($res);
        $termlc = mb_strtolower($term, 'UTF-8');
    }
    $new = isset($wid) == FALSE;
    $titletext = ($new ? "New Term" : "Edit Term") . ": " . tohtml($term);
    pagestart_nobody($titletext);
    ?>
<script type="text/javascript" src="js/unloadformcheck.js" charset="utf-8"></script>
<?php 
    $scrdir = getScriptDirectionTag($lang);
    // NEW
    if ($new) {
        $seid = get_first_value("select TiSeID as value from " . $tbpref . "textitems where TiTxID = " . $_REQUEST['tid'] . " and TiWordCount = 1 and TiOrder = " . $_REQUEST['ord']);
        $sent = getSentence($seid, $termlc, (int) getSettingWithDefault('set-term-sentence-count'));
Example #24
0
require_once 'utilities.inc.php';
$x = $_REQUEST["x"];
$i = stripTheSlashesIfNeeded($_REQUEST["i"]);
$t = stripTheSlashesIfNeeded($_REQUEST["t"]);
if ($x == 1) {
    $sql = 'select SeText, LgGoogleTranslateURI from ' . $tbpref . 'languages, ' . $tbpref . 'sentences, ' . $tbpref . 'textitems where TiSeID = SeID and TiLgID = LgID and TiTxID = ' . $t . ' and TiOrder = ' . $i;
    $res = do_mysql_query($sql);
    $record = mysql_fetch_assoc($res);
    if ($record) {
        $satz = $record['SeText'];
        $trans = isset($record['LgGoogleTranslateURI']) ? $record['LgGoogleTranslateURI'] : "";
        if (substr($trans, 0, 1) == '*') {
            $trans = substr($trans, 1);
        }
    } else {
        my_die("No results: {$sql}");
    }
    mysql_free_result($res);
    if ($trans != '') {
        /*
        echo "{" . $i . "}<br />";
        echo "{" . $t . "}<br />";
        echo "{" . createTheDictLink($trans,$satz) . "}<br />";
        */
        header("Location: " . createTheDictLink($trans, $satz));
    }
    exit;
}
if ($x == 2) {
    /*
    echo "{" . $i . "}<br />";
Example #25
0
function getStemNews($q)
{
    global $aMatch;
    $aStemNews = array();
    // Сначала ищем совпадения по `title`
    $sql = "SELECT \t`id`, `title`, MATCH (`title`) AGAINST ('" . $q . "' IN BOOLEAN MODE) AS `rel`\n\t\t\tFROM `" . DB_PREFIX . DB_TBL_POSTS . "`\n\t\t\tWHERE MATCH (`title`) AGAINST ('" . $q . "' IN BOOLEAN MODE)";
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
    while ($row = mysql_fetch_assoc($sql)) {
        $path = '/postid/' . $row['id'];
        $aStemNews[$path] = $row;
    }
    // Ищем совпадения по `text`
    $sql = "SELECT \t`id`, `title`, MATCH (`text`) AGAINST ('" . $q . "' IN BOOLEAN MODE) AS `rel`\n\t\t\tFROM `" . DB_PREFIX . DB_TBL_POSTS . "`\n\t\t\tWHERE MATCH (`text`) AGAINST ('" . $q . "' IN BOOLEAN MODE)";
    $sql = mysql_query($sql);
    if (false == $sql) {
        my_die();
    }
    while ($row = mysql_fetch_assoc($sql)) {
        $path = '/postid/' . $row['id'];
        // Если эта страница уже найдена - добавить ей веса
        if (!isset($aStemNews[$path])) {
            $aStemNews[$path] = $row;
        } else {
            $aStemNews[$path]['rel'] = $aStemNews[$path]['rel'] + $row['rel'];
        }
    }
    // Если страницы, найденные по стеммингу уже были найдены обычным способом
    // то добавить им релевантности там, а здесь - удалить
    foreach ($aStemNews as $k => $v) {
        if (isset($aMatch[$k])) {
            $aMatch[$k]['rel'] += $aStemNews[$k]['rel'];
        }
    }
    foreach ($aMatch as $k => $v) {
        if (isset($aStemNews[$k])) {
            unset($aStemNews[$k]);
        }
    }
    return $aStemNews;
}
Example #26
0
    }
    $sql = 'select WoText, WoLgID, WoTranslation, WoSentence, WoRomanization, WoStatus from ' . $tbpref . 'words where WoID = ' . $wid;
    $res = do_mysql_query($sql);
    $record = mysql_fetch_assoc($res);
    if ($record) {
        $term = $record['WoText'];
        $lang = $record['WoLgID'];
        $transl = repl_tab_nl($record['WoTranslation']);
        if ($transl == '*') {
            $transl = '';
        }
        $sentence = repl_tab_nl($record['WoSentence']);
        $rom = $record['WoRomanization'];
        $status = $record['WoStatus'];
    } else {
        my_die("Term data not found in edit_tword.php");
    }
    mysql_free_result($res);
    $termlc = mb_strtolower($term, 'UTF-8');
    $titletext = "Edit Term: " . tohtml($term);
    pagestart_nobody($titletext);
    $scrdir = getScriptDirectionTag($lang);
    ?>
<script type="text/javascript" src="js/unloadformcheck.js" charset="utf-8"></script>
	
<form name="editword" class="validate" action="<?php 
    echo $_SERVER['PHP_SELF'];
    ?>
" method="post">
<input type="hidden" name="WoLgID" id="langfield" value="<?php 
    echo $lang;
Example #27
0
$aCategory = mysql_fetch_assoc($sql);
if (empty($aCategory)) {
    $_t->assign('content', '<span style="color: red">Ошибка:</span> Категория новостей не существует!');
    return;
}
// POST
if (isset($_POST['act'])) {
    if (empty($_POST['hidden'])) {
        $_POST['hidden'] = 0;
    }
    switch ($_POST['act']) {
        case $act:
            $sql = "INSERT INTO `" . DB_PREFIX . DB_TBL_POSTS . "` ( \n\t\t\t\t`id`,\n\t\t\t\t`category`,\n\t\t\t\t`t`, \n\t\t\t\t`title`,\n\t\t\t\t`annotation`,\n\t\t\t\t`text`,\n\t\t\t\t`image`,\n\t\t\t\t`hidden`\n\t\t\t\t) VALUES (\t\t\t\t\n\t\t\t\t'',\n\t\t\t\t'" . $category . "',\n\t\t\t\t'" . mysql_escape_string($_POST['t']) . "',\n\t\t\t\t'" . mysql_escape_string($_POST['title']) . "',\n\t\t\t\t'" . mysql_escape_string($_POST['annotation']) . "',\n\t\t\t\t'" . mysql_escape_string($_POST['text']) . "',\n\t\t\t\t'" . mysql_escape_string($_POST['image']) . "',\n\t\t\t\t'" . mysql_escape_string($_POST['hidden']) . "'\n\t\t\t\t)";
            $sql = mysql_query($sql);
            if (false == $sql) {
                my_die();
            }
            header('Location: ' . $aCmsModules['newsadm']['key']);
            break;
    }
}
// load template
$tpl = new KTemplate(FLGR_CMS_TEMPLATES . '/' . $sModuleTpl . '.htm');
if (!defined('FCK')) {
    // TEXT
    $tplFck = $tpl->fetchBlock('text');
    $tplFck->assign($aParent);
    $tpl->assign('text', $tplFck);
    $tplFck->reset();
    unset($aParent['text']);
    // ANNOTATION
Example #28
0
			(SQL via $_SESSION['testsql'])
Show test frame
***************************************************************/
require_once 'settings.inc.php';
require_once 'connect.inc.php';
require_once 'dbutils.inc.php';
require_once 'utilities.inc.php';
$p = '';
if (isset($_REQUEST['selection']) && isset($_SESSION['testsql'])) {
    $testsql = $_SESSION['testsql'];
} elseif (isset($_REQUEST['lang'])) {
    $testsql = ' ' . $tbpref . 'words where WoLgID = ' . $_REQUEST['lang'] . ' ';
} elseif (isset($_REQUEST['text'])) {
    $testsql = ' ' . $tbpref . 'words, ' . $tbpref . 'textitems where TiLgID = WoLgID and TiTextLC = WoTextLC and TiTxID = ' . $_REQUEST['text'] . ' ';
} else {
    my_die("do_test_test.php called with wrong parameters");
}
$testtype = getreq('type') + 0;
if ($testtype < 1) {
    $testtype = 1;
}
if ($testtype > 5) {
    $testtype = 5;
}
$nosent = 0;
if ($testtype > 3) {
    $testtype = $testtype - 3;
    $nosent = 1;
}
$totaltests = $_SESSION['testtotal'];
$wrong = $_SESSION['testwrong'];
Example #29
0
        default:
            break;
    }
}
// BreadCrumbs
$_t->assign('BreadCrumbs', $BreadCrumbs->get());
stylesheet('profile.css');
// DopNav
if ($aSubject['id'] == $Permissions->getLoggedUserId()) {
    DopNav('/' . $aItem['seg'], $aRequest[$nLevel + 1], $aItem['off']);
} else {
    $_t->assign('DopNav', '');
}
// OPEN
if ('' == $sModuleTpl) {
    my_die('Error: Template not found');
}
$tpl = new KTemplate(FLGR_TEMPLATES . '/' . $sModuleTpl . '.htm');
$aWalls = $Walls->getItems($seg, $off);
$aArray = array('title' => '
		Комменты
		<a href="#" onclick="ShowHide(\'write_wall\');" class="comment_new">
			написать
		</a>
	', 'info' => '
		<div id="write_wall" style="display: none;">
			<form method="post">
				<input type="hidden" name="act" value="write_wall" />
				<input type="hidden" name="user_id" value="' . $off . '" />
				<textarea name="message" rows="6" style="width: 90%; overflow-x: hidden;"></textarea>
				<input type="submit" value="Отправить" />
Example #30
0
 function updateFile($file_id)
 {
     // Проверяем существование записи о файле в таблице файлов
     $sql = "SELECT * FROM `" . DB_PREFIX . DB_TBL_FILES . "` WHERE `id` = " . $file_id;
     $sql = mysql_query($sql);
     if (false == $sql) {
         my_die();
     }
     $aList = array();
     while ($row = mysql_fetch_assoc($sql)) {
         $aList[] = $row;
     }
     if (empty($aList)) {
         return 'file record not found';
     }
     $aFile = current($aList);
     // Проверяем существование файла в файловой системе
     if (!defined($aFile['path'])) {
         // Невозможно разрешить путь к файлу
         return 'file path not correct';
     }
     $real_path = constant($aFile['path']) . '/' . $aFile['name'];
     if (!file_exists($real_path)) {
         // Файла в файловой системе нет - надо создать пустой
         safewrite($real_path);
     }
     // Отправляем запрос хэша
     $response = cUpdate::sendXmlRpc('getFileHash', array($aFile['name'], $aFile['path']));
     if (is_object($response)) {
         return 'xmlrpc-error: [' . $response->faultCode() . '] ' . $response->faultString();
     }
     $r_hash = $response;
     // Если хэш совпадает - выходим
     if ($r_hash == md5(file_get_contents($real_path))) {
         //return true;
     }
     // Отправляем запрос файла
     $response = cUpdate::sendXmlRpc('getFileContent', array($aFile['name'], $aFile['path']));
     if (is_object($response)) {
         return 'xmlrpc-error: [' . $response->faultCode() . '] ' . $response->faultString();
     }
     $r_content = base64_decode($response);
     dbg($r_content);
     // Переписываем файл в файловой системе
     if (defined($aFile['path'])) {
         safewrite(constant($aFile['path']) . '/' . $aFile['name'], $r_content);
     }
     // Выходим
     return true;
 }