public function testMultipleRowInsert()
 {
     $query = SQLInsert::create('"SQLInsertTestBase"');
     $query->addRow(array('"Title"' => 'First Object', '"Age"' => 10, '"Description"' => 'First the worst'));
     $query->addRow(array('"Title"' => 'Second object', '"Age"' => 12));
     $sql = $query->sql($parameters);
     // Only test this case if using the default query builder
     if (get_class(DB::get_conn()->getQueryBuilder()) === 'DBQueryBuilder') {
         $this->assertSQLEquals('INSERT INTO "SQLInsertTestBase" ("Title", "Age", "Description") VALUES (?, ?, ?), (?, ?, ?)', $sql);
     }
     $this->assertEquals(array('First Object', 10, 'First the worst', 'Second object', 12, null), $parameters);
     $query->execute();
     $this->assertEquals(2, DB::affected_rows());
     // Check inserted objects are correct
     $firstObject = DataObject::get_one('SQLInsertTestBase', array('"Title"' => 'First Object'), false);
     $this->assertNotEmpty($firstObject);
     $this->assertEquals($firstObject->Title, 'First Object');
     $this->assertEquals($firstObject->Age, 10);
     $this->assertEquals($firstObject->Description, 'First the worst');
     $secondObject = DataObject::get_one('SQLInsertTestBase', array('"Title"' => 'Second object'), false);
     $this->assertNotEmpty($secondObject);
     $this->assertEquals($secondObject->Title, 'Second object');
     $this->assertEquals($secondObject->Age, 12);
     $this->assertEmpty($secondObject->Description);
 }
Example #2
0
 function __construct()
 {
     global $oDB;
     Form::Form('MoveNewsCatForm');
     $catid = Url::get('id', 0);
     if ($catid) {
         $category = DB::select('news_categories', $catid);
         $cmd = Url::get('cmd');
         if ($category) {
             if ($cmd == 'move_up') {
                 if ($category['position'] > 1) {
                     DB::query("UPDATE news_categories SET position=position-1 WHERE id=" . $category['id']);
                     if (DB::affected_rows()) {
                         DB::query("UPDATE news_categories SET position=position+1 WHERE id!=" . $category['id'] . " AND position=" . ($category['position'] - 1));
                     }
                 }
             } else {
                 if ($category['position'] < DB::count("news_categories")) {
                     DB::query("UPDATE news_categories SET position=position+1 WHERE id=" . $category['id']);
                     if (DB::affected_rows()) {
                         DB::query("UPDATE news_categories SET position=position-1 WHERE id!=" . $category['id'] . " AND position=" . ($category['position'] + 1));
                     }
                 }
             }
             AZLib::getNewsCats(1);
         }
     }
     Url::redirect_current();
 }
Example #3
0
	static function query($sql)
	{
		if(func_num_args()>1)	$sql = self::prepare($args = func_get_args());
		
		$st = microtime(true);
		$result = mysql_query($sql);
		if(mysql_error()) DB::error($sql);
		self::$affected_rows = mysql_affected_rows();
		self::$insert_id = mysql_insert_id();
		
		/*
		if(microtime(true) - $st > 1)
		{
			$_q = preg_replace('/[\d,]+/', 'N', $sql);
			$_uri = Request::escape( $_SERVER['REQUEST_URI'] );
			$_long_query = DB::prepare("insert into long_query (q,uri,st) values (?,?,?i)", $_q, $_uri, microtime(true)-$st);
			mysql_query($_long_query); // служедбный запрос, чтобы не сбил нам insert_id и affected_rows
		}
		*/
		
		// echo $sql."<br>\n";
		
		if(microtime(true)-$st>0.1 && $_SERVER['REMOTE_ADDR']=='93.125.42.170') $GLOBALS['queries'][] = Array("time"=>(microtime(true)-$st), "sql"=>$sql);
		
		return $result;
	}
Example #4
0
 function sql_runquery()
 {
     global $_G;
     if ($_GET['onsubmit'] && check() && $_GET['query_string']) {
         $query_string = trim($_GET['query_string']);
         if (strstr($query_string, ';')) {
             $query_string = explode(';', $query_string);
         }
         $query_string = (array) $query_string;
         $update = true;
         $msg = '';
         $query_string = array_filter($query_string);
         $query_string = array_unique($query_string);
         $i = 0;
         foreach ($query_string as $k => $v) {
             if ($v) {
                 $cmd = trim(strtoupper(substr($v, 0, strpos($v, ' '))));
                 if ($cmd === 'UPDATE' || $cmd === 'DELETE') {
                     $update = false;
                 }
                 DB::query($v, array(), $update);
                 $msg .= '<p>' . $v . ',影响行数:' . DB::affected_rows() . '</p>';
                 $i++;
             }
         }
         cpmsg('成功执行:' . $i . '条SQL语句' . $msg, 'success', 'm=' . __CLASS__ . '&a=' . __FUNCTION__, '', "<p claaa='red'>如果更改了某些系统数据,请手动更新系统缓存</p>");
         return false;
     }
     $this->show();
 }
Example #5
0
 function statistic()
 {
     if (empty($this->tableName)) {
         return false;
     }
     $ip = $GLOBALS['_J']['client_ip'];
     $timestamp = time();
     $sql = "UPDATE " . $this->tableName . "\r\n\t\t\tset\r\n\t\t\t`times`=`times`+1,\r\n\t\t\t`last_visit`='{$timestamp}'\r\n\t\t\twhere `name`='{$this->robotName}'";
     DB::query($sql, 'SILENT');
     $result = DB::affected_rows();
     if ($result < 1) {
         $sql = "insert into {$this->tableName}(`name`,`times`,`first_visit`,`last_visit`,`agent`)\r\n\t\t\tvalues('{$this->robotName}','1','{$timestamp}','{$timestamp}','{$this->agent}')";
         DB::query($sql);
         $result = (bool) DB::affected_rows();
     }
     if ($result) {
         $sql = "\r\n\t\t\tUPDATE {$this->tableName}_ip\r\n\t\t\tset\r\n\t\t\t\t`times`=`times`+1,\r\n\t\t\t\t`last_visit`='{$timestamp}'\r\n\t\t\twhere\r\n\t\t\t\t`ip`='{$ip}'\r\n\t\t\t";
         DB::query($sql, 'SILENT');
         $result = DB::affected_rows();
         if ($result < 1) {
             $sql = "insert into\r\n\t\t\t\t{$this->tableName}_ip(`ip`,`name`,`times`,`first_visit`,`last_visit`)\r\n\t\t\t\tvalues('{$ip}','{$this->robotName}','1','{$timestamp}','{$timestamp}')";
             DB::query($sql);
             $result = (bool) DB::affected_rows();
         }
     }
     return $result;
 }
 public function update_onlinetime($uid, $total, $thismonth, $lastupdate)
 {
     if ($uid = intval($uid)) {
         DB::query("UPDATE " . DB::table('common_onlinetime') . "\r\n\t\t\tSET total=total+'{$total}', thismonth=thismonth+'{$thismonth}', lastupdate='" . $lastupdate . "' WHERE " . DB::field($this->_pk, $uid));
         return DB::affected_rows();
     }
     return false;
 }
Example #7
0
	/**
	 * activate area participation
	 */
	public function activate_participation() {
		$sql = "UPDATE participant SET activated=current_date WHERE member=".intval(Login::$member->id)." AND area=".intval($this->id);
		$result = DB::query($sql);
		if ( !DB::affected_rows($result) ) {
			$sql = "INSERT INTO participant (member, area) VALUES (".intval(Login::$member->id).", ".intval($this->id).")";
			DB::query($sql);
		}
		$this->update_participants_cache();
	}
Example #8
0
 public function write($sess_id, $sess_data)
 {
     global $user;
     // If saving of session data is disabled or if the client doesn't have a session,
     // and one isn't being created ($value), do nothing. This keeps crawlers out of
     // the session table. This reduces memory and server load, and gives more useful
     // statistics. We can't eliminate anonymous session table rows without breaking
     // the throttle module and the "Who's Online" block.
     if (!$this->is_save_session() || empty($_COOKIE[session_name()]) && empty($sess_data)) {
         return TRUE;
     }
     $this->_db->query("UPDATE `{$this->_dbtable}` SET `uid`=%d, `lasttime`=%d, `lastip`='%s', `data`='%s' WHERE `sid`='%s'", $user->uid, $this->_timestamp, get_clientip(), $sess_data, $sess_id);
     if (!$this->_db->affected_rows()) {
         //update error, indicating no the session
         $this->_db->query("INSERT INTO `{$this->_dbtable}` (`sid`, `uid`, `lasttime`, `lastip`, `data`) VALUES('%s', %d, %d, '%s', '%s')", $sess_id, $user->uid, $this->_timestamp, get_clientip(), $sess_data);
     }
     return TRUE;
 }
 public function testBasicUpdate()
 {
     $query = SQLUpdate::create()->setTable('"SQLUpdateTestBase"')->assign('"Description"', 'Description 1a')->addWhere(array('"Title" = ?' => 'Object 1'));
     $sql = $query->sql($parameters);
     // Check SQL
     $this->assertSQLEquals('UPDATE "SQLUpdateTestBase" SET "Description" = ? WHERE ("Title" = ?)', $sql);
     $this->assertEquals(array('Description 1a', 'Object 1'), $parameters);
     // Check affected rows
     $query->execute();
     $this->assertEquals(1, DB::affected_rows());
     // Check item updated
     $item = DataObject::get_one('SQLUpdateTestBase', array('"Title"' => 'Object 1'));
     $this->assertEquals('Description 1a', $item->Description);
 }
Example #10
0
 function make($rule = '', $num = 1, $cardval = array())
 {
     global $_G;
     $this->rule = empty($rule) ? $this->set['rule'] : trim($rule);
     if (empty($this->rule)) {
         return -1;
     }
     $this->fail($num);
     if (is_array($cardval)) {
         foreach ($cardval as $key => $val) {
             $sqlkey .= ", {$key}";
             $sqlval .= ", '{$val}'";
         }
     }
     for ($i = 0; $i < $num; $i++) {
         if ($this->checkrule($this->rule)) {
             $card = $this->rule;
             foreach ($this->rulereturn as $key => $val) {
                 $search = array();
                 foreach ($val as $skey => $sval) {
                     $search[] = '/' . $this->rulekey[$key] . '/';
                 }
                 $card = preg_replace($search, $val, $card, 1);
             }
         } else {
             return 0;
         }
         $sql = "INSERT INTO " . DB::table('common_card') . " (id, makeruid, dateline {$sqlkey})VALUES('{$card}', '{$_G['uid']}', '{$_G['timestamp']}' {$sqlval})";
         DB::query($sql, 'SILENT');
         if ($sqlerror = DB::error()) {
             if (DB::errno() == 1062) {
                 $this->fail++;
                 if ($this->failmin > $this->fail) {
                     $num++;
                 } else {
                     $num = $i - 1;
                 }
             } else {
                 DB::halt($sqlerror, $sql);
             }
         } else {
             $this->succeed += intval(DB::affected_rows());
             $this->cardlist[] = $card;
         }
     }
     return true;
 }
Example #11
0
function updatesession($force = false)
{
    global $_G;
    static $updated = false;
    if (!$updated) {
        if ($_G['uid']) {
            if ($_G['cookie']['ulastactivity']) {
                $ulastactivity = authcode($_G['cookie']['ulastactivity'], 'DECODE');
            } else {
                $ulastactivity = getuserprofile('lastactivity');
                dsetcookie('ulastactivity', authcode($ulastactivity, 'ENCODE'), 31536000);
            }
        }
        $discuz =& discuz_core::instance();
        $oltimespan = $_G['setting']['oltimespan'];
        //vot		//$lastolupdate = $discuz->session->var['lastolupdate'];
        /*vot*/
        $lastolupdate = DB::result_first("SELECT lastupdate FROM " . DB::table('common_onlinetime') . " WHERE uid='{$_G['uid']}'");
        if ($_G['uid'] && $oltimespan && TIMESTAMP - ($lastolupdate ? $lastolupdate : $ulastactivity) > $oltimespan * 60) {
            DB::query("UPDATE " . DB::table('common_onlinetime') . "\r\n\t\t\t\tSET total=total+'{$oltimespan}', thismonth=thismonth+'{$oltimespan}', lastupdate='" . TIMESTAMP . "'\r\n\t\t\t\tWHERE uid='{$_G['uid']}'");
            if (!DB::affected_rows()) {
                DB::insert('common_onlinetime', array('uid' => $_G['uid'], 'thismonth' => $oltimespan, 'total' => $oltimespan, 'lastupdate' => TIMESTAMP));
            }
            $discuz->session->set('lastolupdate', TIMESTAMP);
        }
        foreach ($discuz->session->var as $k => $v) {
            if (isset($_G['member'][$k]) && $k != 'lastactivity') {
                $discuz->session->set($k, $_G['member'][$k]);
            }
        }
        foreach ($_G['action'] as $k => $v) {
            $discuz->session->set($k, $v);
        }
        $discuz->session->update();
        $updated = true;
        if ($_G['uid'] && TIMESTAMP - $ulastactivity > 21600) {
            if ($oltimespan && TIMESTAMP - $ulastactivity > 43200) {
                $total = DB::result_first("SELECT total FROM " . DB::table('common_onlinetime') . " WHERE uid='{$_G['uid']}'");
                DB::update('common_member_count', array('oltime' => round(intval($total) / 60)), "uid='{$_G['uid']}'", 1);
                //vot				dsetcookie('ulastactivity', authcode(TIMESTAMP, 'ENCODE'), 31536000);
            }
            dsetcookie('ulastactivity', authcode(TIMESTAMP, 'ENCODE'), 31536000);
            DB::update('common_member_status', array('lastip' => $_G['clientip'], 'lastactivity' => TIMESTAMP, 'lastvisit' => TIMESTAMP), "uid='{$_G['uid']}'", 1);
        }
    }
    return $updated;
}
Example #12
0
 function statistic()
 {
     if (empty($this->tableName)) {
         return false;
     }
     $timestamp = time();
     $sql = "UPDATE " . $this->tableName . " \r\n\t\t\tset \r\n\t\t\t`times`=`times`+1,\r\n\t\t\t`last_visit`={$timestamp}\r\n\t\t\twhere `name`='{$this->robotName}' and `date`='{$this->date}'";
     DB::query($sql, 'SILENT');
     $result = DB::affected_rows();
     if ($result > 0) {
         return true;
     }
     $sql = "insert into {$this->tableName}(`name`,`times`,`date`,`first_visit`,`last_visit`) \r\n\t\tvalues('{$this->robotName}','1','{$this->date}','{$timestamp}','{$timestamp}')";
     DB::query($sql, 'SILENT');
     $result = (bool) DB::affected_rows();
     return $result;
 }
 public function testAffectedRows()
 {
     if (!DB::get_connector() instanceof PDOConnector) {
         $this->markTestSkipped('This test requires the current DB connector is PDO');
     }
     $query = new SQLUpdate('MySQLDatabaseTest_Data');
     $query->setAssignments(array('Title' => 'New Title'));
     // Test update which affects no rows
     $query->setWhere(array('Title' => 'Bob'));
     $result = $query->execute();
     $this->assertInstanceOf('PDOQuery', $result);
     $this->assertEquals(0, DB::affected_rows());
     // Test update which affects some rows
     $query->setWhere(array('Title' => 'First Item'));
     $result = $query->execute();
     $this->assertInstanceOf('PDOQuery', $result);
     $this->assertEquals(1, DB::affected_rows());
 }
Example #14
0
 function make($rule = '', $num = 1, $cardval = array())
 {
     global $_G;
     $this->rule = empty($rule) ? $this->set['rule'] : trim($rule);
     if (empty($this->rule)) {
         return -1;
     }
     $this->fail($num);
     $cardval['makeruid'] = $_G['uid'];
     $cardval['dateline'] = $_G['timestamp'];
     for ($i = 0; $i < $num; $i++) {
         if ($this->checkrule($this->rule)) {
             $card = $this->rule;
             foreach ($this->rulereturn as $key => $val) {
                 $search = array();
                 foreach ($val as $skey => $sval) {
                     $search[] = '/' . $this->rulekey[$key] . '/';
                 }
                 $card = preg_replace($search, $val, $card, 1);
             }
         } else {
             return 0;
         }
         $cardval['id'] = $card;
         C::t('common_card')->insert($cardval, false, false, 'SILENT');
         if ($sqlerror = DB::error()) {
             if ($sqlerror == 1062) {
                 $this->fail++;
                 if ($this->failmin > $this->fail) {
                     $num++;
                 } else {
                     $num = $i - 1;
                 }
             }
             /* else {
             				DB::halt($sqlerror, $sql);
             			}*/
         } else {
             $this->succeed += intval(DB::affected_rows());
             $this->cardlist[] = $card;
         }
     }
     return true;
 }
function friend_delete($touid)
{
    global $_G;
    if (!friend_check($touid)) {
        return false;
    }
    DB::delete('home_friend', "(uid='{$_G['uid']}' AND fuid='{$touid}') OR (fuid='{$_G['uid']}' AND uid='{$touid}')");
    if (DB::affected_rows()) {
        addfriendlog($_G['uid'], $touid, 'delete');
        friend_cache($_G['uid']);
        friend_cache($touid);
    }
}
Example #16
0
     $error_text .= sprintf(__('Please set the correct %s switch!'), __('Show Latest List')) . '<br/>';
 } elseif (!isset($_POST['listnum']) or !ctype_digit($_POST['listnum']) or (int) $_POST['listnum'] > 20) {
     $error_text .= __('Please set the correct number of latest list, the maximum must not exceed 20 !') . '<br/>';
 }
 if (!isset($_POST['downgrade']) or !ctype_digit($_POST['downgrade'])) {
     $error_text .= sprintf(__('Please set the correct %s switch!'), __('Downgrade Support')) . '<br/>';
 }
 if (!isset($_POST['allowfulllist']) or !ctype_digit($_POST['allowfulllist'])) {
     $error_text .= sprintf(__('Please set the correct %s switch!'), __('Full List of Sections')) . '<br/>';
 }
 if (!isset($_POST['url_repo']) or empty($_POST['url_repo'])) {
     $error_text .= __('Please provide a valid repository URL!') . '<br/>';
 }
 if (empty($error_text)) {
     $result = DB::query("SELECT `ID` FROM `" . DCRM_CON_PREFIX . "Users` WHERE (`Username` = '" . DB::real_escape_string($_POST['username']) . "' AND `ID` != '" . $_SESSION['userid'] . "')");
     if (!$result or DB::affected_rows() != 0) {
         $error_text .= __('There is a same username!') . '<br/>';
     } else {
         $result = DB::update(DCRM_CON_PREFIX . 'Users', array('Username' => DB::real_escape_string($_POST['username'])), array('ID' => $_SESSION['userid']));
         if (!empty($_POST['pass1'])) {
             $logout = true;
             $result = DB::update(DCRM_CON_PREFIX . 'Users', array('SHA1' => sha1($_POST['pass1'])), array('ID' => $_SESSION['userid']));
         }
     }
 }
 /* Rewrite Check */
 base_url(true);
 switch ($_POST['rewrite_mod']) {
     case 3:
         $check_url = SITE_URL . 'misc';
         $rewrite_code = url_code($check_url);
Example #17
0
function updatemodworks($modaction, $posts = 1)
{
    global $_G;
    $today = dgmdate(TIMESTAMP, 'Y-m-d');
    if ($_G['setting']['modworkstatus'] && $modaction && $posts) {
        DB::query("UPDATE " . DB::table('forum_modwork') . " SET count=count+1, posts=posts+'{$posts}' WHERE uid='{$_G['uid']}' AND modaction='{$modaction}' AND dateline='{$today}'");
        if (!DB::affected_rows()) {
            DB::query("INSERT INTO " . DB::table('forum_modwork') . " (uid, modaction, dateline, count, posts) VALUES ('{$_G['uid']}', '{$modaction}', '{$today}', 1, '{$posts}')");
        }
    }
}
Example #18
0
 *      [品牌空間] (C)2001-2010 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: theme.inc.php 4442 2010-09-14 09:43:34Z yumiao $
 */
if (!defined('IN_STORE') && !defined('IN_ADMIN')) {
    exit('Acess Denied');
}
if (!$wheresql) {
    cpmsg('no_wheresql');
}
if ($_GET['op'] == 'usetheme') {
    //提交數據的處理
    $themeid = intval(substr($_GET['theme'], 1));
    $query = DB::query("UPDATE " . tname("shopitems") . " SET themeid = '{$themeid}' WHERE {$wheresql} LIMIT 1");
    if (DB::affected_rows($query)) {
        cpmsg('update_success', $BASESCRIPT . '?action=theme&m=shop&itemid=' . $_GET['itemid']);
    }
} else {
    //取得信息
    $query = DB::query('SELECT itemid, subject, themeid FROM ' . tname('shopitems') . ' WHERE ' . $wheresql . ' ORDER BY itemid DESC LIMIT 1');
    $editvalue = DB::fetch($query);
    if (empty($editvalue)) {
        cpmsg('no_item', $BASESCRIPT . '?action=list&m=' . $mname);
    }
    //顯示導航以及表頭
    $subjectnav = $BASESCRIPT == 'admin.php' ? $editvalue['subject'] : '';
    shownav($mname, $mname . '_' . $_GET['action'], $subjectnav);
    if (pkperm('isadmin')) {
        $shopmenu = array(array('shop_edit', 'edit&m=shop&itemid=' . $_GET['itemid']), array('menu_shop_theme', 'theme&m=shop&itemid=' . $_GET['itemid'], 1), array('menu_modifypasswd', 'modifypasswd&m=shop&itemid=' . $_GET['itemid'], 0));
        if ($_G['setting']['enablemap'] == 1) {
Example #19
0
         $poststatus = $poststatus['status'];
         if (getstatus($poststatus, 3) == 0) {
             updatepostcredits('+', $thread['authorid'], 'post', $thread['fid']);
             $attachcount = C::t('forum_attachment_n')->count_by_id('tid:' . $thread['tid'], 'tid', $thread['tid']);
             updatecreditbyaction('postattach', $thread['authorid'], array(), '', $attachcount, 1, $thread['fid']);
         }
         $validatedthreads[] = $thread;
         if ($thread['authorid'] && $thread['authorid'] != $_G['uid']) {
             $pmlist[] = array('act' => 'modthreads_validate', 'notevar' => array('reason' => dhtmlspecialchars($_GET['reason']), 'tid' => $thread['tid'], 'threadsubject' => $thread['subject'], 'from_id' => 0, 'from_idtype' => 'modthreads'), 'authorid' => $thread['authorid']);
         }
     }
     if ($tids) {
         $tidstr = dimplode($tids);
         C::t('forum_post')->update_by_tid(0, $tids, array('invisible' => 0), true, false, 1);
         C::t('forum_thread')->update($tids, array('displayorder' => 0, 'moderated' => 1));
         $threadsmod = DB::affected_rows();
         if ($_G['fid']) {
             updateforumcount($_G['fid']);
         } else {
             $fids = array_keys($modforums['list']);
             foreach ($fids as $f) {
                 updateforumcount($f);
             }
         }
         updatemodworks('MOD', $threadsmod);
         updatemodlog($tidstr, 'MOD');
         updatemoderate('tid', $tids, 2);
     }
 }
 if ($pmlist) {
     foreach ($pmlist as $pm) {
Example #20
0
function updatetopic($topic = '')
{
    global $_G;
    $topicid = empty($topic) ? '' : $topic['topicid'];
    include_once libfile('function/home');
    $_POST['title'] = getstr(trim($_POST['title']), 255, 1, 1);
    $_POST['name'] = getstr(trim($_POST['name']), 255, 1, 1);
    $_POST['domain'] = getstr(trim($_POST['domain']), 255, 1, 1);
    if (empty($_POST['title'])) {
        return 'topic_title_cannot_be_empty';
    }
    if (empty($_POST['name'])) {
        $_POST['name'] = $_POST['title'];
    }
    if (!$topicid || $_POST['name'] != $topic['name']) {
        $value = DB::fetch_first('SELECT * FROM ' . DB::table('portal_topic') . " WHERE name = '{$_POST['name']}' LIMIT 1");
        if ($value) {
            return 'topic_name_duplicated';
        }
    }
    if ($topicid && !empty($topic['domain'])) {
        require_once libfile('function/delete');
        deletedomain($topicid, 'topic');
    }
    if (!empty($_POST['domain'])) {
        require_once libfile('function/domain');
        domaincheck($_POST['domain'], $_G['setting']['domain']['root']['topic'], 1);
    }
    $setarr = array('title' => $_POST['title'], 'name' => $_POST['name'], 'domain' => $_POST['domain'], 'summary' => getstr($_POST['summary'], '', 1, 1), 'keyword' => getstr($_POST['keyword'], '', 1, 1), 'useheader' => $_POST['useheader'] ? '1' : '0', 'usefooter' => $_POST['usefooter'] ? '1' : '0');
    if ($_POST['deletecover'] && $topic['cover']) {
        if ($topic['picflag'] != '0') {
            pic_delete(str_replace('portal/', '', $topic['cover']), 'portal', 0, $topic['picflag'] == '2' ? '1' : '0');
        }
        $setarr['cover'] = '';
    } else {
        if ($_FILES['cover']['tmp_name']) {
            if ($topic['cover'] && $topic['picflag'] != '0') {
                pic_delete(str_replace('portal/', '', $topic['cover']), 'portal', 0, $topic['picflag'] == '2' ? '1' : '0');
            }
            $pic = pic_upload($_FILES['cover'], 'portal');
            if ($pic) {
                $setarr['cover'] = 'portal/' . $pic['pic'];
                $setarr['picflag'] = $pic['remote'] ? '2' : '1';
            }
        } else {
            if (!empty($_POST['cover']) && $_POST['cover'] != $topic['cover']) {
                if ($topic['cover'] && $topic['picflag'] != '0') {
                    pic_delete(str_replace('portal/', '', $topic['cover']), 'portal', 0, $topic['picflag'] == '2' ? '1' : '0');
                }
                $setarr['cover'] = $_POST['cover'];
                $setarr['picflag'] = '0';
            }
        }
    }
    $primaltplname = '';
    if (empty($topicid) || empty($topic['primaltplname']) || $topic['primaltplname'] && $topic['primaltplname'] != 'portal/' . $_POST['primaltplname']) {
        $primaltplname = $_POST['primaltplname'];
        if (!$primaltplname || preg_match("/(\\.)(exe|jsp|asp|aspx|cgi|fcgi|pl)(\\.|\$)/i", $primaltplname)) {
            return 'topic_filename_invalid';
        }
        $primaltplname = 'portal/' . str_replace(array('/', '\\', '.'), '', $primaltplname);
        checkprimaltpl($primaltplname);
        $setarr['primaltplname'] = $primaltplname;
    }
    if ($topicid) {
        DB::update('portal_topic', $setarr, array('topicid' => $topicid));
        DB::update('common_diy_data', array('name' => $setarr['title']), array('targettplname' => 'portal/portal_topic_content_' . $topicid));
    } else {
        $setarr['uid'] = $_G['uid'];
        $setarr['username'] = $_G['username'];
        $setarr['dateline'] = $_G['timestamp'];
        $setarr['closed'] = '1';
        $topicid = addtopic($setarr);
        if (!$topicid) {
            return 'topic_created_failed';
        }
    }
    if (!empty($_POST['domain'])) {
        DB::insert('common_domain', array('domain' => $_POST['domain'], 'domainroot' => addslashes($_G['setting']['domain']['root']['topic']), 'id' => $topicid, 'idtype' => 'topic'));
    }
    $makediyfile = false;
    if ($primaltplname && !empty($topic['primaltplname']) && $topic['primaltplname'] != $primaltplname) {
        $targettplname = 'portal/portal_topic_content_' . $topicid;
        DB::update('common_diy_data', array('primaltplname' => $primaltplname), array('targettplname' => $targettplname));
        if (DB::affected_rows() > 0) {
            updatediytemplate($targettplname);
        } else {
            $makediyfile = true;
        }
    }
    if ($primaltplname && empty($topic['primaltplname']) || $primaltplname && $makediyfile) {
        $content = file_get_contents(DISCUZ_ROOT . './template/default/' . $primaltplname . '.htm');
        $tplfile = DISCUZ_ROOT . './data/diy/portal/portal_topic_content_' . $topicid . '.htm';
        $tplpath = dirname($tplfile);
        if (!is_dir($tplpath)) {
            dmkdir($tplpath);
        }
        file_put_contents($tplfile, $content);
    }
    include_once libfile('function/cache');
    updatecache(array('diytemplatename', 'setting'));
    return $topicid;
}
             $attachcount = DB::result_first("SELECT COUNT(*) FROM " . DB::table(getattachtablebytid($thread['tid'])) . " WHERE tid='{$thread['tid']}'");
             updatecreditbyaction('postattach', $thread['authorid'], array(), '', $attachcount, 1, $thread['fid']);
         }
         $forums[] = $thread['fid'];
         $validatedthreads[] = $thread;
         $pm = 'pm_' . $thread['tid'];
         if (isset($_G['gp_' . $pm]) && $_G['gp_' . $pm] != '' && $thread['authorid']) {
             $pmlist[] = array('action' => 'modthreads_validate', 'notevar' => array('tid' => $thread['tid'], 'threadsubject' => $thread['subject'], 'reason' => dhtmlspecialchars($_G['gp_' . $pm])), 'authorid' => $thread['authorid']);
         }
     }
     if ($tids) {
         $tidstr = dimplode($tids);
         $validates = DB::query("UPDATE " . DB::table(getposttable()) . " SET status='4' WHERE tid IN ({$tidstr}) AND status='0' AND invisible='-2'");
         updatepost(array('invisible' => '0'), "tid IN ({$tidstr}) AND first='1'");
         DB::query("UPDATE " . DB::table('forum_thread') . " SET displayorder='0', moderated='1' WHERE tid IN ({$tidstr})");
         $validates = DB::affected_rows();
         foreach (array_unique($forums) as $fid) {
             updateforumcount($fid);
         }
         updatemodworks('MOD', $validates);
         updatemodlog($tidstr, 'MOD');
         updatemoderate('tid', $tids, 2);
     }
 }
 if ($pmlist) {
     foreach ($pmlist as $pm) {
         notification_add($pm['authorid'], 'system', $pm['action'], $pm['notevar'], 1);
     }
 }
 if ($_G['gp_fast']) {
     echo callback_js($_G['gp_tid']);
Example #22
0
    }
    $runquerys = array();
    //include_once(DZZ_ROOT.'source/admincp/admincp_quickquery.php');
    if (!submitcheck('sqlsubmit')) {
    } else {
        $queries = $_GET['queries'];
        $sqlquery = splitsql(str_replace(array(' {tablepre}', ' cdb_', ' `cdb_', ' pre_', ' `pre_'), array(' ' . $tablepre, ' ' . $tablepre, ' `' . $tablepre, ' ' . $tablepre, ' `' . $tablepre), $queries));
        $affected_rows = 0;
        foreach ($sqlquery as $sql) {
            if (trim($sql) != '') {
                $sql = !empty($_GET['createcompatible']) ? syntablestruct(trim($sql), $db->version() > '4.1', $dbcharset) : $sql;
                DB::query($sql, 'SILENT');
                if ($sqlerror = DB::error()) {
                    break;
                } else {
                    $affected_rows += intval(DB::affected_rows());
                }
            }
        }
        if ($sqlerror) {
            $msg = lang('template', 'database_run_query_invalid', array('sqlerror' => $sqlerror));
            $msg_type = 'text-error';
            $redirecturl = dreferer();
        } else {
            $msg = lang('template', 'database_run_query_succeed', array('affected_rows' => $affected_rows));
            $msg_type = 'text-success';
            $redirecturl = dreferer();
        }
    }
    include template('database');
}
             }
             if (!empty($_G['gp_fids'][$id])) {
                 foreach (explode(',', $_G['gp_fids'][$id]) as $fid) {
                     if ($fid = intval($fid)) {
                         $updatefids[$fid]['deletedids'][] = intval($id);
                     }
                 }
             }
         }
     }
 }
 if (is_array($_G['gp_namenew']) && $_G['gp_namenew']) {
     foreach ($_G['gp_namenew'] as $typeid => $val) {
         $_G['gp_descriptionnew'] = is_array($_G['gp_descriptionnew']) ? $_G['gp_descriptionnew'] : array();
         DB::update('forum_threadtype', array('name' => trim($_G['gp_namenew'][$typeid]), 'description' => dhtmlspecialchars(trim($_G['gp_descriptionnew'][$typeid])), 'displayorder' => intval($_G['gp_displayordernew'][$typeid]), 'special' => 1), "typeid='{$typeid}'");
         if (DB::affected_rows()) {
             $modifiedtypes[] = $typeid;
         }
     }
     if ($modifiedtypes = array_unique($modifiedtypes)) {
         foreach ($modifiedtypes as $id) {
             if (!empty($_G['gp_fids'][$id])) {
                 foreach (explode(',', $_G['gp_fids'][$id]) as $fid) {
                     if ($fid = intval($fid)) {
                         $updatefids[$fid]['modifiedids'][] = $id;
                     }
                 }
             }
         }
     }
 }
Example #24
0
function updatepost($data, $condition, $unbuffered = false, $posttableid = false)
{
    global $_G;
    loadcache('posttableids');
    $affected_rows = 0;
    if (!empty($_G['cache']['posttableids'])) {
        $posttableids = $posttableid !== false && in_array($posttableid, $_G['cache']['posttableids']) ? array($posttableid) : $_G['cache']['posttableids'];
    } else {
        $posttableids = array('0');
    }
    foreach ($posttableids as $id) {
        DB::update(getposttable($id), $data, $condition, $unbuffered);
        $affected_rows += DB::affected_rows();
    }
    return $affected_rows;
}
Example #25
0
function movedate($query)
{
    global $sourcesize, $tableid, $movesize, $targettableid, $hash, $tableindex, $threadtableids, $fieldstr, $fromtableid, $posttable_info;
    $tids = array();
    while ($value = DB::fetch($query)) {
        $tids[$value['tid']] = $value['tid'];
    }
    $fromtable = getposttable($fromtableid, true);
    $condition = " tid IN(" . dimplode($tids) . ")";
    DB::query("INSERT INTO " . DB::table(getposttable($targettableid)) . " ({$fieldstr}) SELECT {$fieldstr} FROM {$fromtable} WHERE {$condition}", 'SILENT');
    if (DB::errno()) {
        DB::delete(getposttable($targettableid), $condition);
    } else {
        foreach ($threadtableids as $threadtableid) {
            $table = $threadtableid ? "forum_thread_{$threadtableid}" : 'forum_thread';
            DB::update($table, array('posttableid' => $targettableid), $condition);
            if (DB::affected_rows() == count($tids)) {
                break;
            }
        }
        DB::delete(getposttable($fromtableid), $condition);
    }
    $status = gettablestatus(DB::table(getposttable($targettableid)), false);
    $targetsize = $sourcesize + $movesize * 1048576;
    $nowdatasize = $targetsize - $status['Data_length'];
    if ($status['Data_length'] >= $targetsize) {
        cpmsg('postsplit_done', 'action=postsplit&operation=optimize&tableid=' . $fromtableid, 'form');
    }
    cpmsg('postsplit_doing', 'action=postsplit&operation=movepost&fromtable=' . $tableid . '&movesize=' . $movesize . '&targettable=' . $targettableid . '&hash=' . $hash . '&tindex=' . $tableindex, 'loadingform', array('datalength' => sizecount($status['Data_length']), 'nowdatalength' => sizecount($nowdatasize)));
}
     $adminidnew = $member['adminid'];
     if (in_array('avatar', $_GET['clear'])) {
         $setarr['avatarstatus'] = 0;
         loaducenter();
         uc_user_deleteavatar($member['uid']);
     }
 }
 if (!empty($my_data) && !empty($mylogtype)) {
     $log_handler = Cloud::loadClass('Cloud_Service_SearchHelper');
     $log_handler->myThreadLog($mylogtype, $my_data);
 }
 $setarr['adminid'] = $adminidnew;
 $setarr['groupid'] = $groupidnew;
 $setarr['status'] = $_GET['bannew'] == 'status' ? -1 : 0;
 C::t('common_member' . $tableext)->update($member['uid'], $setarr);
 if ($_G['group']['allowbanuser'] && DB::affected_rows()) {
     banlog($member['username'], $member['groupid'], $groupidnew, $_GET['banexpirynew'], $reason, $_GET['bannew'] == 'status' ? -1 : 0);
 }
 C::t('common_member_field_forum' . $tableext)->update($member['uid'], array('groupterms' => $member['groupterms'] ? serialize($member['groupterms']) : ''));
 $crimeaction = $noticekey = '';
 include_once libfile('function/member');
 if ($_GET['bannew'] == 'post') {
     $crimeaction = 'crime_banspeak';
     $noticekey = 'member_ban_speak';
     $from_idtype = 'banspeak';
 } elseif ($_GET['bannew'] == 'visit') {
     $crimeaction = 'crime_banvisit';
     $noticekey = 'member_ban_visit';
     $from_idtype = 'banvisit';
 } elseif ($_GET['bannew'] == 'status') {
     $crimeaction = 'crime_banstatus';
Example #27
0
function undeletethreads($tids)
{
    global $_G;
    $threadsundel = 0;
    if ($tids && is_array($tids)) {
        foreach ($tids as $t) {
            my_thread_log('restore', array('tid' => $t));
        }
        $tids = '\'' . implode('\',\'', $tids) . '\'';
        $tuidarray = $ruidarray = $fidarray = array();
        $postarray = getfieldsofposts('fid, first, authorid', "tid IN ({$tids})");
        foreach ($postarray as $post) {
            if ($post['first']) {
                $tuidarray[] = $post['authorid'];
            } else {
                $ruidarray[] = $post['authorid'];
            }
            if (!in_array($post['fid'], $fidarray)) {
                $fidarray[] = $post['fid'];
            }
        }
        if ($tuidarray) {
            updatepostcredits('+', $tuidarray, 'post');
        }
        if ($ruidarray) {
            updatepostcredits('+', $ruidarray, 'reply');
        }
        updatepost(array('invisible' => '0'), "tid IN ({$tids})", true);
        DB::query("UPDATE " . DB::table('forum_thread') . " SET displayorder='0', moderated='1' WHERE tid IN ({$tids})");
        $threadsundel = DB::affected_rows();
        updatemodlog($tids, 'UDL');
        updatemodworks('UDL', $threadsundel);
        foreach ($fidarray as $fid) {
            updateforumcount($fid);
        }
    }
    return $threadsundel;
}
Example #28
0
    if ($sghosts != "" && ghosts_in($userclosed, $sghosts, $Charset) || C_HIDE_ADMINS && ($statusclosed == "a" || $statusclosed == "t") || C_HIDE_MODERS && $statusclosed == "m") {
    } else {
        $ChatM->query("INSERT INTO " . C_MSG_TBL . " VALUES ('" . $usertype . "', '" . $userroom . "', 'SYS exit', '', '" . time() . "', '', 'sprintf(L_CLOSED_ROM, \"(" . $when . ") " . $userclosed . "\")', '', '')");
    }
    if (C_EN_STATS) {
        $ChatM->query("UPDATE " . C_STS_TBL . " SET seconds_away=seconds_away+({$usertime}-last_away), longest_away=IF({$usertime}-last_away < longest_away, longest_away, {$usertime}-last_away), last_away='' WHERE (stat_date=FROM_UNIXTIME(last_away,'%Y-%m-%d') OR stat_date=FROM_UNIXTIME(last_in,'%Y-%m-%d')) AND room='{$userroom}' AND username='******' AND last_away!='0'");
        $ChatM->query("UPDATE " . C_STS_TBL . " SET seconds_in=seconds_in+({$usertime}-last_in), longest_in=IF({$usertime}-last_in < longest_in, longest_in, {$usertime}-last_in), last_in='' WHERE stat_date=FROM_UNIXTIME(last_in,'%Y-%m-%d') AND room='{$userroom}' AND username='******' AND last_in!='0'");
    }
    $ChatM->query("DELETE FROM " . C_USR_TBL . " WHERE username='******'");
    $CleanUsrTbl = $ChatM->affected_rows() > 0;
    $highpath = "botfb/" . $userclosed;
    // file is in DIR "botfb" and called "username"
    if (file_exists($highpath)) {
        unlink($highpath);
    }
    // checks to see if user file exists.
    // if it does delete it.
    $botpath = "botfb/" . $userclosed . ".txt";
    // file is in DIR "botfb" and called "username.txt"
    if (file_exists($botpath)) {
        unlink($botpath);
    }
    // checks to see if user file exists.
}
$ChatM->close();
// Clean users table of disconnected users if booting is disabled
if (!C_CHAT_BOOT && !$CleanUsrTbl) {
    $Chat->query("DELETE FROM " . C_USR_TBL . " WHERE username != '" . C_BOT_NAME . "' AND (u_time<'" . (time() - C_USR_DEL * 60) . "' OR (status='k' AND u_time<'" . (time() - 20) . "'))");
    $CleanUsrTbl = $Chat->affected_rows() > 0;
    $Chat->close();
}
Example #29
0
 function onPhotoRemoveAlbum($uId, $aId, $action = null, $targetAlbumId = null)
 {
     $res = $this->getUserSpace($uId);
     if (!$res) {
         return new ErrorResponse('1', "User({$uId}) Not Exists");
     }
     $aId = intval($aId);
     if ($aId < 1) {
         $errCode = 120;
         $errMessage = 'Invalid Album Id';
         return new ErrorResponse($errCode, $errMessage);
     }
     if ($action == 'move') {
         $targetAlbumId = intval($targetAlbumId);
         if ($targetAlbumId < 1) {
             $errCode = 120;
             $errMessage = 'Invalid Target Album Id';
             return new ErrorResponse($errCode, $errMessage);
         }
         $sql = 'SELECT  picnum FROM ' . DB::table('home_album') . ' WHERE albumid=' . $aId . ' AND uid=' . $uId;
         $query = DB::query($sql);
         $albumInfo = DB::fetch($query);
         if (!$albumInfo) {
             $errCode = 120;
             $errMessage = 'Invalid Album Id';
             return new ErrorResponse($errCode, $errMessage);
         }
         if ($albumInfo['picnum'] > 0) {
             $sql = sprintf('UPDATE %s SET picnum = picnum + %d, dateline=%d WHERE albumid =%d AND uid=%d', DB::table('home_album'), $albumInfo['picnum'], time(), $targetAlbumId, $uId);
             DB::query($sql);
             $existsAlbum = DB::affected_rows();
             if (!$existsAlbum) {
                 $errCode = 120;
                 $errMessage = 'Invalid Target Album Id';
                 return new ErrorResponse($errCode, $errMessage);
             }
             DB::update('home_pic', array('albumid' => $targetAlbumId), array('albumid' => $aId, 'uid' => $uId));
         }
     }
     require_once libfile('function/delete');
     $res = deletealbums(array($aId));
     if ($res && is_array($res)) {
         return true;
     } else {
         $errCode = 124;
         $errMessage = 'Delete Album Failure';
         return new ErrorResponse($errCode, $errMessage);
     }
 }
Example #30
0
        $quotetext = str_replace("\n", "", $quotetext);
        if ($R != "1") {
            $DbLink->query("SELECT m_time FROM " . C_MSG_TBL . " WHERE username='******' AND room = '{$R}' AND m_time > " . (time() - $quotetime) . " ORDER BY m_time DESC LIMIT 1");
            if ($DbLink->num_rows() == 0) {
                $DbLink->query("INSERT INTO " . C_MSG_TBL . " VALUES ({$T}, '{$R}', '" . C_QUOTE_NAME . "', '', " . time() . ", '', '{$quotetext}', '', '')");
            }
        }
    }
}
if (C_CHAT_BOOT) {
    $CondForQueryM = "(username='******' OR message='stripslashes(sprintf(L_ENTER_ROM, \"" . $U . "\"))' OR message='stripslashes(sprintf(L_ENTER_ROM_NOSOUND, \"" . $U . "\"))' OR ((username='******' OR username LIKE 'SYS top%' OR username='******' OR username='******' OR username='******' OR username='******' OR username='******' OR username='******' OR username='******' OR username='******' OR username='******') AND address='{$U}'))";
    $DbLink->query("SELECT type,m_time,room FROM " . C_MSG_TBL . " WHERE " . $CondForQueryM . " ORDER BY m_time DESC LIMIT 1");
    list($m_type, $m_time, $m_room) = $DbLink->next_record();
    $CondForQueryU = "status!='a' AND status!='t' AND status!='m' AND username='******' AND username!='" . C_BOT_NAME . "' AND awaystat='0' AND (u_time > " . ($m_time + C_USR_DEL * 60) . " OR (status ='k' AND u_time <  " . (time() - 20) . "))" . $Hide . "";
    $DbLink->query("DELETE FROM " . C_USR_TBL . " WHERE " . $CondForQueryU . "");
    $CleanUsrTbl = $DbLink->affected_rows() > 0;
    if ($CleanUsrTbl) {
        // Ghost Control mod by Ciprian
        if (C_SPECIAL_GHOSTS != "") {
            $sghosts = "";
            $sghosts = str_replace("'", "", C_SPECIAL_GHOSTS);
            $sghosts = str_replace(" AND username != ", ",", $sghosts);
        }
        if ($sghosts != "" && ghosts_in(stripslashes($U), $sghosts, $Charset) || C_HIDE_ADMINS && ($status == "a" || $status == "t") || C_HIDE_MODERS && $status == "m") {
        } else {
            $DbLink->query("INSERT INTO " . C_MSG_TBL . " VALUES ('" . $m_type . "', '" . $m_room . "', 'SYS exit', '', " . time() . ", '', 'sprintf(L_BOOT_ROM, \"{$U}\")', '', '')");
        }
        if (C_EN_STATS) {
            $DbLink->query("UPDATE " . C_STS_TBL . " SET seconds_away=seconds_away+({$curtime}-last_away), longest_away=IF({$curtime}-last_away < longest_away, longest_away, {$curtime}-last_away), last_away='' WHERE (stat_date=FROM_UNIXTIME(last_away,'%Y-%m-%d') OR stat_date=FROM_UNIXTIME(last_in,'%Y-%m-%d')) AND room='{$m_room}' AND username='******' AND last_away!='0'");
            $DbLink->query("UPDATE " . C_STS_TBL . " SET seconds_in=seconds_in+({$curtime}-last_in), longest_in=IF({$curtime}-last_in < longest_in, longest_in, {$curtime}-last_in), last_in='' WHERE stat_date=FROM_UNIXTIME(last_in,'%Y-%m-%d') AND room='{$m_room}' AND username='******' AND last_in!='0'");
        }