affectedRows() public static method

public static affectedRows ( )
Example #1
0
 public static function updateViewCount(array $viewCount)
 {
     if (!$viewCount) {
         return 0;
     }
     $query = 'update `clips` set `view_count` =  case ';
     foreach ($viewCount as $clip_id => $view_count) {
         $query .= ' when `id` = ' . intval($clip_id) . ' then ' . intval($view_count);
     }
     unset($clip_id, $view_count);
     $query .= ' end';
     DB::query($query);
     return DB::affectedRows();
 }
    public function onAfterWrite()
    {
        parent::onAfterWrite();
        $ID = $this->owner->ID;
        $className = $this->owner->ClassName;
        $subClasses = ClassInfo::dataClassesFor($className);
        $versionsToDelete = array();
        $version_limit = Config::inst()->get('VersionTruncator', 'version_limit');
        if (is_numeric($version_limit)) {
            $search = DB::query('SELECT "RecordID", "Version" FROM "SiteTree_versions"
				 WHERE "RecordID" = ' . $ID . ' AND "ClassName" = \'' . $className . '\'
				 AND "PublisherID" > 0
				 ORDER BY "LastEdited" DESC LIMIT ' . $version_limit . ', 200');
            foreach ($search as $row) {
                array_push($versionsToDelete, array('RecordID' => $row['RecordID'], 'Version' => $row['Version']));
            }
        }
        $draft_limit = Config::inst()->get('VersionTruncator', 'draft_limit');
        if (is_numeric($draft_limit)) {
            $search = DB::query('SELECT "RecordID", "Version" FROM "SiteTree_versions"
				 WHERE "RecordID" = ' . $ID . ' AND "ClassName" = \'' . $className . '\'
				 AND "PublisherID" = 0
				 ORDER BY "LastEdited" DESC LIMIT ' . $draft_limit . ', 200');
            foreach ($search as $row) {
                array_push($versionsToDelete, array('RecordID' => $row['RecordID'], 'Version' => $row['Version']));
            }
        }
        $delete_old_page_types = Config::inst()->get('VersionTruncator', 'delete_old_page_types');
        if ($delete_old_page_types) {
            $search = DB::query('SELECT "RecordID", "Version" FROM "SiteTree_versions"
				 WHERE "RecordID" = ' . $ID . ' AND "ClassName" != \'' . $className . '\'');
            foreach ($search as $row) {
                array_push($versionsToDelete, array('RecordID' => $row['RecordID'], 'Version' => $row['Version']));
            }
        }
        /* If versions to delete, start deleting */
        if (count($versionsToDelete) > 0) {
            $affected_tables = array();
            foreach ($subClasses as $subclass) {
                $versionsTable = $subclass . '_versions';
                foreach ($versionsToDelete as $d) {
                    DB::query('DELETE FROM "' . $versionsTable . '"' . ' WHERE "RecordID" = ' . $d['RecordID'] . ' AND "Version" = ' . $d['Version']);
                    if (DB::affectedRows() == 1) {
                        array_push($affected_tables, $versionsTable);
                    }
                }
            }
            $this->vacuumTables($affected_tables);
        }
    }
Example #3
0
 /**
  * Delete a file from the VFS.
  *
  * @param string $path  The path to store the file in.
  * @param string $name  The filename to use.
  *
  * @throws Horde_Vfs_Exception
  */
 public function deleteFile($path, $name)
 {
     $this->_checkQuotaDelete($path, $name);
     $this->_connect();
     $result = $this->_db->query(sprintf('DELETE FROM %s WHERE vfs_type = ? AND vfs_path = ? AND vfs_name = ?', $this->_params['table']), array(self::FILE, $path, $name));
     if ($this->_db->affectedRows() == 0) {
         throw new Horde_Vfs_Exception('Unable to delete VFS file.');
     }
     if ($result instanceof PEAR_Error) {
         throw new Horde_Vfs_Exception($result->getMessage());
     }
     if (!@unlink($this->_getNativePath($path, $name))) {
         throw new Horde_Vfs_Exception('Unable to delete VFS file.');
     }
 }
 public function delete($tableName, $sWhere = null)
 {
     $sql = "DELETE FROM {$tableName}";
     if (!is_null($sWhere)) {
         $sql .= " WHERE {$sWhere}";
     }
     $result = $this->conn->query($sql);
     self::logQuery();
     if (DB::isError($result)) {
         throw new LoggedException($result->getMessage(), $result->getCode(), self::module);
     }
     //Ensure the delete count is returned
     $this->conn->setOption('portability', DB_PORTABILITY_DELETE_COUNT);
     //return the number of rows affected
     return $this->conn->affectedRows();
 }
 function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     if (isset($_GET["updatepayment"])) {
         DB::query("\n\t\t\t\tUPDATE \"Payment\"\n\t\t\t\tSET \"AmountAmount\" = \"Amount\"\n\t\t\t\tWHERE\n\t\t\t\t\t\"Amount\" > 0\n\t\t\t\t\tAND (\n\t\t\t\t\t\t\"AmountAmount\" IS NULL\n\t\t\t\t\t\tOR \"AmountAmount\" = 0\n\t\t\t\t\t)\n\t\t\t");
         $countAmountChanges = DB::affectedRows();
         if ($countAmountChanges) {
             DB::alteration_message("Updated Payment.Amount field to 2.4 - {$countAmountChanges} rows updated", "edited");
         }
         DB::query("\n\t\t\t\tUPDATE \"Payment\"\n\t\t\t\tSET \"AmountCurrency\" = \"Currency\"\n\t\t\t\tWHERE\n\t\t\t\t\t\"Currency\" <> ''\n\t\t\t\t\tAND \"Currency\" IS NOT NULL\n\t\t\t\t\tAND (\n\t\t\t\t\t\t\"AmountCurrency\" IS NULL\n\t\t\t\t\t\tOR \"AmountCurrency\" = ''\n\t\t\t\t\t)\n\t\t\t");
         $countCurrencyChanges = DB::affectedRows();
         if ($countCurrencyChanges) {
             DB::alteration_message("Updated Payment.Currency field to 2.4  - {$countCurrencyChanges} rows updated", "edited");
         }
         if ($countAmountChanges != $countCurrencyChanges) {
             DB::alteration_message("Potential error in Payment fields update to 2.4, please review data", "deleted");
         }
     }
 }
Example #6
0
 public function __add_to_cart($item_id, $sides)
 {
     $item = DB::queryOneRow("SELECT * FROM menu_items WHERE id=%s", $item_id);
     $existing_uid = DB::queryOneRow("SELECT uid FROM carts WHERE user_id=%s AND cart_type=%s AND active=%d", $this->data["uid"], $item["service_id"], 1);
     if (DB::count() != 0) {
         $uid = $existing_uid["uid"];
     } else {
         $uid = GUID();
     }
     DB::query("UPDATE carts SET quantity=quantity+1 WHERE item_id=%s AND user_id=%s AND cart_type=%s AND active=%d", $item_id, $this->data["uid"], $item["service_id"], 1);
     if (DB::affectedRows() == 0) {
         DB::insert("carts", array("uid" => $uid, "cart_type" => $item["service_id"], "item_id" => $item_id, "user_id" => $this->data["uid"]));
     }
     if (count($sides) > 0) {
         foreach ($sides as $sk => $sv) {
             DB::query("UPDATE cart_sides SET quantity=quantity+1 WHERE cart_entry_uid=%s AND side_id=%s", $uid, $sv);
             if (DB::affectedRows() == 0) {
                 DB::insert("cart_sides", array("cart_entry_uid" => $uid, "side_id" => $sv));
             }
         }
     }
     return $this->get_cart($item["category_id"]);
     //        DB::sqleval("NOW()")
 }
Example #7
0
<?php

$GLOBALS['Session']->requireAccountLevel('Developer');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    DB::nonQuery('DELETE FROM `%s` WHERE CollectionID IN (SELECT ID FROM `%s` WHERE Site != "Local")', array(SiteFile::$tableName, SiteCollection::$tableName));
    apc_clear_cache('user');
    die('Cleared ' . DB::affectedRows() . ' cached files');
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Clear Parent Site Cache</title>
    <style>
        * {
            font-size: xx-large;
            text-align: center;
        }

        input {
            cursor: pointer;
            margin: 1em;
        }

        em strong {
            color: #c00;
        }
    </style>
</head>
<body>
Example #8
0
<?php 
try {
    ?>
    <form method = "post">
        <input type = "hidden" name = "secure_input" value = "<?php 
    echo $_SESSION['secure_token_last'];
    ?>
">
        <textarea cols="70" name="query" rows="4"><?php 
    echo isset($_POST['query']) ? $_POST['query'] : "SELECT * FROM {PREFIX}users";
    ?>
</textarea><br />
        <input type="submit" value="Query" />
    </form>
    <?php 
    if (isset($_POST['query'])) {
        try {
            $query = $_POST['query'];
            if (empty($_POST['query'])) {
                throw new Exception("INVALID QUERY");
            }
            $db = new DB();
            $db->query(stripslashes($db->escape($query)));
            echo notice($query . "<br />Affected rows " . $db->affectedRows());
        } catch (Exception $e) {
            echo error(_t($e->getMessage()));
        }
    }
} catch (Exception $e) {
    echo error(_t($e->getMessage()));
}
Example #9
0
 public function act()
 {
     $result = DB::pureQuery((string) $this);
     switch ($this->type) {
         case self::select:
             return $result;
         case self::delete:
         case self::update:
             return DB::affectedRows();
         case self::insert:
             return DB::insertedID();
     }
 }
Example #10
0
	/**
	 * Generate the given field on the table, modifying whatever already exists as necessary.
	 * @param string $table The table name.
	 * @param string $field The field name.
	 * @param array|string $spec The field specification. If passed in array syntax, the specific database
	 * 	driver takes care of the ALTER TABLE syntax. If passed as a string, its assumed to
	 * 	be prepared as a direct SQL framgment ready for insertion into ALTER TABLE. In this case you'll
	 * 	need to take care of database abstraction in your DBField subclass.  
	 */
	function requireField($table, $field, $spec) {
		//TODO: this is starting to get extremely fragmented.
		//There are two different versions of $spec floating around, and their content changes depending
		//on how they are structured.  This needs to be tidied up.
		$fieldValue = null;
		$newTable = false;
		
		Profiler::mark('requireField');
		
		// backwards compatibility patch for pre 2.4 requireField() calls
		$spec_orig=$spec;
		
		if(!is_string($spec)) {
			$spec['parts']['name'] = $field;
			$spec_orig['parts']['name'] = $field;
			//Convert the $spec array into a database-specific string
			$spec=DB::getConn()->$spec['type']($spec['parts'], true);
		}
		
		// Collations didn't come in until MySQL 4.1.  Anything earlier will throw a syntax error if you try and use
		// collations.
		// TODO: move this to the MySQLDatabase file, or drop it altogether?
		if(!$this->supportsCollations()) {
			$spec = preg_replace('/ *character set [^ ]+( collate [^ ]+)?( |$)/', '\\2', $spec);
		}
		
		if(!isset($this->tableList[strtolower($table)])) $newTable = true;

		if(!$newTable && !isset($this->fieldList[$table])) {
			$this->fieldList[$table] = $this->fieldList($table);
		}

		if(is_array($spec)) {
			$specValue = DB::getConn()->$spec_orig['type']($spec_orig['parts']);
		} else {
			$specValue = $spec;
		}

		// We need to get db-specific versions of the ID column:
		if($spec_orig==DB::getConn()->IdColumn() || $spec_orig==DB::getConn()->IdColumn(true))
			$specValue=DB::getConn()->IdColumn(true);
		
		if(!$newTable) {
			if(isset($this->fieldList[$table][$field])) {
				if(is_array($this->fieldList[$table][$field])) {
					$fieldValue = $this->fieldList[$table][$field]['data_type'];
				} else {
					$fieldValue = $this->fieldList[$table][$field];
				}
			}
		}
		
		// Get the version of the field as we would create it. This is used for comparison purposes to see if the
		// existing field is different to what we now want
		if(is_array($spec_orig)) {
			$spec_orig=DB::getConn()->$spec_orig['type']($spec_orig['parts']);
		}
		
		if($newTable || $fieldValue=='') {
			Profiler::mark('createField');
			
			$this->transCreateField($table, $field, $spec_orig);
			Profiler::unmark('createField');
			$this->alterationMessage("Field $table.$field: created as $spec_orig","created");
		} else if($fieldValue != $specValue) {
			// If enums/sets are being modified, then we need to fix existing data in the table.
			// Update any records where the enum is set to a legacy value to be set to the default.
			// One hard-coded exception is SiteTree - the default for this is Page.
			foreach(array('enum','set') as $enumtype) {
				if(preg_match("/^$enumtype/i",$specValue)) {
					$newStr = preg_replace("/(^$enumtype\s*\(')|('$\).*)/i","",$spec_orig);
					$new = preg_split("/'\s*,\s*'/", $newStr);
				
					$oldStr = preg_replace("/(^$enumtype\s*\(')|('$\).*)/i","", $fieldValue);
					$old = preg_split("/'\s*,\s*'/", $newStr);

					$holder = array();
					foreach($old as $check) {
						if(!in_array($check, $new)) {
							$holder[] = $check;
						}
					}
					if(count($holder)) {
						$default = explode('default ', $spec_orig);
						$default = $default[1];
						if($default == "'SiteTree'") $default = "'Page'";
						$query = "UPDATE \"$table\" SET $field=$default WHERE $field IN (";
						for($i=0;$i+1<count($holder);$i++) {
							$query .= "'{$holder[$i]}', ";
						}
						$query .= "'{$holder[$i]}')";
						DB::query($query);
						$amount = DB::affectedRows();
						$this->alterationMessage("Changed $amount rows to default value of field $field (Value: $default)");
					}
				}
			}
			Profiler::mark('alterField');
			$this->transAlterField($table, $field, $spec_orig);
			Profiler::unmark('alterField');
			$this->alterationMessage("Field $table.$field: changed to $specValue <i style=\"color: #AAA\">(from {$fieldValue})</i>","changed");
		}
		Profiler::unmark('requireField');
	}
 /**
  * Cancel any cancellable jobs
  *
  * @param string $type Type of job to cancel
  * @return int Number of jobs cleared
  */
 protected function cancelExistingJobs($type)
 {
     $clearable = array(QueuedJob::STATUS_PAUSED, QueuedJob::STATUS_NEW, QueuedJob::STATUS_WAIT, QueuedJob::STATUS_INIT, QueuedJob::STATUS_RUN);
     DB::query(sprintf('UPDATE "QueuedJobDescriptor" ' . ' SET "JobStatus" = \'%s\'' . ' WHERE "JobStatus" IN (\'%s\')' . ' AND "Implementation" = \'%s\'', Convert::raw2sql(QueuedJob::STATUS_CANCELLED), implode("','", Convert::raw2sql($clearable)), Convert::raw2sql($type)));
     return DB::affectedRows();
 }
Example #12
0
 public function destroy()
 {
     DB::nonQuery('DELETE FROM `%s` WHERE `%s` = \'%s\' AND `%s` = %u AND `%s` = %u', array(static::$tableName, static::_cn('ContextClass'), $this->ContextClass, static::_cn('ContextID'), $this->ContextID, static::_cn('TagID'), $this->TagID));
     return DB::affectedRows() > 0;
 }
Example #13
0
 function test_7_insert_update()
 {
     $true = DB::insertUpdate('accounts', array('id' => 2, 'username' => 'gonesoon', 'password' => 'something', 'age' => 61, 'height' => 199.194), 'age = age + %i', 1);
     $this->assert($true === true);
     $this->assert(DB::affectedRows() === 2);
     // a quirk of MySQL, even though only 1 row was updated
     $result = DB::query("SELECT * FROM accounts WHERE age = %i", 16);
     $this->assert(count($result) === 1);
     $this->assert($result[0]['height'] === '10.371');
     DB::insertUpdate('accounts', array('id' => 2, 'username' => 'blahblahdude', 'age' => 233, 'height' => 199.194));
     $result = DB::query("SELECT * FROM accounts WHERE age = %i", 233);
     $this->assert(count($result) === 1);
     $this->assert($result[0]['height'] === '199.194');
     $this->assert($result[0]['username'] === 'blahblahdude');
     DB::insertUpdate('accounts', array('id' => 2, 'username' => 'gonesoon', 'password' => 'something', 'age' => 61, 'height' => 199.194), array('age' => 74));
     $result = DB::query("SELECT * FROM accounts WHERE age = %i", 74);
     $this->assert(count($result) === 1);
     $this->assert($result[0]['height'] === '199.194');
     $this->assert($result[0]['username'] === 'blahblahdude');
     $multiples[] = array('id' => 3, 'username' => 'gonesoon', 'password' => 'something', 'age' => 61, 'height' => 199.194);
     $multiples[] = array('id' => 1, 'username' => 'gonesoon', 'password' => 'something', 'age' => 61, 'height' => 199.194);
     DB::insertUpdate('accounts', $multiples, array('age' => 914));
     $this->assert(DB::affectedRows() === 4);
     $result = DB::query("SELECT * FROM accounts WHERE age=914 ORDER BY id ASC");
     $this->assert(count($result) === 2);
     $this->assert($result[0]['username'] === 'Abe');
     $this->assert($result[1]['username'] === 'Charlie\'s Friend');
     $true = DB::query("UPDATE accounts SET age=15, username='******' WHERE age=%i", 74);
     $this->assert($true === true);
     $this->assert(DB::affectedRows() === 1);
 }
Example #14
0
 /**
  * Generate the given field on the table, modifying whatever already exists as necessary.
  * @param string $table The table name.
  * @param string $field The field name.
  * @param string $spec The field specification.
  */
 function requireField($table, $field, $spec)
 {
     $newTable = false;
     Profiler::mark('requireField');
     // Collations didn't come in until MySQL 4.1.  Anything earlier will throw a syntax error if you try and use
     // collations.
     if (!$this->supportsCollations()) {
         $spec = eregi_replace(' *character set [^ ]+( collate [^ ]+)?( |$)', '\\2', $spec);
     }
     if (!isset($this->tableList[strtolower($table)])) {
         $newTable = true;
     }
     if (!$newTable && !isset($this->fieldList[$table])) {
         $this->fieldList[$table] = $this->fieldList($table);
     }
     if ($newTable || !isset($this->fieldList[$table][$field])) {
         Profiler::mark('createField');
         $this->transCreateField($table, $field, $spec);
         Profiler::unmark('createField');
         Database::alteration_message("Field {$table}.{$field}: created as {$spec}", "created");
     } else {
         if ($this->fieldList[$table][$field] != $spec) {
             // If enums are being modified, then we need to fix existing data in the table.
             // Update any records where the enum is set to a legacy value to be set to the default.
             // One hard-coded exception is SiteTree - the default for this is Page.
             if (substr($spec, 0, 4) == "enum") {
                 $new = substr($spec, 5);
                 $old = substr($this->fieldList[$table][$field], 5);
                 $new = substr($new, 0, strpos($new, ')'));
                 $old = substr($old, 0, strpos($old, ')'));
                 $new = str_replace("'", '', $new);
                 $old = str_replace("'", '', $old);
                 $new = explode(',', $new);
                 $old = explode(',', $old);
                 $holder = array();
                 foreach ($old as $check) {
                     if (!in_array($check, $new)) {
                         $holder[] = $check;
                     }
                 }
                 if (count($holder)) {
                     $default = explode('default ', $spec);
                     $default = $default[1];
                     if ($default == "'SiteTree'") {
                         $default = "'Page'";
                     }
                     $query = "UPDATE `{$table}` SET {$field}={$default} WHERE {$field} IN (";
                     for ($i = 0; $i + 1 < count($holder); $i++) {
                         $query .= "'{$holder[$i]}', ";
                     }
                     $query .= "'{$holder[$i]}')";
                     DB::query($query);
                     $amount = DB::affectedRows();
                     Database::alteration_message("Changed {$amount} rows to default value of field {$field} (Value: {$default})");
                 }
             }
             Profiler::mark('alterField');
             $this->transAlterField($table, $field, $spec);
             Profiler::unmark('alterField');
             Database::alteration_message("Field {$table}.{$field}: changed to {$spec} <i style=\"color: #AAA\">(from {$this->fieldList[$table][$field]})</i>", "changed");
         }
     }
     Profiler::unmark('requireField');
 }
Example #15
0
function verify_code()
{
    DB::query('UPDATE users SET email_verification=1 WHERE id=%i AND email_verification=%s LIMIT 1', $_GET['id'], $_GET['code']);
    if (DB::affectedRows() != 1) {
        trigger_error('ID or code incorrect', E_USER_ERROR);
    }
    set_login_data($id);
    // LOG THEM IN
    header('Location: Approve');
}
 public static function handleRequest()
 {
     // TODO: try global handle lookup?
     // resolve URL in root
     $resolvedNode = false;
     $rootNode = static::getRootCollection('site-root');
     // handle root request - default page
     if (empty(static::$pathStack[0]) && static::$defaultPage) {
         static::$pathStack[0] = static::$defaultPage;
     }
     // route request
     if (static::$pathStack[0] == 'emergence') {
         array_shift(static::$pathStack);
         return Emergence::handleRequest();
     } elseif (static::$pathStack[0] == 'parent-refresh' && $_REQUEST['key'] == static::$controlKey) {
         DB::nonQuery('DELETE FROM `%s` WHERE CollectionID IN (SELECT ID FROM `%s` WHERE SiteID != %u)', array(SiteFile::$tableName, SiteCollection::$tableName, Site::getSiteID()));
         die('Cleared ' . DB::affectedRows() . ' cached files');
     } else {
         $resolvedNode = $rootNode;
         $resolvedPath = array();
         while ($handle = array_shift(static::$pathStack)) {
             $scriptHandle = substr($handle, -4) == '.php' ? $handle : $handle . '.php';
             //printf('%s: (%s)/(%s) - %s<br>', $resolvedNode->Handle, $handle, implode('/',static::$pathStack), $scriptHandle);
             if ($resolvedNode && method_exists($resolvedNode, 'getChild') && (($childNode = $resolvedNode->getChild($handle)) || $scriptHandle && ($childNode = $resolvedNode->getChild($scriptHandle))) || ($childNode = Emergence::resolveFileFromParent('site-root', array_merge($resolvedPath, array($handle)))) || $scriptHandle && ($childNode = Emergence::resolveFileFromParent('site-root', array_merge($resolvedPath, array($scriptHandle))))) {
                 $resolvedNode = $childNode;
                 if (is_a($resolvedNode, 'SiteFile')) {
                     break;
                 }
             } else {
                 $resolvedNode = false;
                 //break;
             }
             $resolvedPath[] = $handle;
         }
     }
     if ($resolvedNode) {
         // create session
         if (static::$autoCreateSession && $resolvedNode->MIMEType == 'application/php') {
             $GLOBALS['Session'] = UserSession::getFromRequest();
         }
         if (is_callable(static::$onRequestMapped)) {
             call_user_func(static::$onRequestMapped, $resolvedNode);
         }
         if ($resolvedNode->MIMEType == 'application/php') {
             require $resolvedNode->RealPath;
             exit;
         } elseif (!is_callable(array($resolvedNode, 'outputAsResponse'))) {
             //throw new Exception('Node does not support rendering');
             static::respondNotFound();
         } else {
             $resolvedNode->outputAsResponse();
         }
     } else {
         static::respondNotFound();
     }
 }
<?php

/* ---  kontrola jadra  --- */
if (!defined('_core')) {
    exit;
}
/* ---  odstraneni ankety  --- */
$message = "";
if (isset($_GET['del']) && _xsrfCheck(true)) {
    $del = intval($_GET['del']);
    DB::query("DELETE FROM `" . _mysql_prefix . "-polls` WHERE id=" . $del . _admin_pollAccess());
    if (DB::affectedRows() != 0) {
        $message = _formMessage(1, $_lang['global.done']);
    }
}
/* ---  vystup  --- */
// filtr autoru
if (_loginright_adminpollall and isset($_GET['author']) and $_GET['author'] != -1) {
    $pasep = true;
    $author_filter_id = intval($_GET['author']);
    $author_filter = "author=" . intval($_GET['author']);
} else {
    $pasep = false;
    $author_filter = "";
    $author_filter_id = -1;
}
$output .= "\n<p class='bborder'>" . $_lang['admin.content.polls.p'] . "</p>\n<p><img src='images/icons/new.png' class='icon' alt='new' /><a href='index.php?p=content-polls-edit'>" . $_lang['admin.content.polls.new'] . "</a></p>\n";
// filtr
if (_loginright_adminpollall) {
    $output .= "\n  <form class='cform' action='index.php' method='get'>\n  <input type='hidden' name='p' value='content-polls' />\n  <strong>" . $_lang['admin.content.polls.filter'] . ":</strong> " . _admin_authorSelect("author", $author_filter_id, "adminpoll=1", null, $_lang['global.all2']) . " <input type='submit' value='" . $_lang['global.apply'] . "' />\n  </form>\n  ";
}
Example #18
0
<?php

$GLOBALS['Session']->requireAccountLevel('Developer');
header('Content-Type: text/plain');
// delete orphan collections
DB::nonQuery('DELETE c3 FROM (SELECT c1.* FROM _e_file_collections c1 LEFT JOIN _e_file_collections c2 ON c2.ID = c1.ParentID WHERE c1.ParentID IS NOT NULL AND c2.ID IS NULL) orphan JOIN _e_file_collections c3 ON (c3.PosLeft BETWEEN orphan.PosLeft AND orphan.PosRight)');
printf("Deleted %u orphan collections\n", DB::affectedRows());
// delete orphan files
DB::nonQuery('DELETE f FROM _e_files f LEFT JOIN _e_file_collections c ON c.ID = f.CollectionID WHERE c.ID IS NULL');
printf("Deleted %u orphan files\n", DB::affectedRows());
Example #19
0
<?php

require_once __DIR__ . '/../all.php';
$cookies = new Cookies();
$user = $cookies->user_from_cookie();
$vars = array("id", "service_id");
if (set_vars($_POST, $vars)) {
    if ($user->data["permission"] === "4" || $user->data["permission"] === "3" && $user->data["service_id"] === $_POST["service_id"]) {
        //        DB::insert("menu_sides", array("name"=>$_POST["name"], "price"=>$_POST["price"], "required"=>$_POST["req"], "service_id"=>$_POST["service_id"]));
        DB::delete("menu_categories", "id=%d", $_POST["id"]);
        echo DB::affectedRows();
    } else {
        echo "-1";
    }
} else {
    echo "-1";
}
Example #20
0
 /**
  * Tests affectedRows()
  */
 public function testAffectedRows()
 {
     $this->assertSame(mysql_affected_rows(), DB::affectedRows());
 }
                }
                $sql .= '';
                DB::query($sql);
            }
            // message
            $done = isset($last) ? $last + 1 : count($done);
            $message = _formMessage($done === $total ? 1 : 2, sprintf($_lang['admin.content.manageimgs.upload.msg'], $done, $total));
            break;
    }
}
/* ---  odstraneni obrazku  --- */
if (isset($_GET['del']) && _xsrfCheck(true) && $continue) {
    $del = intval($_GET['del']);
    _tmpGalStorageCleanOnDel('id=' . $del . ' AND home=' . $g);
    DB::query("DELETE FROM `" . _mysql_prefix . "-images` WHERE id=" . $del . " AND home=" . $g);
    if (DB::affectedRows() === 1) {
        $message = _formMessage(1, $_lang['global.done']);
    }
}
/* ---  vystup  --- */
if ($continue) {
    $output .= "\n<a href='index.php?p=content-editgallery&amp;id=" . $g . "' class='backlink'>&lt; návrat zpět</a>\n<h1>" . $_lang['admin.content.manageimgs.title'] . "</h1>\n<p class='bborder'>" . str_replace("*galtitle*", $galdata['title'], $_lang['admin.content.manageimgs.p']) . "</p>\n\n" . $message . "\n\n<script type='text/javascript'>\n/* <![CDATA[ */\n\$(document).ready(function(){\n    \$('.hs_fieldset').each(function(){\n        var fieldset = this;\n        var link = \$(fieldset).find('legend > a').get(0);\n        var form = \$(fieldset).children('form');\n        \$(form).hide();\n        \$(link).click(function(){\n            \$(form).slideToggle('fast');\n\n            return false;\n        });\n    });\n});\n/* ]]> */\n</script>\n\n<fieldset>\n<legend>" . $_lang['admin.content.manageimgs.upload'] . "</legend>\n<form action='index.php?p=content-manageimgs&amp;g=" . $g . "' method='post' enctype='multipart/form-data'>\n    <p>" . sprintf($_lang['admin.content.manageimgs.upload.text'], _galuploadresize_w, _galuploadresize_h) . "</p>\n    <input type='hidden' name='xaction' value='7' />\n    <div id='fmanFiles'><input type='file' name='uf0[]' multiple='multiple' />&nbsp;&nbsp;<a href='#' onclick='return _sysFmanAddFile();'>" . $_lang['admin.fman.upload.addfile'] . "</a></div>\n    <div class='hr'><hr /></div>\n    <p>\n        <input type='submit' value='" . $_lang['admin.content.manageimgs.upload.submit'] . "' />" . (($uplimit = _getUploadLimit(true)) !== null ? " &nbsp;<small>" . $_lang['global.uploadlimit'] . ": <em>" . _getUploadLimit() . "MB</em>, " . $_lang['global.uploadext'] . ": <em>" . implode(', ', SL::$imageExt) . "</em></small>" : '') . "<br />\n        <label><input type='checkbox' value='1' name='moveords' checked='checked' /> " . $_lang['admin.content.manageimgs.moveords'] . "</label>\n    </p>\n" . _xsrfProtect() . "</form>\n</fieldset>\n\n<fieldset class='hs_fieldset'>\n<legend><a href='#'>" . $_lang['admin.content.manageimgs.insert'] . "</a> &nbsp;<small>(" . $_lang['admin.content.manageimgs.insert.tip'] . ")</small></legend>\n<form action='index.php?p=content-manageimgs&amp;g=" . $g . "' method='post' name='addform' onsubmit='_sysGalTransferPath(this);'>\n<input type='hidden' name='xaction' value='1' />\n\n<table>\n<tr class='valign-top'>\n\n<td>\n    <table>\n    <tr>\n    <td class='rpad'><strong>" . $_lang['admin.content.form.title'] . "</strong></td>\n    <td><input type='text' name='title' class='inputmedium' maxlength='64' /></td>\n    </tr>\n\n    <tr>\n    <td class='rpad'><strong>" . $_lang['admin.content.form.ord'] . "</strong></td>\n    <td><input type='text' name='ord' class='inputsmall' disabled='disabled' />&nbsp;&nbsp;<label><input type='checkbox' name='moveords' value='1' checked='checked' onclick=\"_sysDisableField(this.checked, 'addform', 'ord');\" /> " . $_lang['admin.content.manageimgs.moveords'] . "</label></td>\n    </tr>\n\n    <tr>\n    <td class='rpad'><strong>" . $_lang['admin.content.manageimgs.prev'] . "</strong></td>\n    <td><input type='text' name='prev' class='inputsmall' disabled='disabled' />&nbsp;&nbsp;<label><input type='checkbox' name='autoprev' value='1' checked='checked' onclick=\"_sysDisableField(this.checked, 'addform', 'prev');\" /> " . $_lang['admin.content.manageimgs.autoprev'] . "</label></td>\n    </tr>\n\n    <tr>\n    <td class='rpad'><strong>" . $_lang['admin.content.manageimgs.full'] . "</strong></td>\n    <td><input type='text' name='full' class='inputmedium' /></td>\n    </tr>\n\n    <tr>\n    <td></td>\n    <td><input type='submit' value='" . $_lang['global.insert'] . "' /></td>\n    </tr>\n\n    </table>\n</td>\n\n<td>\n" . (_loginright_adminfman ? "<div id='gallery-browser'>\n    " . (!isset($_GET['browserpath']) ? "<a href='#' onclick=\"return _sysGalBrowse('" . urlencode(_upload_dir) . (_loginright_adminfmanlimit ? _loginname . '%2F' : '') . "');\"><img src='images/icons/loupe.png' alt='browse' class='icon' />" . $_lang['admin.content.manageimgs.insert.browser.link'] . "</a>" : "<script type='text/javascript'>_sysGalBrowse('" . _htmlStr($_GET['browserpath']) . "');</script>") . "\n</div>" : '') . "\n</td>\n\n</tr>\n</table>\n\n" . _xsrfProtect() . "</form>\n</fieldset>\n\n";
    // strankovani
    $paging = _resultPaging("index.php?p=content-manageimgs&amp;g=" . $g, $galdata['var2'], "images", "home=" . $g);
    $s = $paging[2];
    $output .= "\n<fieldset>\n<legend>" . $_lang['admin.content.manageimgs.current'] . "</legend>\n<form action='index.php?p=content-manageimgs&amp;g=" . $g . "&amp;page=" . $s . "' method='post' name='editform'>\n<input type='hidden' name='xaction' value='4' />\n\n<input type='submit' value='" . $_lang['admin.content.manageimgs.savechanges'] . "' class='gallery-savebutton' />\n" . $paging[0] . "\n<div class='cleaner'></div>";
    // vypis obrazku
    $images = DB::query("SELECT * FROM `" . _mysql_prefix . "-images` WHERE home=" . $g . " ORDER BY ord " . $paging[1]);
    $images_forms = array();
    if (DB::size($images) != 0) {
        // sestaveni formularu
<?php

$GLOBALS['Session']->requireAccountLevel('Developer');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    DB::nonQuery('DELETE FROM `%s` WHERE CollectionID IN (SELECT ID FROM `%s` WHERE Site != "Local")', array(SiteFile::$tableName, SiteCollection::$tableName));
    print 'Cleared ' . DB::affectedRows() . ' cached files<br>' . PHP_EOL;
    DB::nonQuery('DELETE FROM `%s` WHERE Site != "Local"', array(SiteCollection::$tableName));
    die('Cleared ' . DB::affectedRows() . ' cached collections');
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Clear Parent Site Cache + Nuke Collections</title>
    <style>
        * {
            font-size: xx-large;
            text-align: center;
        }

        input {
            cursor: pointer;
            margin: 1em;
        }

        em strong {
            color: #c00;
        }
    </style>
</head>
 public function destroy()
 {
     DB::nonQuery('DELETE FROM `%s` WHERE ContextClass = "%s" AND ContextID = %u AND CategoryID = %u', array(static::$tableName, DB::escape($ContextClass), $ContextID, $CategoryID));
     return DB::affectedRows() > 0;
 }
Example #24
0
 public static function synchronize(Job $Job, $pretend = true)
 {
     if ($Job->Status != 'Pending' && $Job->Status != 'Completed') {
         return static::throwError('Cannot execute job, status is not Pending or Complete');
     }
     // update job status
     $Job->Status = 'Pending';
     if (!$pretend) {
         $Job->save();
     }
     // init results struct
     $results = array('events' => array('analyzed' => 0, 'created' => 0, 'updated' => 0, 'deleted' => 0, 'skipped' => 0));
     // uncap execution time
     set_time_limit(0);
     $now = time();
     $nowString = date('Y-m-d H:i:s', $now);
     // compile course upload data
     foreach (Feed::getAll() as $Feed) {
         $ics = new iCal($Feed->Link);
         foreach ($ics->getEvents() as $icsEvent) {
             if ($Feed->MinimumDate && $Feed->MinimumDate > $icsEvent->getStart()) {
                 $results['events']['skipped']++;
                 continue;
             }
             $results['events']['analyzed']++;
             $icsId = $icsEvent->getUID();
             if ($recurrenceId = $icsEvent->getProperty('recurrence-id')) {
                 $icsId .= '+' . $recurrenceId;
             }
             // try to get existing
             if (!($Event = FeedEvent::getByUID($icsId))) {
                 $Event = FeedEvent::create(array('UID' => $icsId));
             }
             $description = trim($icsEvent->getDescription());
             $location = trim($icsEvent->getLocation());
             $Event->setFields(array('Title' => $icsEvent->getSummary(), 'Description' => $description ? $description : null, 'Location' => $location ? $location : null, 'StartTime' => $icsEvent->getStart(), 'EndTime' => $icsEvent->getEnd(), 'FeedID' => $Feed->ID, 'Imported' => $now));
             $logEntry = $Job->logRecordDelta($Event, array('messageRenderer' => function ($logEntry) {
                 if ($logEntry['action'] == 'create') {
                     return "Created new event: {$logEntry[record]->Title}";
                 } else {
                     return "Updated event #{$logEntry[record]->ID}: {$logEntry[record]->Title}";
                 }
             }, 'ignoreFields' => array('Imported'), 'valueRenderers' => array('StartTime' => function ($value) {
                 return date('Y-m-d H:i:s', $value);
             }, 'EndTime' => function ($value) {
                 return date('Y-m-d H:i:s', $value);
             })));
             if ($logEntry['action'] == 'create') {
                 $results['events']['created']++;
             } elseif ($logEntry['action'] == 'update') {
                 $results['events']['updated']++;
             }
             if (!$pretend) {
                 $Event->save();
             }
         }
         if (!$pretend) {
             // delete events that came from this feed but weren't included this time
             \DB::nonQuery('DELETE FROM `%s` WHERE FeedID = %u AND Imported != "%s"', array(FeedEvent::$tableName, $Feed->ID, $nowString));
         }
         $results['events']['deleted'] += \DB::affectedRows();
     }
     // save job results
     $Job->Status = 'Completed';
     $Job->Results = $results;
     if (!$pretend) {
         $Job->save();
     }
     return true;
 }
Example #25
0
         break;
     }
 case 'decline':
     $friend_id = getID($this->args['var_b']);
     $db = new DB("friends");
     $db->delete("friend_receiver = '" . USER_ID . "' AND friend_sender = '" . $friend_id . "' AND friend_status='0'");
     if ($db->affectedRows()) {
         //$notif->add($friend_id, "friend", json_encode(array("type" => "decline", "user" => USER_ID)));
         break;
     }
 case 'remove':
     $friend_id = getID($this->args['var_b']);
     $db = new DB("friends");
     $db->delete("friend_receiver = '" . $friend_id . "' AND friend_sender = '" . USER_ID . "' AND friend_status='1'");
     $db->delete("friend_receiver = '" . USER_ID . "' AND friend_sender = '" . $friend_id . "' AND friend_status='1'");
     if ($db->affectedRows()) {
         //$notif->add($friend_id, "friend", json_encode(array("type" => "remove", "user" => USER_ID)));
         break;
     }
 case 'add':
     $friend_id = getID($this->args['var_b']);
     if ($friend_id == USER_ID) {
         throw new Exception("Cannot add your self as friend");
     }
     $db = new DB("friends");
     $db->select("friend_receiver = '" . $friend_id . "' AND friend_sender = '" . USER_ID . "'");
     if (!$db->numRows()) {
         $db->nextRecord();
         if ($db->status == 0) {
             $db = new DB("friends");
             $db->friend_sender = USER_ID;
 protected function currencyToMoneyFields_30()
 {
     $explanation = "\r\n\t\t\t<h1>30. Currency to Money Fields</h1>\r\n\t\t\t<p>Move the Payment Amount in the Amount field to a composite DB field (AmountAmount + AmountCurrency) </p>\r\n\t\t";
     if ($this->retrieveInfoOnly) {
         return $explanation;
     } else {
         echo $explanation;
     }
     if ($this->hasTableAndField("Payment", "Amount")) {
         //ECOMMERCE PAYMENT *************************
         DB::query("\r\n\t\t\t\tUPDATE \"Payment\"\r\n\t\t\t\tSET \"AmountAmount\" = \"Amount\"\r\n\t\t\t\tWHERE\r\n\t\t\t\t\t\"Amount\" > 0\r\n\t\t\t\t\tAND (\r\n\t\t\t\t\t\t\"AmountAmount\" IS NULL OR \"AmountAmount\" = 0\r\n\t\t\t\t\t)\r\n\t\t\t");
         $countAmountChanges = DB::affectedRows();
         if ($countAmountChanges) {
             $this->DBAlterationMessageNow("Updated Payment.Amount field to 2.4 - {$countAmountChanges} rows updated", "edited");
         }
     } else {
         $this->DBAlterationMessageNow('There is no need to move Payment.Amount to Payment.AmountAmount');
     }
     if ($this->hasTableAndField("Payment", "Currency")) {
         DB::query("\r\n\t\t\t\tUPDATE \"Payment\"\r\n\t\t\t\tSET \"AmountCurrency\" = \"Currency\"\r\n\t\t\t\tWHERE\r\n\t\t\t\t\t\"Currency\" <> ''\r\n\t\t\t\t\tAND \"Currency\" IS NOT NULL\r\n\t\t\t\t\tAND (\r\n\t\t\t\t\t\t\"AmountCurrency\" IS NULL\r\n\t\t\t\t\t\tOR \"AmountCurrency\" = ''\r\n\t\t\t\t\t)\r\n\t\t\t");
         $countCurrencyChanges = DB::affectedRows();
         if ($countCurrencyChanges) {
             $this->DBAlterationMessageNow("Updated Payment.Currency field to 2.4  - {$countCurrencyChanges} rows updated", "edited");
         }
         if ($countAmountChanges != $countCurrencyChanges) {
             $this->DBAlterationMessageNow("Potential error in Payment fields update to 2.4, please review data", "deleted");
         }
     } else {
         $this->DBAlterationMessageNow('There is no need to move Payment.Currency to Payment.AmountCurrency');
     }
 }
Example #27
0
" />&nbsp;&nbsp;<a href="#" onclick="return _admin_tableName();"><?php 
echo $_lang['admin.other.sqlex.tablename.hint'];
?>
</a>
<?php 
echo _xsrfProtect();
?>
</form>

<?php 
if ($process) {
    echo '<h2>' . $_lang['global.result'] . '</h2><br />';
    $query = DB::query($sql, true);
    if (DB::error() == null) {
        $fields = array();
        $aff_rows = DB::affectedRows();
        if ($query) {
            $num_rows = intval(DB::size($query));
        } else {
            $num_rows = 0;
        }
        $heading = false;
        if ($num_rows != 0) {
            echo '<p><strong>' . $_lang['admin.other.sqlex.rows'] . ':</strong> ' . $num_rows . '</p>
<table class="list">' . "\n";
            while ($item = DB::row($query)) {
                // nacteni sloupcu, vytvoreni hlavicky tabulky
                if (!$heading) {
                    // sloupce
                    $load = false;
                    foreach ($item as $field => $value) {
 /**
  * Update admin settings.
  *
  * @param array   $post_data
  * @param integer $active_user
  *
  * @return boolean
  */
 function update_settings($post_data = array(), $active_user = 0)
 {
     if (count($post_data) == 0 || $active_user == 0) {
         return false;
     }
     $admins = "";
     $settings_table_name = TABLE_PREFIX . 'rt_config_settings';
     DB::execute("UPDATE  {$settings_table_name} SET config_settings = '" . serialize($post_data) . "'");
     return DB::affectedRows();
 }
 public static function delete($id)
 {
     DB::nonQuery('DELETE FROM `%s` WHERE `%s` = %u', array(static::$tableName, static::_cn('ID'), $id));
     static::_invalidateRecordCaches($id);
     return DB::affectedRows() > 0;
 }
Example #30
0
 /**
  * Updates a file
  * @param  [int] $fileId File ID
  * @param  [int] $name File name
  * @param  [int] $data File data
  * @param  [string] $tokenValue
  * @return [int] -1 if invalid token, 1 if valid token and file was updated, 0, if valid token, but file content was same (no update performed)
  */
 public static function update($id, $name, $data, $tokenValue)
 {
     $result = -1;
     if (CWM_API::IsTokenValid($tokenValue)) {
         DB::update('CWM_File', array('Name' => $name, 'Data' => $data), "Id=%?", $id);
         $result = DB::affectedRows();
     }
     return $result;
 }