/**
 * UpdateUserProfile
 *
 * @param $user_id
 * @param $pass1
 * @param $hideOffline
 * @param $theme
 * @param $language
 */
function UpdateUserProfile($user_id, $pass1, $hideOffline, $theme, $language)
{
    global $cfg, $db;
    if (empty($hideOffline) || $hideOffline == "" || !isset($hideOffline)) {
        $hideOffline = "0";
    }
    // update values
    $rec = array();
    if ($pass1 != "") {
        $rec['password'] = md5($pass1);
        AuditAction($cfg["constants"]["update"], $cfg['_PASSWORD']);
    }
    $sql = "select * from tf_users where user_id = " . $db->qstr($user_id);
    $rs = $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    $rec['hide_offline'] = $hideOffline;
    $rec['theme'] = $theme;
    $rec['language_file'] = $language;
    $sql = $db->GetUpdateSQL($rs, $rec);
    if ($sql != "") {
        $result = $db->Execute($sql);
        if ($db->ErrorNo() != 0) {
            dbError($sql);
        }
        // flush session-cache
        cacheFlush($cfg["user"]);
    }
}
Beispiel #2
0
 function login($email, $password)
 {
     global $db;
     // Prepare e-mail address
     $email = $db->escape_string($email);
     $email = strtolower($email);
     $password = $db->escape_string($password);
     $email_part = explode("@", $email);
     $username = $email_part[0];
     $domain = $email_part[1];
     // Check e-mail address
     $sql = "SELECT `" . DBC_USERS_ID . "`, `" . DBC_USERS_PASSWORD . "` FROM `" . DBT_USERS . "` WHERE `" . DBC_USERS_USERNAME . "` = '{$username}' AND `" . DBC_USERS_DOMAIN . "` = '{$domain}' LIMIT 1;";
     if (!($result = $db->query($sql))) {
         dbError($db->error);
     }
     if ($result->num_rows === 1) {
         $userdata = $result->fetch_array(MYSQLI_ASSOC);
         $uid = $userdata[DBC_USERS_ID];
         $password_hash = $userdata[DBC_USERS_PASSWORD];
         // Check password
         if (crypt($password, $password_hash) === $password_hash) {
             // Password is valid, start a logged-in user session
             $this->loggedin = true;
             $_SESSION['uid'] = $uid;
             $_SESSION['email'] = $email;
             return true;
         } else {
             // Password is invalid
             return false;
         }
     } else {
         // User could not be found
         return false;
     }
 }
/**
 * Modify Cookie Host Information
 *
 * @param $cid
 * @param $newCookie
 */
function modCookieInfo($cid, $newCookie)
{
    global $db;
    $sql = "UPDATE tf_cookies SET host=" . $db->qstr($newCookie["host"]) . ", data=" . $db->qstr($newCookie["data"]) . " WHERE cid=" . $db->qstr($cid);
    $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
}
/**
 * get rss links
 *
 * @return array
 */
function GetRSSLinks()
{
    global $cfg, $db;
    $link_array = array();
    $sql = "SELECT rid, url FROM tf_rss ORDER BY rid";
    $link_array = $db->GetAssoc($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    return $link_array;
}
Beispiel #5
0
function dbQuery($query, $link = 'db_link'){

	global $link;

	$$link = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);

	if ($$link) mysql_select_db(DB_DATABASE);

		$result = mysql_query($query, $$link) or dbError($query, mysql_errno(), mysql_error());

	return $result;

}
Beispiel #6
0
 public static function Delete($lang)
 {
     global $DB;
     $DB->Query("SELECT * FROM `" . self::$table . "` WHERE `SID` = '" . sSql($lang) . "'");
     if (!$DB->numRows()) {
         return false;
     } else {
         $sql = "DELETE FROM `" . self::$table . "` WHERE `SID` = '" . sSql($lang) . "';";
         if ($DB->Query($sql)) {
             return true;
         } else {
             dbError($DB->Error());
             return false;
         }
     }
 }
 /**
  * prune database
  */
 function _maintenanceDatabasePrune()
 {
     global $cfg, $db;
     // output
     $this->_outputMessage("pruning database...\n");
     $this->_outputMessage("table : tf_log\n");
     // Prune LOG
     $this->_count = 0;
     $testTime = time() - $cfg['days_to_keep'] * 86400;
     // 86400 is one day in seconds
     $sql = "delete from tf_log where time < " . $db->qstr($testTime);
     $result = $db->Execute($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     $this->_count += $db->Affected_Rows();
     unset($result);
     $testTime = time() - $cfg['minutes_to_keep'] * 60;
     $sql = "delete from tf_log where time < " . $db->qstr($testTime) . " and action=" . $db->qstr($cfg["constants"]["hit"]);
     $result = $db->Execute($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     $this->_count += $db->Affected_Rows();
     unset($result);
     /* done */
     if ($this->_count > 0) {
         $this->_outputMessage("deleted entries from tf_log : " . $this->_count . "\n");
     } else {
         $this->_outputMessage("no entries deleted.\n");
     }
     $this->_outputMessage("prune database done.\n");
 }
 public static function Delete($ID)
 {
     global $DB;
     $DB->Query("SELECT * FROM `" . self::$table . "` WHERE `ID` = '" . sSql($ID) . "'");
     if (!$DB->numRows()) {
         return false;
     } else {
         $sql1 = "DELETE FROM `" . self::$table . "` WHERE `ID` = '" . sSql($ID) . "';";
         $sql2 = "DELETE FROM `" . self::$table_lang . "` WHERE `CATALOG_TYPE_ID` = '" . sSql($ID) . "';";
         if ($DB->Query($sql1) and $DB->Query($sql2)) {
             return true;
         } else {
             dbError($DB->Error());
             return false;
         }
     }
 }
Beispiel #9
0
function getDownloadFtpLogUsers($srchFile, $logNumber = "")
{
    global $cfg, $db, $dlLog;
    $userlist = array();
    $userRenamer = array();
    //xferlog or xferlog.0 (last month)
    //$ftplog = '/var/log/proftpd/xferlog'.$logNumber;
    $ftplog = "/var/log/pure-ftpd/stats_transfer{$logNumber}.log";
    if (!is_file($ftplog)) {
        return array();
    }
    //Search in Log (for old or external log insert, todo)
    $srchFile = str_replace($cfg["path"], '', $srchFile);
    //Search in cached db log array
    foreach ($dlLog as $row) {
        if ($row->file == $srchFile) {
            $userlist[$row->user_id] = htmlentities(substr($row->user_id, 0, 3), ENT_QUOTES);
        }
    }
    if (count($userlist) > 0) {
        return $userlist;
    }
    if (!file_exists($ftplog)) {
        return $userlist;
    }
    $userRenamer["root"] = "epsylon3";
    $cmdLog = "cat {$ftplog}|" . $cfg["bin_grep"] . ' ' . tfb_shellencode(str_replace(' ', '_', $srchFile));
    //.'|'.$cfg["bin_grep"]." -o -E ' r (.*) ftp'"
    $dlInfos = trim(@shell_exec($cmdLog));
    if ($dlInfos) {
        $ftpusers = explode("\n", $dlInfos);
        foreach ($ftpusers as $key => $value) {
            /* PROFTPD
            			$value=substr($value,4);
            			$time=strtotime(substr($value,0,20));
            			$value=substr($value,21);
            			$lineWords=explode(' ',$value);
            			$hostname=$lineWords[1];
            			$size=0+($lineWords[2]);
            			$username=$lineWords[count($lineWords)-5];
            			$complete=$lineWords[count($lineWords)-1]; */
            /* pure-ftpd (stats:/var/log/pure-ftpd/stats_transfer.log) */
            $lineWords = explode(' ', $value);
            $time = 0 + $lineWords[0];
            $username = $lineWords[2];
            $hostname = $lineWords[3];
            $complete = str_replace("D", "c", $lineWords[4]);
            $size = 0.0 + $lineWords[5];
            //die( "<pre>$size-$complete-$hostname-$username-$time\n$value\n</pre>");
            if ($complete == "c") {
                //rename user ?
                if (array_key_exists($username, $userRenamer)) {
                    $username = $userRenamer[$username];
                }
                if (!array_key_exists($username, $userlist)) {
                    $srchAction = "File Download (FTP)";
                    $db->Execute("INSERT INTO tf_log (user_id,file,action,ip,ip_resolved,user_agent,time)" . " VALUES (" . $db->qstr($username) . "," . $db->qstr($srchFile) . "," . $db->qstr($srchAction) . "," . $db->qstr('FTP') . "," . $db->qstr($hostname) . "," . $db->qstr('FTP') . "," . $time . ")");
                    if ($db->ErrorNo() != 0) {
                        dbError($sql);
                    }
                }
                $userlist[$username] = substr($username, 0, 3);
            }
        }
    }
    return $userlist;
}
/**
 * Delete Profile Information
 *
 * @param $pid
 */
function deleteProfileInfo($pid)
{
    global $db;
    $sql = "DELETE FROM tf_trprofiles WHERE id=" . $db->qstr($pid);
    $result = $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
}
/**
 * Get Message data in an array
 *
 * @param $mid
 * @return array
 */
function GetMessage($mid)
{
    global $cfg, $db;
    $sql = "select from_user, message, ip, time, isnew, force_read from tf_messages where mid=" . $db->qstr($mid) . " and to_user="******"user"]);
    $rtnValue = $db->GetRow($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    return $rtnValue;
}
Beispiel #12
0
function getComments($dbconn, $xmlDoc, $post_id)
{
    $parentNode = $xmlDoc->createElement('comments');
    $query = "select * from comments where post_id = " . dbEsc($post_id) . " order by date DESC";
    $result = mysql_query($query);
    if (!$result) {
        $statusNode = $xmlDoc->createElement('getComments_status', $query);
        dbError($xmlDoc, $parentNode, mysql_error());
    } else {
        $statusNode = $xmlDoc->createElement('query_status', 'success');
    }
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $query2 = "SELECT username FROM users WHERE user_id = " . $row['user_id'];
        $result2 = mysql_query($query2);
        $row2 = mysql_fetch_array($result2, MYSQL_ASSOC);
        $theChildNode = $xmlDoc->createElement('comment');
        $theChildNode->setAttribute('username', $row2['username']);
        $theChildNode->setAttribute('comment', $row['comment']);
        $theChildNode->setAttribute('date', $row['date']);
        $parentNode->appendChild($theChildNode);
    }
    $parentNode->appendChild($statusNode);
    return $parentNode;
}
 /**
  * method to get data from URL -- uses timeout and user agent
  *
  * @param $get_url
  * @param $get_referer
  * @return string
  */
 function instance_getData($get_url, $get_referer = "")
 {
     global $cfg, $db;
     // set fields
     $this->url = $get_url;
     $this->referer = $get_referer;
     // (re)set state
     $this->state = SIMPLEHTTP_STATE_NULL;
     // (re-)set some vars
     $this->cookie = "";
     $this->request = "";
     $this->responseBody = "";
     $this->responseHeaders = array();
     $this->gotResponseLine = false;
     $this->status = "";
     $this->errstr = "";
     $this->errno = 0;
     $this->socket = 0;
     /**
      * array of URL component parts for use in raw HTTP request
      * @param	array	$domain
      */
     $domain = parse_url($this->url);
     if (empty($domain) || empty($domain['scheme']) || $domain['scheme'] != 'http' && $domain['scheme'] != 'https' || empty($domain['host'])) {
         $this->state = SIMPLEHTTP_STATE_ERROR;
         $msg = "Error fetching " . $this->url . ".  This is not a valid HTTP/HTTPS URL.";
         array_push($this->messages, $msg);
         AuditAction($cfg["constants"]["error"], $msg);
         return $data = "";
     }
     $secure = $domain['scheme'] == 'https';
     if ($secure && !$this->_canTLS()) {
         $this->state = SIMPLEHTTP_STATE_ERROR;
         $msg = "Error fetching " . $this->url . ".  PHP does not have module OpenSSL, which is needed for HTTPS.";
         array_push($this->messages, $msg);
         AuditAction($cfg["constants"]["error"], $msg);
         return $data = "";
     }
     // get-command
     if (!array_key_exists("path", $domain)) {
         $domain["path"] = "/";
     }
     $this->getcmd = $domain["path"];
     if (!array_key_exists("query", $domain)) {
         $domain["query"] = "";
     }
     // append the query string if included:
     $this->getcmd .= !empty($domain["query"]) ? "?" . $domain["query"] : "";
     // Check to see if cookie required for this domain:
     $sql = "SELECT c.data AS data FROM tf_cookies AS c LEFT JOIN tf_users AS u ON ( u.uid = c.uid ) WHERE u.user_id = " . $db->qstr($cfg["user"]) . " AND c.host = " . $db->qstr($domain['host']);
     $this->cookie = $db->GetOne($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     if (!array_key_exists("port", $domain)) {
         $domain["port"] = $secure ? 443 : 80;
     }
     // Fetch the data using fsockopen():
     $this->socket = @fsockopen(($secure ? 'tls://' : '') . $domain["host"], $domain["port"], $this->errno, $this->errstr, $this->timeout);
     if (!empty($this->socket)) {
         // Write the outgoing HTTP request using cookie info
         // Standard HTTP/1.1 request looks like:
         //
         // GET /url/path/example.php HTTP/1.1
         // Host: example.com
         // Accept: */*
         // Accept-Language: en-us
         // User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1) Gecko/20061010 Firefox/2.0
         // Connection: Close
         // Cookie: uid=12345;pass=asdfasdf;
         //
         //$this->request  = "GET " . ($this->httpVersion=="1.1" ? $this->getcmd : $this->url ). " HTTP/" . $this->httpVersion ."\r\n";
         $this->request = "GET " . $this->_fullURLEncode($this->getcmd) . " HTTP/" . $this->httpVersion . "\r\n";
         $this->request .= !empty($this->referer) ? "Referer: " . $this->referer . "\r\n" : "";
         $this->request .= "Accept: */*\r\n";
         $this->request .= "Accept-Language: en-us\r\n";
         $this->request .= "User-Agent: " . $this->userAgent . "\r\n";
         $this->request .= "Host: " . $domain["host"] . "\r\n";
         if ($this->httpVersion == "1.1") {
             $this->request .= "Connection: Close\r\n";
         }
         if (!empty($this->cookie)) {
             $this->request .= "Cookie: " . $this->cookie . "\r\n";
         }
         $this->request .= "\r\n";
         // Send header packet information to server
         fputs($this->socket, $this->request);
         // socket-options
         stream_set_timeout($this->socket, $this->timeout);
         // meta-data
         $info = stream_get_meta_data($this->socket);
         // Get response headers:
         while (!$info['timed_out'] && ($line = @fgets($this->socket, 500000))) {
             // First empty line/\r\n indicates end of response headers:
             if ($line == "\r\n") {
                 break;
             }
             if (!$this->gotResponseLine) {
                 preg_match("@HTTP/[^ ]+ (\\d\\d\\d)@", $line, $matches);
                 // TODO: Use this to see if we redirected (30x) and follow the redirect:
                 $this->status = $matches[1];
                 $this->gotResponseLine = true;
                 continue;
             }
             // Get response headers:
             preg_match("/^([^:]+):\\s*(.*)/", trim($line), $matches);
             $this->responseHeaders[strtolower($matches[1])] = $matches[2];
             // meta-data
             $info = stream_get_meta_data($this->socket);
         }
         if ($this->httpVersion == "1.1" && isset($this->responseHeaders["transfer-encoding"]) && !empty($this->responseHeaders["transfer-encoding"])) {
             /*
             // NOT CURRENTLY WORKING, USE HTTP/1.0 ONLY UNTIL THIS IS FIXED!
             */
             // Get body of HTTP response:
             // Handle chunked encoding:
             /*
             		length := 0
             		read chunk-size, chunk-extension (if any) and CRLF
             		while (chunk-size > 0) {
             		   read chunk-data and CRLF
             		   append chunk-data to entity-body
             		   length := length + chunk-size
             		   read chunk-size and CRLF
             		}
             */
             // Used to count total of all chunk lengths, the content-length:
             $chunkLength = 0;
             // Get first chunk size:
             $chunkSize = hexdec(trim(fgets($this->socket)));
             // 0 size chunk indicates end of content:
             while (!$info['timed_out'] && $chunkSize > 0) {
                 // Read in up to $chunkSize chars:
                 $line = @fgets($this->socket, $chunkSize);
                 // Discard crlf after current chunk:
                 fgets($this->socket);
                 // Append chunk to response body:
                 $this->responseBody .= $line;
                 // Keep track of total chunk/content length:
                 $chunkLength += $chunkSize;
                 // Read next chunk size:
                 $chunkSize = hexdec(trim(fgets($this->socket)));
                 // meta-data
                 $info = stream_get_meta_data($this->socket);
             }
             $this->responseHeaders["content-length"] = $chunkLength;
         } else {
             while (!$info['timed_out'] && ($line = @fread($this->socket, 500000))) {
                 $this->responseBody .= $line;
                 // meta-data
                 $info = stream_get_meta_data($this->socket);
             }
         }
         @fclose($this->socket);
         // Close our connection
     } else {
         return "Error fetching " . $this->url . ".  PHP Error No=" . $this->errno . " . PHP Error String=" . $this->errstr;
     }
     /*
     Check if we need to follow a redirect:
     http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
     
     Each of these HTTP response status codes indicates a redirect and the
     content should be included in the Location field/header:
     
     300 Multiple Locations
     301 Moved Permanently
     302 Found (has a temp location somewhere else on server)
     303 See Other (should be fetched using GET, probably not relevant but won't hurt to include it)
     307 Temporary Redirect
     */
     if (preg_match("/^30[0-37]\$/D", $this->status) > 0) {
         // Check we're not already over the max redirects limit:
         if ($this->redirectCount > $this->redirectMax) {
             $this->state = SIMPLEHTTP_STATE_ERROR;
             $msg = "Error fetching " . $this->url . ".  The maximum number of allowed redirects ";
             $msg .= "(" . $this->redirectMax . ") was exceeded.  Last followed URL was: " . $this->redirectUrl;
             array_push($this->messages, $msg);
             AuditAction($cfg["constants"]["error"], $msg);
             return $data = "";
         } else {
             $this->redirectCount++;
             // Check we have a location to get redirected content:
             if (isset($this->responseHeaders["location"]) && !empty($this->responseHeaders["location"])) {
                 // 3 different cases for location header:
                 // - full URL (scheme://.../foobar) -- just go to that URL,
                 // - absolute URL (/foobar) -- keep everything up to host/port,
                 //                             and replace end of request,
                 // - relative URL (foobar) -- keep everything up to last component of path,
                 //                            and replace end of request.
                 $redirectLocation = $this->responseHeaders["location"];
                 if (preg_match('#^(ht|f)tp(s)?://#', $redirectLocation) > 0) {
                     // Case 1: full URL. Just use it.
                     $this->redirectUrl = $redirectLocation;
                 } else {
                     // Cases 2 or 3: partial URL.
                     // Keep scheme/user/pass/host/port of current request.
                     $redirectUrlBase = $domain['scheme'] . '://' . (isset($domain['user']) || isset($domain['pass']) ? (isset($domain['user']) ? $domain['user'] : '') . (isset($domain['pass']) ? ':' . $domain['pass'] : '') . '@' : '') . $domain['host'] . (isset($domain['port']) ? ':' . $domain['port'] : '');
                     if ($redirectLocation[0] == '/') {
                         // Case 2: absolute URL.
                         // Append it to current request's base.
                         $this->redirectUrl = $redirectUrlBase . $redirectLocation;
                     } else {
                         // Case 3: relative URL.
                         // Append it to current request's base + path stripped of its last component.
                         $domainPathAry = explode('/', $domain['path']);
                         array_splice($domainPathAry, -1, 1, $redirectLocation);
                         $domainPathNew = implode('/', $domainPathAry);
                         $this->redirectUrl = $redirectUrlBase . (isset($domainPathNew) && strlen($domainPathNew) > 0 && $domainPathNew[0] == '/' ? '' : '/') . $domainPathNew;
                     }
                 }
             } else {
                 $msg = "Error fetching " . $this->url . ".  A redirect status code (" . $this->status . ")";
                 $msg .= " was sent from the remote webserver, but no location header was set to obtain the redirected content from.";
                 AuditAction($cfg["constants"]["error"], $msg);
                 array_push($this->messages, $msg);
                 return $data = "";
             }
             $this->instance_getData($this->redirectUrl);
         }
     }
     // Trim any extraneous linefeed chars:
     $this->responseBody = trim($this->responseBody, "\r\n");
     // If a filename is associated with this content, assign it to $filename
     if (isset($this->responseHeaders["content-disposition"]) && !empty($this->responseHeaders["content-disposition"])) {
         // Content-disposition: attachment; filename="nameoffile":
         // Don't think single quotes can be used to escape filename here, but just in case check for ' and ":
         if (preg_match("/filename=(['\"])([^\\1]+)\\1/", $this->responseHeaders["content-disposition"], $matches)) {
             if (isset($matches[2]) && !empty($matches[2])) {
                 $file_name = $matches[2];
                 // Only accept filenames, not paths:
                 if (!preg_match("@/@", $file_name)) {
                     $this->filename = $file_name;
                 }
             }
         }
     }
     // state
     $this->state = SIMPLEHTTP_STATE_OK;
     // return content
     return $this->responseBody;
 }
/**
 * reset Owner
 *
 * @param $transfer
 * @return string
 */
function resetOwner($transfer)
{
    global $cfg, $db, $transfers;
    // log entry has expired so we must renew it
    $rtnValue = "n/a";
    if (file_exists($cfg["transfer_file_path"] . $transfer . ".stat")) {
        $sf = new StatFile($transfer);
        if (IsUser($sf->transferowner)) {
            $rtnValue = $sf->transferowner;
        } else {
            $rtnValue = GetSuperAdmin();
        }
        /* no owner found, so the super admin will now own it */
        // add entry to the log
        $sql = "INSERT INTO tf_log (user_id,file,action,ip,ip_resolved,user_agent,time)" . " VALUES (" . $db->qstr($rtnValue) . "," . $db->qstr($transfer) . "," . $db->qstr($cfg["constants"]["reset_owner"]) . "," . $db->qstr($cfg['ip']) . "," . $db->qstr($cfg['ip_resolved']) . "," . $db->qstr($cfg['user_agent']) . "," . $db->qstr(time()) . ")";
        $result = $db->Execute($sql);
        if ($db->ErrorNo() != 0) {
            dbError($sql);
        }
    }
    $transfers['owner'][$transfer] = $rtnValue;
    return $rtnValue;
}
/**
 * Change User Level
 *
 * @param $user_id
 * @param $level
 */
function changeUserLevel($user_id, $level)
{
    global $db;
    $sql = "select * from tf_users where user_id = " . $db->qstr($user_id);
    $rs = $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    $rec = array('user_level' => $level);
    $sql = $db->GetUpdateSQL($rs, $rec);
    $result = $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
}
/**
 * update the Email
 *
 * @param $user_id string
 * @param $email string
 * @return boolean
 */
function UpdateUserEmail($user_id, $email)
{
    global $db;
    $sql = "UPDATE tf_users SET email_address = " . $db->qstr($email) . " WHERE user_id = " . $db->qstr($user_id);
    $rs = $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
        die;
        return false;
    }
    return true;
}
 /**
  * save settings
  */
 function settingsSave()
 {
     global $db;
     // Messy - a not exists would prob work better
     deleteTransferSettings($this->transfer);
     // insert
     $sql = "INSERT INTO tf_transfers " . "(" . "transfer," . "type," . "client," . "hash," . "datapath," . "savepath," . "running," . "rate," . "drate," . "maxuploads," . "superseeder," . "runtime," . "sharekill," . "minport," . "maxport," . "maxcons," . "rerequest" . ") VALUES (" . $db->qstr($this->transfer) . "," . $db->qstr($this->type) . "," . $db->qstr($this->client) . "," . $db->qstr($this->hash) . "," . $db->qstr($this->datapath) . "," . $db->qstr($this->savepath) . "," . $db->qstr($this->running) . "," . $db->qstr($this->rate) . "," . $db->qstr($this->drate) . "," . $db->qstr($this->maxuploads) . "," . $db->qstr($this->superseeder) . "," . $db->qstr($this->runtime) . "," . $db->qstr($this->sharekill) . "," . $db->qstr($this->minport) . "," . $db->qstr($this->maxport) . "," . $db->qstr($this->maxcons) . "," . $db->qstr($this->rerequest) . ")";
     $db->Execute($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     // set transfers-cache
     cacheTransfersSet();
     return true;
 }
/**
 * resets totals of a transfer
 *
 * @param $transfer name of the transfer
 * @param $delete boolean if to delete meta-file
 * @return array
 */
function resetTransferTotals($transfer, $delete = false)
{
    global $cfg, $db, $transfers;
    $msgs = array();
    $tid = getTransferHash($transfer);
    // delete meta-file
    if ($delete) {
        $ch = ClientHandler::getInstance(getTransferClient($transfer));
        $ch->delete($transfer);
        if (count($ch->messages) > 0) {
            $msgs = array_merge($msgs, $ch->messages);
        }
    } else {
        // reset in stat-file
        $sf = new StatFile($transfer, getOwner($transfer));
        $sf->uptotal = 0;
        $sf->downtotal = 0;
        $sf->write();
    }
    // reset in db
    $sql = "DELETE FROM tf_transfer_totals WHERE tid = " . $db->qstr($tid);
    $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    // set transfers-cache
    cacheTransfersSet();
    return $msgs;
}
 /**
  * Dump Database
  *
  * @param $type
  * @return mixed
  */
 function _dump($type)
 {
     global $cfg, $db;
     switch ($type) {
         case "settings":
             $sql = "SELECT tf_key, tf_value FROM tf_settings";
             break;
         case "users":
             $sql = "SELECT uid, user_id FROM tf_users";
             break;
         default:
             $this->_outputError("invalid type : " . $type . "\n");
             return false;
     }
     $recordset = $db->Execute($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     $content = "";
     while (list($a, $b) = $recordset->FetchRow()) {
         $content .= $a . _DUMP_DELIM . $b . "\n";
     }
     echo $content;
     return $content != "";
 }
Beispiel #20
0
<?php

if (isset($_GET['deleted']) && $_GET['deleted'] == "1") {
    add_message("success", "Domain deleted successfully.");
} else {
    if (isset($_GET['created']) && $_GET['created'] == "1") {
        add_message("success", "Domain created successfully.");
    } else {
        if (isset($_GET['adm_del']) && $_GET['adm_del'] == "1") {
            add_message("fail", "Domain could not be deleted because admin account would be affected.");
        }
    }
}
$sql = "SELECT d.*, COUNT(DISTINCT u.`" . DBC_USERS_ID . "`) AS `user_count`, COUNT(DISTINCT r.`" . DBC_ALIASES_ID . "`) AS `redirect_count`\nFROM `" . DBT_DOMAINS . "` AS d\nLEFT JOIN `" . DBT_USERS . "` AS u ON (u.`" . DBC_USERS_DOMAIN . "` = d.`" . DBC_DOMAINS_DOMAIN . "`)\nLEFT JOIN `" . DBT_ALIASES . "` AS r ON (r.`" . DBC_ALIASES_SOURCE . "` LIKE CONCAT('%@', d.`" . DBC_DOMAINS_DOMAIN . "`))\nGROUP BY d.`" . DBC_DOMAINS_DOMAIN . "`\nORDER BY `" . DBC_DOMAINS_DOMAIN . "` ASC;";
if (!($result = $db->query($sql))) {
    dbError($db->error);
}
?>

<h1>Domains</h1>

<div class="buttons">
	<a class="button" href="<?php 
echo url('admin/createdomain');
?>
">Create new domain</a>
</div>

<?php 
output_messages();
?>
Beispiel #21
0
 /**
  * Gets upload/download usage for all users starting at timestamp from SQL
  *
  * @param $start
  * @param $period
  */
 function _getUsage($start, $period)
 {
     global $db;
     $sql = "SELECT user_id, SUM(download) AS download, SUM(upload) AS upload FROM tf_xfer WHERE date >= " . $db->qstr($start) . " AND user_id != '' GROUP BY user_id";
     $rtnValue = $db->GetAll($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     foreach ($rtnValue as $row) {
         $this->_sumUsage($row[0], $row[1], $row[2], $period);
     }
 }
Beispiel #22
0
function dbNumRows($sql)
{
    dbLog($sql);
    if (!($result = mysql_query($sql))) {
        dbError($sql);
    }
    return mysql_num_rows($result);
}
/**
 * resets totals of a transfer
 *
 * @param $transfer name of the transfer
 * @param $delete boolean if to delete meta-file
 * @return array
 */
function resetTransferTotals($transfer, $delete = false)
{
    global $cfg, $db, $transfers;
    $msgs = array();
    $tid = getTransferHash($transfer);
    $client = getTransferClient($transfer);
    // delete meta-file
    if ($delete) {
        $ch = ClientHandler::getInstance($client);
        $ch->delete($transfer);
        if (count($ch->messages) > 0) {
            $msgs = array_merge($msgs, $ch->messages);
        }
    } else {
        // reset in stat-file
        $sf = new StatFile($transfer, getOwner($transfer));
        $sf->uptotal = 0;
        $sf->downtotal = 0;
        $sf->write();
        if ($client == "vuzerpc") {
            require_once "inc/functions/functions.rpc.vuze.php";
            vuzeResetUpload($tid);
        }
    }
    // reset in db
    $uid = (int) getTransferOwnerID($transfer);
    $sql = "UPDATE tf_transfer_totals SET uptotal=0 WHERE tid = " . $db->qstr($tid) . " AND uid IN (0,{$uid})";
    $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    // set transfers-cache
    cacheTransfersSet();
    return $msgs;
}
/**
 * This method adds a Transmission transfer for a certain user in database
 *
 * @return array with uid and transmission transfer hash
 * TODO: check if $tid is filled in and return error
 */
function addTransmissionTransferToDB($uid = 0, $tid)
{
    global $db;
    $retVal = array();
    $uid = (int) $uid;
    $sql = "DELETE FROM tf_transmission_user WHERE uid={$uid} AND tid='{$tid}'";
    $recordset = $db->Execute($sql);
    $sql = "INSERT INTO tf_transmission_user (uid,tid) VALUES ({$uid},'{$tid}')";
    $recordset = $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    /*return $retVal;*/
}
function loadUserSettingsToConfig($uid)
{
    global $cfg, $db;
    // get user-settings from db and set in global cfg-array
    $sql = "SELECT tf_key, tf_value FROM tf_settings_user WHERE uid = " . $db->qstr($uid);
    $recordset = $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    if (isset($recordset) && $recordset->NumRows() > 0) {
        while (list($key, $value) = $recordset->FetchRow()) {
            $cfg[$key] = $value;
        }
    }
    // return
    return true;
}
 public function setPropertyValue($elementID, $propertyCODE, $propertyValue)
 {
     global $DB;
     $arUpd = array("VALUE" => $propertyValue);
     if (is_numeric($propertyCODE)) {
         $propID = intVal($propertyCODE);
     } else {
         $propID = self::GetPropIDByCODE($propertyCODE);
     }
     $sql_props = updSql(self::$table_props_values, $arUpd) . " WHERE `CATALOG_ELEMENT_ID` = '" . intVal($elementID) . "' AND `CATALOG_PROPERTY_ID` = " . intVal($propID) . ";";
     if ($DB->Query($sql_props)) {
         return true;
     } else {
         dbError($DB->Error());
         return false;
     }
 }
Beispiel #27
0
/**
 * Prepare a statement, but in a way that checks the result, and errors out when it fails.
 * @param mysqli $db
 * @param string $sql
 * @return mysqli_stmt
 */
function checkPrepare($db, $query)
{
    $result = $db->prepare($query);
    if ($result === FALSE) {
        dbError($db);
    }
    return $result;
}
 /**
  * Обновление осн. св-ва элемента каталога
  * @param int $ID
  * @param string $propertyCODE
  * @param string $propertyValue
  */
 public function setFieldValue($ID, $propertyCODE, $propertyValue)
 {
     global $DB;
     $sql = updSql(self::$table, array($propertyCODE => $propertyValue)) . " WHERE `ID` = '" . intVal($ID) . "';";
     if ($DB->Query($sql)) {
         return true;
     } else {
         dbError($DB->Error());
         return false;
     }
 }
     $tmpl->setvar('xfer_week', tmplGetXferBar($cfg['xfer_week'], $xfer_total['week']['total'], $cfg['_XFERTHRU'] . ' ' . $cfg['week_start'] . ':'));
 }
 $monthStart = strtotime(date('Y-m-') . $cfg['month_start']);
 $monthText = date('j') < $cfg['month_start'] ? date('M�j', strtotime('-1 Day', $monthStart)) : date('M�j', strtotime('+1 Month -1 Day', $monthStart));
 if ($cfg['xfer_month']) {
     $tmpl->setvar('xfer_month', tmplGetXferBar($cfg['xfer_month'], $xfer_total['month']['total'], $cfg['_XFERTHRU'] . ' ' . $monthText . ':'));
 }
 if ($cfg['xfer_total']) {
     $tmpl->setvar('xfer_total', tmplGetXferBar($cfg['xfer_total'], $xfer_total['total']['total'], $cfg['_TOTALXFER'] . ':'));
 }
 if ($cfg['enable_public_xfer'] == 1 || $cfg['isAdmin']) {
     $tmpl->setvar('show_xfer', 1);
     $sql = 'SELECT user_id FROM tf_users ORDER BY user_id';
     $rtnValue = $db->GetCol($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     $xfer = Xfer::getStats();
     $user_list = array();
     foreach ($rtnValue as $user_id) {
         array_push($user_list, array('user_id' => $user_id, 'total' => formatFreeSpace(@$xfer["{$user_id}"]['total']['total'] / 1048576), 'month' => formatFreeSpace(@$xfer["{$user_id}"]['month']['total'] / 1048576), 'week' => formatFreeSpace(@$xfer["{$user_id}"]['week']['total'] / 1048576), 'day' => formatFreeSpace(@$xfer["{$user_id}"]['day']['total'] / 1048576)));
     }
     $tmpl->setloop('user_list', $user_list);
     $tmpl->setvar('total_total', formatFreeSpace(@$xfer_total['total']['total'] / 1048576));
     $tmpl->setvar('total_month', formatFreeSpace(@$xfer_total['month']['total'] / 1048576));
     $tmpl->setvar('total_week', formatFreeSpace(@$xfer_total['week']['total'] / 1048576));
     $tmpl->setvar('total_day', formatFreeSpace(@$xfer_total['day']['total'] / 1048576));
     //
     $username = tfb_getRequestVar('user');
     $tmpl->setvar('user', $username);
     $_month = tfb_getRequestVar('month');
Beispiel #30
0
function dbError()
{
    $conexion = dbConnect();
    return mysqli_error($conexion);
}
//Ejecución de consultas
function dbQuery($query)
{
    $conexion = dbConnect();
    $result = mysqli_query($conexion, $query);
    return $result;
}
//Insercion de datos
if ($tipo == "short") {
    $query = "SELECT `FECHA`,`HORA`,`COD_ALARM` FROM `" . nombreTabla() . "` ORDER BY id DESC LIMIT 1";
} else {
    $query = "SELECT * FROM `" . nombreTabla() . "`  LEFT JOIN `MTU_ALARMAS` ON " . nombreTabla() . ".COD_ALARM=MTU_ALARMAS.Codigo ORDER  BY id DESC LIMIT 1";
}
//$query = "SELECT * FROM `".nombreTabla()."` ORDER  BY id DESC LIMIT 1";
//$query = "SELECT * FROM `MTU_ALARMAS` WHERE `Codigo`='23'";
$result = dbQuery($query);
$json_array = array();
if (!$result) {
    $error = dbError();
    echo $error;
} else {
    while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
        array_push($json_array, $row);
    }
    echo str_replace(array('[', ']'), "", json_encode($json_array, JSON_UNESCAPED_UNICODE));
}