public function parse_cookie($cookie) { // Parse the given cookie if (!preg_match("/^uid:(\\d+):([a-z0-9]+):([a-z0-9]+)\$/", $cookie, $m)) { Logger::log("Invalid login cookie received: {$cookie}", LOGGER_WARNING); // Invalid cookie - ignore it return FALSE; } list(, $this->user_id, $this->series, $this->token) = $m; $this->user_id = (int) $this->user_id; // Flush old cookies Dal::query("DELETE FROM login_cookies WHERE expires < NOW()"); // Locate our cookie $r = Dal::query_one("SELECT token FROM login_cookies WHERE user_id=? AND series=?", array($this->user_id, $this->series)); if (!$r) { // Totally invalid - we don't even know of the series. Probably timed out. return FALSE; } list($token) = $r; if ($token != $this->token) { // Possible attack detected - invalidate all sessions for this user Dal::query("DELETE FROM login_cookies WHERE user_id=?", array($this->user_id)); Logger::log("Invalidated all sessions for user {$this->user_id} as a valid series ID but invalid token was presented -- someone has possibly had their login cookie stolen!", LOGGER_WARNING); return FALSE; } // Success -- assign a new token $this->token = $this->make_token(); Dal::query("UPDATE login_cookies SET token=?, expires=DATE_ADD(NOW(), INTERVAL " . LoginCookie::$cookie_lifetime . " SECOND) WHERE user_id=? AND series=?", array($this->token, $this->user_id, $this->series)); return $this->user_id; }
public function delete($leaf) { //TODO: use innodb so this actually matters list($file_id, $servers) = Dal::query_one("SELECT file_id, servers FROM local_files WHERE filename=? FOR UPDATE", array($leaf)); try { if (!$file_id) { throw new PAException(FILE_NOT_FOUND, "Unable to find file {$leaf} in local_files table:"); } $path = $this->getPath($leaf); $server_ids = explode(",", $servers); if (in_array(PA::$server_id, $server_ids)) { if (empty($path)) { throw new PAException(FILE_NOT_FOUND, "Unable to delete nonexistent file {$path}"); } if (!@unlink($path)) { throw new PAException(STORAGE_ERROR, "Error deleting {$path}"); } $server_ids = array_filter($server_ids, "not_this_server"); $servers = implode(",", $server_ids); } Dal::query("UPDATE local_files SET is_deletion=1, timestamp=NOW(), servers=? WHERE file_id=?", array($file_id, $servers)); } catch (PAException $e) { Dal::rollback(); throw $e; } return TRUE; }
public static function getExtCache($user_id, $key) { $row = Dal::query_one("SELECT data FROM ext_cache WHERE user_id=? AND cache_key=? AND expires < NOW()", array($user_id, $key)); if ($row) { return unserialize($row[0]); } return NULL; }
public function load_first($user_id, $album_type) { $this->album_type = $album_type; $sql = "SELECT CC.collection_id FROM {contentcollections} as CC, {contentcollections_albumtype} AS CCA WHERE CC.collection_id = CCA.contentcollection_id AND CCA.album_type_id = ? AND CC.is_active = ? AND CC.author_id = ? AND CC.type = ? order by CC.collection_id"; $data = array($album_type, 1, $user_id, 2); $r = Dal::query_one($sql, $data); if (empty($r)) { throw new PAException(CONTENT_COLLECTION_NOT_FOUND, "No albums of type {$album_type} found"); } list($collection_id) = $r; $this->load($collection_id); }
function testProfileReadingFunctions() { // find a user with 'newcss' set list($uid, $css) = Dal::query_one("SELECT user_id, field_value FROM user_profile_data WHERE field_type='ui' AND field_name='newcss' ORDER BY user_id LIMIT 1"); if (empty($uid)) { echo "Test not possible as nobody has the newcss field set. Try again on a more populated database.\n"; return; } // find another field, so we can test with more than one list($f2_name, $f2_value) = Dal::query_one("SELECT field_name, field_value FROM user_profile_data WHERE field_type='ui' AND user_id=? AND field_name <>'newcss' AND field_value IS NOT NULL LIMIT 1", $uid); echo "getting ui/newcss and {$f2_name} properties from user_profile_data for user_id {$uid}.\n"; $user = new User(); $user->load((int) $uid); // load just the newcss field echo "getting just the newcss property for user {$uid}\n"; $css2 = $user->get_profile_field('ui', 'newcss'); $this->assertEquals($css, $css2); // load just the second field echo "getting just the {$f2_name} property for user {$uid}\n"; $v = $user->get_profile_field('ui', $f2_name); $this->assertEquals($v, $f2_value); // load newcss and the second field, with get_profile_fields() echo "getting the newcss and {$f2_name} properties, with get_profile_fields()\n"; $data = $user->get_profile_fields('ui', array('newcss', 'graagh', $f2_name)); $this->assertEquals($css, $data['newcss']); $this->assertEquals(NULL, $data['graagh']); $this->assertEquals($f2_value, $data[$f2_name]); // try again, flushing the cache first Cache::reset(); echo "(without cache) getting the newcss and {$f2_name} properties, with get_profile_fields()\n"; $data = $user->get_profile_fields('ui', array('newcss', 'graagh', $f2_name)); $this->assertEquals($css, $data['newcss']); $this->assertEquals(NULL, $data['graagh']); $this->assertEquals($f2_value, $data[$f2_name]); // regression test (phil) 2007-04-01, for bug spotted by martin // 2007-03-23: make sure we don't crash if we request fields that // are all cached. echo "regression: make sure it doesn't crash if everything is in the cache\n"; $data = $user->get_profile_fields('ui', array('newcss')); $this->assertEquals($css, $data['newcss']); // try by loading the entire 'ui' section echo "getting entire ui section for user {$uid}\n"; $ui = User::load_profile_section($uid, "ui"); $this->assertEquals($css, $ui['newcss']['value']); $this->assertEquals($f2_value, $ui[$f2_name]['value']); }
function explain_query($sql, $args, $query_time) { if (!preg_match("/^\\s*SELECT/i", $sql)) { return; } echo "================================================================================\n"; echo sprintf("%.04f s | SQL: %s\n", $query_time, $sql); global $_timed_queries; $_timed_queries[$sql][] = $query_time; $explain = Dal::query("EXPLAIN {$sql}", $args); $tables = array(); while ($r = Dal::row_assoc($explain)) { if (!empty($r['table'])) { $tables[] = $r['table']; } echo "\n"; foreach ($r as $k => $v) { echo sprintf("%15s: %s\n", $k, $v); } } foreach ($tables as $table) { echo "--------------------------------------------------------------------------------\n"; try { $create_table = Dal::query_one("SHOW CREATE TABLE {$table}"); } catch (PAException $e) { if ($e->getCode() != DB_QUERY_FAILED) { throw $e; } $bits = preg_split("/(\\s+|,)/", $sql); $pos = array_search($table, $bits); if ($pos === NULL) { throw new PAException(GENERAL_SOME_ERROR, "Failed to find real name for table {$table} in query {$sql}"); } $table = strtolower($bits[$pos - 1]) == 'as' ? $bits[$pos - 2] : $bits[$pos - 1]; $create_table = Dal::query_one("SHOW CREATE TABLE {$table}"); } echo $create_table[1] . "\n"; } }
public static function count_all_content() { list($ct) = Dal::query_one("SELECT COUNT(*) FROM {contents}"); return $ct; }
/** * get the login name from the user id */ public static function get_login_name_from_id($user_id) { Logger::log("Enter: function User::get_login_name_from_id with user_id=" . $user_id); list($login) = Dal::query_one("SELECT login_name FROM {users} WHERE user_id=? AND is_active=1", array($user_id)); Logger::log("Exit: function User::get_login_name_from_id"); return $login; }
public function run(PHPUnit_Framework_TestResult $result = NULL) { if ($result === NULL) { $result = new PHPUnit_Framework_TestResult(); $result->startTest($this); $counter = 0; foreach ($this->queries as $query_data) { $query = 'EXPLAIN ' . $query_data['query']; $parameters = $query_data['parameters']; $parameters_print = ''; try { if (!empty($parameters)) { $res = Dal::query($query, $parameters); $parameters_print = 'PARAMETERS:' . "\n"; foreach ($parameters as $param) { $parameters_print .= '- ' . $param . "\n"; } } else { $res = Dal::query($query); } } catch (PAException $e) { try { PHPUnit_Framework_Assert::assertEquals($e->getCode(), DB_QUERY_FAILED); } catch (PHPUnit_Framework_AssertionFailedError $e) { $result->addFailure($this, $e); } catch (Exception $e) { $result->addError($this, $e); } } $tables = array(); print "{{{ ==================================================================\n"; $query_row = wordwrap($explain . "QUERY: \"{$query}\"", 70); print $query_row . "\n"; if (!empty($parameters_print)) { print "----------------------------------------------------------------------\n"; print $parameters_print; } while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) { print "----------------------------------------------------------------------\n"; print 'ID: ' . $row->id . "\n"; print 'SELECT TYPE: ' . $row->select_type . "\n"; print 'TABLE: ' . $row->table . "\n"; if (!empty($row->table)) { $tables[] = $row->table; } print 'TYPE: ' . $row->type . "\n"; print 'POSSIBLE KEYS: ' . $row->possible_keys . "\n"; print 'KEY: ' . $row->key . "\n"; print 'KEY LENGTH: ' . $row->key_len . "\n"; print 'REFERENCE: ' . $row->ref . "\n"; print 'ROWS: ' . $row->rows . "\n"; print 'EXTRA: ' . $row->Extra . "\n"; $counter++; } // Now show all the tables used in the query. foreach ($tables as $table) { print "----------------------------------------------------------------------\n"; try { $create_table = Dal::query_one("SHOW CREATE TABLE {$table}"); } catch (PAException $e) { if ($e->getCode() != DB_QUERY_FAILED) { throw $e; } $bits = preg_split("/(\\s+|,)/", $query); $pos = array_search($table, $bits); if ($pos === NULL) { throw new PAException(GENERAL_SOME_ERROR, "Failed to find real name for table {$table} in query {$sql}"); } $table = strtolower($bits[$pos - 1]) == 'as' ? $bits[$pos - 2] : $bits[$pos - 1]; $create_table = Dal::query_one("SHOW CREATE TABLE {$table}"); } echo $create_table[1] . "\n"; } print "================================================================== }}}\n"; } $result->endTest($this); return $result; } }
static function add_spam_term($term, $blacklist = 1) { $r = Dal::query_one("SELECT id FROM spam_terms WHERE term=?", array($term)); if ($r[0]) { return; } // we already have this term Dal::query("INSERT INTO spam_terms SET term=?, blacklist=?", array($term, $blacklist)); }
function render_main_page_area($user) { global $admin_password; $page_url = PA::$url . "/comment_management.php"; $paging_url = "{$page_url}?"; // url to pass to the pager object $msg = ""; $path_info = @$_SERVER['PATH_INFO']; // see if the user is logged in as an admin if ($path_info == "/login") { if (@$_REQUEST['admin_password'] == $admin_password) { $_SESSION['comment_management_is_admin'] = TRUE; } else { $msg = "Incorrect password! Try again..."; } } else { if ($path_info == "/logout") { $_SESSION['comment_management_is_admin'] = FALSE; $msg = "You are now logged out (of admin mode)."; } } $is_admin = @$_SESSION['comment_management_is_admin']; $limit_set = NULL; // set this to an array with keys 'comment_id' to limit display to those keys $current_search_terms = NULL; // current search terms switch ($path_info) { case '/analyze_comment': $comment_id = (int) @$_REQUEST['comment']; if (!$is_admin) { $msg = "Sorry, only administrators can analyze comments at the moment :("; } elseif ($comment_id) { $cmt = new Comment(); $cmt->load($comment_id); $cmt->index_spam_domains(); $msg = "<p>Analysis of comment {$comment_id}:</p><hr/><p>" . nl2br(htmlspecialchars($cmt->comment)) . "</p><hr/><ul>"; $hosts = $cmt->get_link_hosts(); foreach ($hosts as $domain => $links) { $msg .= "<li><b>" . htmlspecialchars($domain) . "</b> (<a href=\"{$page_url}/analyze_domain?domain=" . htmlspecialchars($domain) . "\">analyze</a>): "; $dom = new SpamDomain($domain); if ($dom->blacklisted) { $msg .= " BLACKLISTED"; } $msg .= "<ul>"; foreach ($links as $link) { list($url, $linktexts) = $link; $msg .= "<li>" . htmlspecialchars($url) . " -> " . implode(" | ", array_map("htmlspecialchars", $linktexts)) . "</li>"; } $msg .= "</ul></li>"; } $msg .= "</ul><hr/>"; } break; case '/search': $current_search_terms = @$_REQUEST['q']; if (!$is_admin) { $msg = "Sorry, only administrators can search comments at the moment :("; } elseif ($current_search_terms) { $paging_url = "{$page_url}/search?q=" . urlencode($current_search_terms) . "&"; $limit_set = Comment::search($current_search_terms); } break; case '/stats': $msg = "<p>Stats:</p>"; list($n) = Dal::query_one("SELECT COUNT(*) FROM {comments}"); list($n_deleted) = Dal::query_one("SELECT COUNT(*) FROM {comments} WHERE is_active=0"); $n_active = $n - $n_deleted; $msg .= "<li>{$n} comments ({$n_active} active / {$n_deleted} deleted)</li>"; list($n_ham) = Dal::query_one("SELECT COUNT(*) FROM {comments} WHERE is_active=1 AND spam_state=0"); $n_spam = $n_active - $n_ham; $msg .= "<li>{$n_spam} active+spam / {$n_ham} active+not spam</li>"; list($n_no_class) = Dal::query_one("SELECT COUNT(*) FROM {comments} WHERE is_active=1 AND akismet_spam IS NULL"); $msg .= "<li>{$n_no_class} active comments not (yet?) classified by Akismet</li>"; list($n_akismet_del) = Dal::query_one("SELECT COUNT(*) FROM {comments} WHERE is_active=0 AND akismet_spam=1"); $msg .= "<li>{$n_akismet_del} comments flagged as spam by akismet and deleted</li>"; break; case '/add_spam_term': $spam_term = @$_REQUEST['term']; if (!$is_admin) { $msg = "Sorry, only administrators can add spam terms at the moment."; } elseif ($spam_term) { // find the comments $matches = Comment::search($spam_term); $n_deleted = count($matches); // add the term Comment::add_spam_term($spam_term); // and delete the comments $blk_size = 1000; $F_fetch_ids = create_function('$item', 'return $item["comment_id"];'); for ($i = 0; $i < count($matches); $i += $blk_size) { Comment::set_spam_state(array_map($F_fetch_ids, array_slice($matches, $i, $blk_size)), SPAM_STATE_SPAM_WORDS); } $msg = "Added <b>" . htmlspecialchars($spam_term) . '</b> to the spam term database, and deleted ' . $n_deleted . ' comments containing it.'; } break; case '/analyze_domain': $domain = @$_REQUEST['domain']; if (!$is_admin) { $msg = "Sorry, only administrators can analyze domains."; } else { $msg .= "<p>analysis of domain " . htmlspecialchars($domain) . ":</p><ul>"; $domain = new SpamDomain($domain); foreach ($domain->find_associated_domains() as $r) { $msg .= "<li>" . $r['domain'] . " (" . $r['domain_id'] . "): " . $r['match_count'] . " matches</li>"; } $msg .= "</ul>"; } break; case '/blacklist_domain': $domain = @$_REQUEST['domain']; if (!$is_admin) { $msg = "Sorry, only administrators can blacklist domains."; } elseif (!trim($domain)) { $msg = "Invalid domain"; } else { $dom = new SpamDomain($domain); $dom->set_blacklisted(DOMAIN_BLACKLISTED_MANUALLY); foreach ($dom->find_associated_domains() as $assoc_domain) { SpamDomain::recalculate_link_counts_for_domain_id($assoc_domain['domain_id']); } } // FALL THROUGH TO /common_domains // FALL THROUGH TO /common_domains case '/common_domains': if (!$is_admin) { $msg = "Sorry, only administrators can do this."; } else { list($total_domains, $total_blacklisted_domains) = SpamDomain::count_domains(); $msg .= "<p>Most common domains (out of total {$total_domains}, {$total_blacklisted_domains} blacklisted) in comments:</p><ul>"; foreach (SpamDomain::get_most_common_domains() as $dom) { $msg .= "<li>" . $dom['active_count'] . " times: " . $dom['domain'] . ' ' . ($dom['blacklisted'] ? 'BLACKLISTED' : '') . ' (<a href="' . $page_url . '/blacklist_domain?domain=' . $dom['domain'] . '">blacklist domain</a> | <a href="' . $page_url . '/analyze_domain?domain=' . $dom['domain'] . '">analyze domain</a>)</li>'; } $msg .= "</ul>"; } break; case '/akismet_verify_key': global $akismet_key; if (!$is_admin) { $msg = "Sorry, only administrators can access Akismet at the moment."; } elseif (!$akismet_key) { $msg .= '<p>No Akismet key has been configured - Akismet is not active.</p>'; } else { // global var $_base_url has been removed - please, use PA::$url static variable $msg .= "<p>verifying akismet key: {$akismet_key}</p>"; $ak = new Akismet($akismet_key); $msg .= "<p>result: " . var_export($ak->verify_key(PA::$url . PA_ROUTE_USER_PUBLIC . '/' . $user->user_id), TRUE) . "</p>"; } break; case '/akismet_check_spam': if (!$is_admin) { $msg = "Sorry, only administrators can access Akismet at the moment."; } else { global $akismet_key; $msg .= "<p>checking comment for spam</p>"; $cmt = new Comment(); try { $cmt->load((int) $_REQUEST['comment']); } catch (PAException $e) { if ($e->getCode() != COMMENT_NOT_EXIST) { throw $e; } $msg .= "<p>Comment already deleted.</p>"; break; } $cmt->akismet_check(); $msg .= "<p>result: " . var_export($cmt->akismet_spam, TRUE) . "</p>"; } break; default: if (preg_match("~^/delete/(\\d+)\$~", $path_info, $m)) { list(, $cid) = $m; if (!$is_admin) { $msg = "Sorry, only administrators can delete comments at the moment :("; } else { try { $c = new Comment(); $c->load((int) $cid); $c->delete(); $msg = "Comment deleted."; } catch (PAException $e) { if ($e->code == COMMENT_NOT_EXIST) { $msg = "Comment already deleted."; } else { throw $e; } } } } } $per_page = 20; // how many comments to show on a page // paging if ($limit_set !== NULL) { $total_comments = count($limit_set); } else { $total_comments = Comment::count_all_comments($is_admin ? 0 : $user->user_id); } $pager = new pager($total_comments, $per_page, $paging_url); $paging = $pager->getButList(8) . " (total {$total_comments} comments)"; // main comment list if ($limit_set !== NULL) { $show_start = max(0, min(($pager->page - 1) * $per_page, $total_comments)); $show_count = min($per_page, $total_comments - $show_start); $limit_set_ids = array_map(create_function('$item', 'return $item["comment_id"];'), array_slice($limit_set, $show_start, $show_count)); $cmts = Comment::get_selected($limit_set_ids); } else { $cmts = Comment::get_all_comments($is_admin ? 0 : $user->user_id, $per_page, $pager->page); } $comments = ""; foreach ($cmts as $cmt) { // $comments .= "<li>".htmlspecialchars(var_export($cmt, TRUE))."</li>"; $akismet_result = $cmt['akismet_spam'] ? "spam" : "?"; $comments .= "<tr><td>" . $cmt['comment_id'] . "</td><td>" . $cmt['content_id'] . "</td><td>" . esc_wbr($cmt['name']) . "</td><td>" . esc_wbr($cmt['email']) . "</td><td>" . esc_wbr($cmt['homepage']) . "</td><td>" . esc_wbr($cmt['subject']) . "</td><td>" . esc_wbr($cmt['comment']) . " {$akismet_result} <a href=\"{$page_url}/analyze_comment?comment=" . $cmt['comment_id'] . "\">analyze</a></td><td>" . esc_wbr($cmt['ip_addr']) . "</td><td>" . '<form method="POST" action="' . PA::$url . '/comment_management.php/delete/' . $cmt['comment_id'] . '?page=' . $pager->page . '"><input type="submit" value="X"></form> <a href="' . $page_url . '/akismet_check_spam?comment=' . $cmt['comment_id'] . '">ak</a></td></tr>'; } if ($is_admin) { if ($current_search_terms) { $current_search = '<form method="POST" action="' . $page_url . '/add_spam_term"><p>Currently displaying results for: <b>' . htmlspecialchars($current_search_terms) . '</b>. <a href="' . $page_url . '">Show all comments</a>. <input type="hidden" name="term" value="' . htmlspecialchars($current_search_terms) . '"><input type="submit" value="Blacklist this term"></p></form>'; } else { $current_search = ""; } $your_permissions = <<<EOS \t<form method="POST" action="{$page_url}/logout"><p>You are an administrator, so all comments in the site will be displayed. <input type="submit" value="Log out"></p></form> \t<p><a href="{$page_url}/akismet_verify_key">Verify Akismet key</a> | <a href="{$page_url}/common_domains">Show most common domains</a> | <a href="{$page_url}/stats">Spam statistics</a></p> \t<form method="GET" action="{$page_url}/search"><p>Search comment content: <input type="text" id="search_q" name="q" size="20"><input type="submit" value="Search"/></p></form> \t<script language="javascript"><!-- \t document.getElementById("search_q").focus(); // --></script> {$current_search} EOS; } else { $your_permissions = <<<EOS <p>Showing comments on your blog and groups for which you are moderator.</p> <form method="POST" action="{$page_url}/login"><p>Or enter the admin password here to adminster the whole site: <input type="password" name="admin_password" size="20"/><input type="submit" value="Log in"/></p></form> EOS; } $page_title = "Manage comments"; global $akismet_key; if ($akismet_key) { $page_title .= " (Akismet active)"; } else { $page_title .= " (Akismet not configured)"; } $page_html = <<<EOS <div class="pane comment_manage_pane"> <h1>{$page_title}</h1> <div id="msg" class="fade">{$msg}</div> {$your_permissions} <p>{$paging}</p> <table class="bulk_comment_summary"><tr> <td>ID</td> <td>Post</td> <td>Name</td> <td>Email</td> <td>Website</td> <td>Subject</td> <td>Comment</td> <td>IP</td> <td>X</td> </tr> {$comments} </table> </div><!-- comment_manage_pane --> EOS; return $page_html; }
public static function count_domains() { list($total) = Dal::query_one("SELECT COUNT(*) FROM spam_domains"); list($total_blacklisted) = Dal::query_one("SELECT COUNT(*) FROM spam_domains WHERE blacklisted=1"); return array($total, $total_blacklisted); }
public static function relation_exists($user_id, $relation_id) { $r = Dal::query_one("SELECT * FROM {relations} WHERE user_id=? AND relation_id=?", array($user_id, $relation_id)); if ($r) { return true; } else { return false; } }
function is_modified($path) { $r = Dal::query_one("SELECT kind,path,hash FROM svn_objects WHERE is_active=1 AND path=?", array($path)); if (!$r) { throw new Subversion_Failure("Attempt to check modification for a nonexistent file {$path}"); } list($kind, $leaf, $hash) = $r; $path = "{$this->root}/{$leaf}"; return $this->_check_modified($kind, $path, $hash); }
public function count_persona_service_paths($persona_service_id) { list($count) = Dal::query_one("SELECT COUNT(*) FROM {persona_service_paths} WHERE persona_service_id = ?", array($persona_service_id)); return intval($count); }
public static function insert_id() { list($id) = Dal::query_one("SELECT LAST_INSERT_ID()"); return $id; }
function get_remaining() { list($remaining) = Dal::query_one("SELECT COUNT(*) FROM comments WHERE is_active=1 AND akismet_spam IS NULL"); return (int) $remaining; }
function is_applied($key, $network=NULL) { if (!$network) $network = ''; $r = Dal::query_one("SELECT * FROM mc_db_status WHERE stmt_key=? AND network=?", Array($key, $network)); return $r ? TRUE : FALSE; }
public function count_persona_services_enabled() { list($count) = Dal::query_one("SELECT COUNT(*) FROM {persona_services}\n WHERE enabled=1", array()); return intval($count); }
function testStorage() { // test Storage - public API // store test.txt echo "saving test.txt with a crazy name\n"; $file_id = Storage::save('test.txt', 'O*Bc3wukygfsT@#($0876)$!@#*+_][.txt'); echo "resulting file_id = {$file_id}\n"; $file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($file_id)); $this->assertEquals($file->link_count, 0); $this->assertEquals($file->last_linked, NULL); $file_path = Storage::getPath($file_id); $file_url = Storage::getURL($file_id); echo "getPath({$file_id}) -> {$file_path}\n"; echo "getURL({$file_id}) -> {$file_url}\n"; $this->assertTrue(strpos($file_path, PA::$path . "/web/files/") === 0); $this->assertTrue(strpos($file_url, PA::$url) === 0); // link it in somewhere $link_id = Storage::link($file_id, array('role' => 'avatar', 'user' => 1)); echo "linked it in as avatar for user 1; link_id = {$link_id}\n"; $link = Dal::query_one_object("SELECT * FROM file_links WHERE link_id=?", array($link_id)); $this->assertEquals($link->file_id, $file_id); $file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($file_id)); $this->assertEquals($file->link_count, 1); $this->assertNotEquals($file->last_linked, NULL); // another file $child_file_id = Storage::save('test2.txt', 'this is the child file.jpg', 'throwaway', 'image/jpeg'); echo "child file: {$child_file_id}\n"; $child_file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($child_file_id)); $child_file_path = Storage::getPath($child_file_id); $child_file_url = Storage::getURL($child_file_id); echo "getPath({$child_file_id}) -> {$child_file_path}\n"; echo "getURL({$child_file_id}) -> {$child_file_url}\n"; $this->assertTrue(strpos($child_file_path, PA::$path . "/web/files/") === 0); $this->assertTrue(strpos($child_file_url, PA::$url) === 0); // link child file in as a thumbnail of first file $child_link_id = Storage::link($child_file_id, array('role' => 'thumb', 'file' => $file_id, 'dim' => '123x123')); echo "child link id: {$child_link_id}\n"; $child_link = Dal::query_one_object("SELECT * FROM file_links WHERE link_id=?", array($child_link_id)); $this->assertEquals($child_link->file_id, $child_file_id); $this->assertEquals($child_link->parent_file_id, $file_id); $child_file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($child_file_id)); $this->assertEquals($child_file->link_count, 1); $this->assertNotEquals($child_file->last_linked, NULL); // this should fail (missing role) try { Storage::link($file_id, array("user" => 1)); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), BAD_PARAMETER); } // this should fail (missing network) try { Storage::link($file_id, array("role" => "header", "group" => 42)); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), BAD_PARAMETER); } // this should fail (network not valid) try { Storage::link($file_id, array("role" => "thumb", "network" => 1, "file" => $file_id, "dim" => "123x123")); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), BAD_PARAMETER); } // this should fail (parent_file_id == file_id) try { $link_id = Storage::link($file_id, array("role" => "thumb", "file" => $file_id, "dim" => "123x123")); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), BAD_PARAMETER); } // Now unlink the two files we just created ... // unlink the first - but don't delete it Storage::unlink($file_id, $link_id, FALSE); // make sure it's gone $this->assertEquals(Dal::query_one("SELECT * FROM file_links WHERE link_id=?", array($link_id)), NULL); // the file should still be there, with zero links, though $file = Dal::query_one("SELECT * FROM files WHERE file_id=?", array($file_id)); $this->assertNotEquals($file, NULL); $this->assertEquals($file->link_count, 0); // try a bad unlink operation try { Storage::unlink($file_id, $child_link_id); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), FILE_NOT_FOUND); } // unlink and delete the second Storage::unlink($child_file_id, $child_link_id); // make sure it's gone $this->assertEquals(Dal::query_one("SELECT * FROM file_links WHERE link_id=?", array($child_link_id)), NULL); // and make sure the file is gone too $this->assertEquals(Dal::query_one("SELECT * FROM files WHERE file_id=?", array($child_file)), NULL); // reap unlinked files (immediately - no grace period) Storage::cleanupFiles(-1, -1); // make sure the first file is now gone $this->assertEquals(Dal::query_one("SELECT * FROM files WHERE file_id=?", array($file_id)), NULL); }
public function count_user_personas($user_id) { list($count) = Dal::query_one("SELECT COUNT(*) FROM {personas} WHERE user_id = ?", array($user_id)); return intval($count); }
public function migrateLegacyFiles($dry_run = TRUE) { $this->dry_run = $dry_run; require_once PA::$path . "/db/Dal/DbUpdate.php"; echo "Migrating legacy files to new storage system\n"; $this->all_files = array(); if (!($h = opendir(PA::$path . '/web/files'))) { throw new PAException(GENERAL_SOME_ERROR, "Unable to open web/files directory"); } while (false !== ($f = readdir($h))) { if ($f[0] == '.') { continue; } $this->all_files[$f] = TRUE; } closedir($h); $this->unmatched = count($this->all_files); $this->unmatchable = 0; $this->matched = 0; $this->dupes = 0; echo "{$this->unmatched} files found\n"; echo "Matching with user images ...\n"; $sql = Dal::validate_sql("SELECT user_id,picture FROM {users}", $network); $sth = Dal::query($sql); while ($r = Dal::row($sth)) { list($uid, $pic) = $r; // user avatar $this->_matchLegacyFile($pic, array("role" => "avatar", "user" => $uid)); //TODO: user header image } $this->_dumpMatchResults(); $networks = DbUpdate::get_valid_networks(); echo "Processing " . count($networks) . " networks\n"; foreach ($networks as $network) { echo " Network: {$network}\n"; // network level stuff list($network_id, $act, $logo, $extra) = Dal::query_one("SELECT network_id, is_active, inner_logo_image, extra FROM networks WHERE address=?", array($network)); assert($act); // sanity check $extra = unserialize($extra); // network avatar $this->_matchLegacyFile($logo, array("role" => "avatar", "network" => $network_id)); // network header image $header_image = @$extra["basic"]["header_image"]["name"]; if (!empty($header_image)) { $this->_matchLegacyFile($header_image, array("role" => "header", "network" => $network_id)); } // emblems foreach (unserialize(Dal::query_first(Dal::validate_sql("SELECT data FROM {moduledata} WHERE modulename='LogoModule'"))) as $emblem) { $this->_matchLegacyFile($emblem["file_name"], array("role" => "emblem", "network" => $network_id)); } // group pictures $sth = Dal::query(Dal::validate_sql("SELECT collection_id, picture FROM {contentcollections} WHERE type=1 AND is_active=1", $network)); while ($r = Dal::row($sth)) { list($cid, $pic) = $r; $this->_matchLegacyFile($pic, array("role" => "avatar", "network" => $network_id, "group" => $cid)); $header = Dal::query_first(Dal::validate_sql("SELECT header_image FROM groups WHERE group_id=?", $network), array($cid)); $this->_matchLegacyFile($header, array("role" => "header", "network" => $network_id, "group" => $cid)); } /* disabled until we update peopleaggregator.net $sth = Dal::query(Dal::validate_sql("SELECT group_id, header_image FROM {groups}", $network)); while ($r = Dal::row($sth)) { list ($gid, $pic) = $r; $this->_matchLegacyFile($network, "group", $gid, $pic); } */ //TODO: advertisements // images, audio, video foreach (array("image", "audio", "video") as $table) { $sth = Dal::query(Dal::validate_sql('SELECT mc.content_id, mc.' . $table . '_file, c.author_id, c.collection_id, c.is_active FROM {' . $table . 's} mc LEFT JOIN {contents} c ON mc.content_id=c.content_id HAVING c.is_active=1', $network)); while ($r = Dal::row($sth)) { list($cid, $fn, $uid, $ccid, $act) = $r; $this->_matchLegacyFile($fn, array("role" => "media", "network" => $network_id, "content" => $cid)); } } } $this->_dumpMatchResults(); foreach ($this->all_files as $fn => $v) { if ($v === TRUE) { echo " * unmatchable: {$fn}\n"; } } echo "Overall results from web/files: "; $this->_dumpMatchResults(); }