diff options
Diffstat (limited to 'classes')
-rw-r--r-- | classes/Avatar.php | 4 | ||||
-rw-r--r-- | classes/Config.php | 160 | ||||
-rw-r--r-- | classes/Deleted_notice.php | 46 | ||||
-rw-r--r-- | classes/File.php | 55 | ||||
-rw-r--r-- | classes/File_oembed.php | 21 | ||||
-rw-r--r-- | classes/File_redirection.php | 71 | ||||
-rw-r--r-- | classes/Location_namespace.php | 46 | ||||
-rw-r--r-- | classes/Login_token.php | 42 | ||||
-rw-r--r-- | classes/Memcached_DataObject.php | 29 | ||||
-rw-r--r-- | classes/Message.php | 57 | ||||
-rw-r--r-- | classes/Notice.php | 281 | ||||
-rw-r--r-- | classes/Plugin_DataObject.php | 195 | ||||
-rw-r--r-- | classes/Profile.php | 204 | ||||
-rw-r--r-- | classes/Profile_role.php | 55 | ||||
-rw-r--r-- | classes/Status_network.php | 28 | ||||
-rw-r--r-- | classes/User.php | 188 | ||||
-rw-r--r-- | classes/User_group.php | 82 | ||||
-rw-r--r-- | classes/User_openid.php | 25 | ||||
-rw-r--r-- | classes/statusnet.ini | 77 |
19 files changed, 1338 insertions, 328 deletions
diff --git a/classes/Avatar.php b/classes/Avatar.php index 5e8b315fe..cc7a6b647 100644 --- a/classes/Avatar.php +++ b/classes/Avatar.php @@ -81,7 +81,7 @@ class Avatar extends Memcached_DataObject if (empty($server)) { $server = common_config('site', 'server'); } - + common_debug('path = ' . $path); // XXX: protocol return 'http://'.$server.$path.$filename; @@ -102,6 +102,6 @@ class Avatar extends Memcached_DataObject static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', AVATAR_STREAM_SIZE => 'stream', AVATAR_MINI_SIZE => 'mini'); - return theme_path('default-avatar-'.$sizenames[$size].'.png'); + return Theme::path('default-avatar-'.$sizenames[$size].'.png'); } } diff --git a/classes/Config.php b/classes/Config.php new file mode 100644 index 000000000..390d75381 --- /dev/null +++ b/classes/Config.php @@ -0,0 +1,160 @@ +<?php +/* + * Laconica - a distributed open-source microblogging tool + * Copyright (C) 2008, 2009, Control Yourself, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +/** + * Table Definition for config + */ + +require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; + +class Config extends Memcached_DataObject +{ + ###START_AUTOCODE + /* the code below is auto generated do not remove the above tag */ + + public $__table = 'config'; // table name + public $section; // varchar(32) primary_key not_null + public $setting; // varchar(32) primary_key not_null + public $value; // varchar(255) + + /* Static get */ + function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Config',$k,$v); } + + /* the code above is auto generated do not remove the tag below */ + ###END_AUTOCODE + + const settingsKey = 'config:settings'; + + static function loadSettings() + { + $settings = self::_getSettings(); + if (!empty($settings)) { + self::_applySettings($settings); + } + } + + static function _getSettings() + { + $c = self::memcache(); + + if (!empty($c)) { + $settings = $c->get(common_cache_key(self::settingsKey)); + if (!empty($settings)) { + return $settings; + } + } + + $settings = array(); + + $config = new Config(); + + $config->find(); + + while ($config->fetch()) { + $settings[] = array($config->section, $config->setting, $config->value); + } + + $config->free(); + + if (!empty($c)) { + $c->set(common_cache_key(self::settingsKey), $settings); + } + + return $settings; + } + + static function _applySettings($settings) + { + global $config; + + foreach ($settings as $s) { + list($section, $setting, $value) = $s; + $config[$section][$setting] = $value; + } + } + + function insert() + { + $result = parent::insert(); + if ($result) { + Config::_blowSettingsCache(); + } + return $result; + } + + function delete() + { + $result = parent::delete(); + if ($result) { + Config::_blowSettingsCache(); + } + return $result; + } + + function update($orig=null) + { + $result = parent::update($orig); + if ($result) { + Config::_blowSettingsCache(); + } + return $result; + } + + function &pkeyGet($kv) + { + return Memcached_DataObject::pkeyGet('Config', $kv); + } + + static function save($section, $setting, $value) + { + $result = null; + + $config = Config::pkeyGet(array('section' => $section, + 'setting' => $setting)); + + if (!empty($config)) { + $orig = clone($config); + $config->value = $value; + $result = $config->update($orig); + } else { + $config = new Config(); + + $config->section = $section; + $config->setting = $setting; + $config->value = $value; + + $result = $config->insert(); + } + + return $result; + } + + function _blowSettingsCache() + { + $c = self::memcache(); + + if (!empty($c)) { + $c->delete(common_cache_key(self::settingsKey)); + } + } +} diff --git a/classes/Deleted_notice.php b/classes/Deleted_notice.php new file mode 100644 index 000000000..64dc85da6 --- /dev/null +++ b/classes/Deleted_notice.php @@ -0,0 +1,46 @@ +<?php +/* + * Laconica - a distributed open-source microblogging tool + * Copyright (C) 2008, 2009, Control Yourself, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +/** + * Table Definition for notice + */ +require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; + +class Deleted_notice extends Memcached_DataObject +{ + ###START_AUTOCODE + /* the code below is auto generated do not remove the above tag */ + + public $__table = 'deleted_notice'; // table name + public $id; // int(4) primary_key not_null + public $profile_id; // int(4) not_null + public $uri; // varchar(255) unique_key + public $created; // datetime() not_null + public $deleted; // datetime() not_null + + /* Static get */ + function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Deleted_notice',$k,$v); } + + /* the code above is auto generated do not remove the tag below */ + ###END_AUTOCODE +} diff --git a/classes/File.php b/classes/File.php index 308d0a771..e04a9d525 100644 --- a/classes/File.php +++ b/classes/File.php @@ -94,7 +94,13 @@ class File extends Memcached_DataObject $file_redir = File_redirection::staticGet('url', $given_url); if (empty($file_redir)) { $redir_data = File_redirection::where($given_url); - $redir_url = $redir_data['url']; + if (is_array($redir_data)) { + $redir_url = $redir_data['url']; + } elseif (is_string($redir_data)) { + $redir_url = $redir_data; + } else { + throw new ServerException("Can't process url '$given_url'"); + } // TODO: max field length if ($redir_url === $given_url || strlen($redir_url) > 255) { $x = File::saveNew($redir_data, $given_url); @@ -197,17 +203,44 @@ class File extends Memcached_DataObject return 'http://'.$server.$path.$filename; } - function isEnclosure(){ - if(isset($this->filename)){ - return true; - } - $notEnclosureMimeTypes = array('text/html','application/xhtml+xml',null); - $mimetype = strtolower($this->mimetype); - $semicolon = strpos($mimetype,';'); - if($semicolon){ - $mimetype = substr($mimetype,0,$semicolon); + function getEnclosure(){ + $enclosure = (object) array(); + $enclosure->title=$this->title; + $enclosure->url=$this->url; + $enclosure->title=$this->title; + $enclosure->date=$this->date; + $enclosure->modified=$this->modified; + $enclosure->size=$this->size; + $enclosure->mimetype=$this->mimetype; + + if(! isset($this->filename)){ + $notEnclosureMimeTypes = array('text/html','application/xhtml+xml'); + $mimetype = strtolower($this->mimetype); + $semicolon = strpos($mimetype,';'); + if($semicolon){ + $mimetype = substr($mimetype,0,$semicolon); + } + if(in_array($mimetype,$notEnclosureMimeTypes)){ + $oembed = File_oembed::staticGet('file_id',$this->id); + if($oembed){ + $mimetype = strtolower($oembed->mimetype); + $semicolon = strpos($mimetype,';'); + if($semicolon){ + $mimetype = substr($mimetype,0,$semicolon); + } + if(in_array($mimetype,$notEnclosureMimeTypes)){ + return false; + }else{ + if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype; + if($oembed->url) $enclosure->url=$oembed->url; + if($oembed->title) $enclosure->title=$oembed->title; + if($oembed->modified) $enclosure->modified=$oembed->modified; + unset($oembed->size); + } + } + } } - return(! in_array($mimetype,$notEnclosureMimeTypes)); + return $enclosure; } } diff --git a/classes/File_oembed.php b/classes/File_oembed.php index 6be651815..e41ccfd09 100644 --- a/classes/File_oembed.php +++ b/classes/File_oembed.php @@ -20,6 +20,7 @@ if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; +require_once INSTALLDIR.'/classes/File_redirection.php'; /** * Table Definition for file_oembed @@ -34,6 +35,7 @@ class File_oembed extends Memcached_DataObject public $file_id; // int(4) primary_key not_null public $version; // varchar(20) public $type; // varchar(20) + public $mimetype; // varchar(50) public $provider; // varchar(50) public $provider_url; // varchar(255) public $width; // int(4) @@ -93,7 +95,24 @@ class File_oembed extends Memcached_DataObject if (!empty($data->title)) $file_oembed->title = $data->title; if (!empty($data->author_name)) $file_oembed->author_name = $data->author_name; if (!empty($data->author_url)) $file_oembed->author_url = $data->author_url; - if (!empty($data->url)) $file_oembed->url = $data->url; + if (!empty($data->url)){ + $file_oembed->url = $data->url; + $given_url = File_redirection::_canonUrl($file_oembed->url); + if (! empty($given_url)){ + $file = File::staticGet('url', $given_url); + if (empty($file)) { + $file_redir = File_redirection::staticGet('url', $given_url); + if (empty($file_redir)) { + $redir_data = File_redirection::where($given_url); + $file_oembed->mimetype = $redir_data['type']; + } else { + $file_id = $file_redir->file_id; + } + } else { + $file_oembed->mimetype=$file->mimetype; + } + } + } $file_oembed->insert(); if (!empty($data->thumbnail_url)) { File_thumbnail::saveNew($data, $file_id); diff --git a/classes/File_redirection.php b/classes/File_redirection.php index 76b18f672..08a6e8d8b 100644 --- a/classes/File_redirection.php +++ b/classes/File_redirection.php @@ -47,18 +47,15 @@ class File_redirection extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - function _commonCurl($url, $redirs) { - $curlh = curl_init(); - curl_setopt($curlh, CURLOPT_URL, $url); - curl_setopt($curlh, CURLOPT_AUTOREFERER, true); // # setup referer header when folowing redirects - curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 10); // # seconds to wait - curl_setopt($curlh, CURLOPT_MAXREDIRS, $redirs); // # max number of http redirections to follow - curl_setopt($curlh, CURLOPT_USERAGENT, USER_AGENT); - curl_setopt($curlh, CURLOPT_FOLLOWLOCATION, true); // Follow redirects - curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curlh, CURLOPT_FILETIME, true); - curl_setopt($curlh, CURLOPT_HEADER, true); // Include header in output - return $curlh; + static function _commonHttp($url, $redirs) { + $request = new HTTPClient($url); + $request->setConfig(array( + 'connect_timeout' => 10, // # seconds to wait + 'max_redirs' => $redirs, // # max number of http redirections to follow + 'follow_redirects' => true, // Follow redirects + 'store_body' => false, // We won't need body content here. + )); + return $request; } function _redirectWhere_imp($short_url, $redirs = 10, $protected = false) { @@ -79,32 +76,42 @@ class File_redirection extends Memcached_DataObject } } - $curlh = File_redirection::_commonCurl($short_url, $redirs); - // Don't include body in output - curl_setopt($curlh, CURLOPT_NOBODY, true); - curl_exec($curlh); - $info = curl_getinfo($curlh); - curl_close($curlh); - - if (405 == $info['http_code']) { - $curlh = File_redirection::_commonCurl($short_url, $redirs); - curl_exec($curlh); - $info = curl_getinfo($curlh); - curl_close($curlh); + if(strpos($short_url,'://') === false){ + return $short_url; + } + try { + $request = self::_commonHttp($short_url, $redirs); + // Don't include body in output + $request->setMethod(HTTP_Request2::METHOD_HEAD); + $response = $request->send(); + + if (405 == $response->getStatus()) { + // Server doesn't support HEAD method? Can this really happen? + // We'll try again as a GET and ignore the response data. + $request = self::_commonHttp($short_url, $redirs); + $response = $request->send(); + } + } catch (Exception $e) { + // Invalid URL or failure to reach server + return $short_url; } - if (!empty($info['redirect_count']) && File::isProtected($info['url'])) { - return File_redirection::_redirectWhere_imp($short_url, $info['redirect_count'] - 1, true); + if ($response->getRedirectCount() && File::isProtected($response->getUrl())) { + // Bump back up the redirect chain until we find a non-protected URL + return self::_redirectWhere_imp($short_url, $response->getRedirectCount() - 1, true); } - $ret = array('code' => $info['http_code'] - , 'redirects' => $info['redirect_count'] - , 'url' => $info['url']); + $ret = array('code' => $response->getStatus() + , 'redirects' => $response->getRedirectCount() + , 'url' => $response->getUrl()); - if (!empty($info['content_type'])) $ret['type'] = $info['content_type']; + $type = $response->getHeader('Content-Type'); + if ($type) $ret['type'] = $type; if ($protected) $ret['protected'] = true; - if (!empty($info['download_content_length'])) $ret['size'] = $info['download_content_length']; - if (isset($info['filetime']) && ($info['filetime'] > 0)) $ret['time'] = $info['filetime']; + $size = $response->getHeader('Content-Length'); // @fixme bytes? + if ($size) $ret['size'] = $size; + $time = $response->getHeader('Last-Modified'); + if ($time) $ret['time'] = strtotime($time); return $ret; } diff --git a/classes/Location_namespace.php b/classes/Location_namespace.php new file mode 100644 index 000000000..5ab95d9ef --- /dev/null +++ b/classes/Location_namespace.php @@ -0,0 +1,46 @@ +<?php +/* + * StatusNet - the distributed open-source microblogging tool + * Copyright (C) 2009, StatusNet, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } + +/** + * Table Definition for location_namespace + */ + +require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; + +class Location_namespace extends Memcached_DataObject +{ + ###START_AUTOCODE + /* the code below is auto generated do not remove the above tag */ + + public $__table = 'location_namespace'; // table name + public $id; // int(4) primary_key not_null + public $description; // varchar(255) + public $created; // datetime() not_null + public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP + + /* Static get */ + function staticGet($k,$v=NULL) { + return Memcached_DataObject::staticGet('Location_namespace',$k,$v); + } + + /* the code above is auto generated do not remove the tag below */ + ###END_AUTOCODE +} diff --git a/classes/Login_token.php b/classes/Login_token.php new file mode 100644 index 000000000..bd6381f90 --- /dev/null +++ b/classes/Login_token.php @@ -0,0 +1,42 @@ +<?php +/** + * Table Definition for group_alias + * + * StatusNet - the distributed open-source microblogging tool + * Copyright (C) 2009, StatusNet, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } + +require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; + +class Login_token extends Memcached_DataObject +{ + ###START_AUTOCODE + /* the code below is auto generated do not remove the above tag */ + + public $__table = 'login_token'; // table name + public $user_id; // int(4) primary_key not_null + public $token; // char(32) not_null + public $created; // datetime() not_null + public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP + + /* Static get */ + function staticGet($k,$v=NULL) { return DB_DataObject::staticGet('Login_token',$k,$v); } + + /* the code above is auto generated do not remove the tag below */ + ###END_AUTOCODE +} diff --git a/classes/Memcached_DataObject.php b/classes/Memcached_DataObject.php index 9c2ac3e01..753fe954e 100644 --- a/classes/Memcached_DataObject.php +++ b/classes/Memcached_DataObject.php @@ -184,27 +184,20 @@ class Memcached_DataObject extends DB_DataObject require_once INSTALLDIR.'/lib/search_engines.php'; static $search_engine; if (!isset($search_engine)) { - $connected = false; - if (common_config('sphinx', 'enabled')) { - $search_engine = new SphinxSearch($this, $table); - $connected = $search_engine->is_connected(); - } - - // unable to connect to sphinx' search daemon - if (!$connected) { - if ('mysql' === common_config('db', 'type')) { - $type = common_config('search', 'type'); - if ($type == 'like') { - $search_engine = new MySQLLikeSearch($this, $table); - } else if ($type == 'fulltext') { - $search_engine = new MySQLSearch($this, $table); - } else { - throw new ServerException('Unknown search type: ' . $type); - } + if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) { + if ('mysql' === common_config('db', 'type')) { + $type = common_config('search', 'type'); + if ($type == 'like') { + $search_engine = new MySQLLikeSearch($this, $table); + } else if ($type == 'fulltext') { + $search_engine = new MySQLSearch($this, $table); } else { - $search_engine = new PGSearch($this, $table); + throw new ServerException('Unknown search type: ' . $type); } + } else { + $search_engine = new PGSearch($this, $table); } + } } return $search_engine; } diff --git a/classes/Message.php b/classes/Message.php index 4806057b4..718a9d922 100644 --- a/classes/Message.php +++ b/classes/Message.php @@ -4,7 +4,7 @@ */ require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; -class Message extends Memcached_DataObject +class Message extends Memcached_DataObject { ###START_AUTOCODE /* the code below is auto generated do not remove the above tag */ @@ -14,58 +14,79 @@ class Message extends Memcached_DataObject public $uri; // varchar(255) unique_key public $from_profile; // int(4) not_null public $to_profile; // int(4) not_null - public $content; // varchar(140) - public $rendered; // text() - public $url; // varchar(255) + public $content; // text() + public $rendered; // text() + public $url; // varchar(255) public $created; // datetime() not_null public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP - public $source; // varchar(32) + public $source; // varchar(32) /* Static get */ - function staticGet($k,$v=null) - { return Memcached_DataObject::staticGet('Message',$k,$v); } + function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Message',$k,$v); } /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - + function getFrom() { return Profile::staticGet('id', $this->from_profile); } - + function getTo() { return Profile::staticGet('id', $this->to_profile); } - + static function saveNew($from, $to, $content, $source) { - + + $sender = Profile::staticGet('id', $from); + + if (!$sender->hasRight(Right::NEWMESSAGE)) { + throw new ClientException(_('You are banned from sending direct messages.')); + } + $msg = new Message(); - + $msg->from_profile = $from; $msg->to_profile = $to; $msg->content = common_shorten_links($content); $msg->rendered = common_render_text($content); $msg->created = common_sql_now(); $msg->source = $source; - + $result = $msg->insert(); - + if (!$result) { common_log_db_error($msg, 'INSERT', __FILE__); return _('Could not insert message.'); } - + $orig = clone($msg); $msg->uri = common_local_url('showmessage', array('message' => $msg->id)); - + $result = $msg->update($orig); - + if (!$result) { common_log_db_error($msg, 'UPDATE', __FILE__); return _('Could not update message with new URI.'); } - + return $msg; } + + static function maxContent() + { + $desclimit = common_config('message', 'contentlimit'); + // null => use global limit (distinct from 0!) + if (is_null($desclimit)) { + $desclimit = common_config('site', 'textlimit'); + } + return $desclimit; + } + + static function contentTooLong($content) + { + $contentlimit = self::maxContent(); + return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit)); + } } diff --git a/classes/Notice.php b/classes/Notice.php index 7d0502626..ebb5022b9 100644 --- a/classes/Notice.php +++ b/classes/Notice.php @@ -1,5 +1,5 @@ <?php -/* +/** * StatusNet - the distributed open-source microblogging tool * Copyright (C) 2008, 2009, StatusNet, Inc. * @@ -15,9 +15,26 @@ * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @category Notices + * @package StatusNet + * @author Brenda Wallace <shiny@cpan.org> + * @author Christopher Vollick <psycotica0@gmail.com> + * @author CiaranG <ciaran@ciarang.com> + * @author Craig Andrews <candrews@integralblue.com> + * @author Evan Prodromou <evan@controlezvous.ca> + * @author Gina Haeussge <osd@foosel.net> + * @author Jeffery To <jeffery.to@gmail.com> + * @author Mike Cochrane <mikec@mikenz.geek.nz> + * @author Robin Millette <millette@controlyourself.ca> + * @author Sarven Capadisli <csarven@controlyourself.ca> + * @author Tom Adams <tom@holizz.com> + * @license GNU Affero General Public License http://www.gnu.org/licenses/ */ -if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} /** * Table Definition for notice @@ -40,7 +57,7 @@ class Notice extends Memcached_DataObject public $id; // int(4) primary_key not_null public $profile_id; // int(4) not_null public $uri; // varchar(255) unique_key - public $content; // varchar(140) + public $content; // text() public $rendered; // text() public $url; // varchar(255) public $created; // datetime() not_null @@ -49,6 +66,10 @@ class Notice extends Memcached_DataObject public $is_local; // tinyint(1) public $source; // varchar(32) public $conversation; // int(4) + public $lat; // decimal(10,7) + public $lon; // decimal(10,7) + public $location_id; // int(4) + public $location_ns; // int(4) /* Static get */ function staticGet($k,$v=NULL) { @@ -75,17 +96,30 @@ class Notice extends Memcached_DataObject $this->blowFavesCache(true); $this->blowSubsCache(true); + // For auditing purposes, save a record that the notice + // was deleted. + + $deleted = new Deleted_notice(); + + $deleted->id = $this->id; + $deleted->profile_id = $this->profile_id; + $deleted->uri = $this->uri; + $deleted->created = $this->created; + $deleted->deleted = common_sql_now(); + $this->query('BEGIN'); + + $deleted->insert(); + //Null any notices that are replies to this notice $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id)); $related = array('Reply', 'Fave', 'Notice_tag', 'Group_inbox', - 'Queue_item'); - if (common_config('inboxes', 'enabled')) { - $related[] = 'Notice_inbox'; - } + 'Queue_item', + 'Notice_inbox'); + foreach ($related as $cls) { $inst = new $cls(); $inst->notice_id = $this->id; @@ -134,48 +168,46 @@ class Notice extends Memcached_DataObject } static function saveNew($profile_id, $content, $source=null, - $is_local=Notice::LOCAL_PUBLIC, $reply_to=null, $uri=null, $created=null) { + $is_local=Notice::LOCAL_PUBLIC, $reply_to=null, $uri=null, $created=null, + $lat=null, $lon=null, $location_id=null, $location_ns=null) { $profile = Profile::staticGet($profile_id); $final = common_shorten_links($content); - if (mb_strlen($final) > 140) { - common_log(LOG_INFO, 'Rejecting notice that is too long.'); - return _('Problem saving notice. Too long.'); + if (Notice::contentTooLong($final)) { + throw new ClientException(_('Problem saving notice. Too long.')); } - if (!$profile) { - common_log(LOG_ERR, 'Problem saving notice. Unknown user.'); - return _('Problem saving notice. Unknown user.'); + if (empty($profile)) { + throw new ClientException(_('Problem saving notice. Unknown user.')); } if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) { common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.'); - return _('Too many notices too fast; take a breather and post again in a few minutes.'); + throw new ClientException(_('Too many notices too fast; take a breather '. + 'and post again in a few minutes.')); } if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) { common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.'); - return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.'); + throw new ClientException(_('Too many duplicate messages too quickly;'. + ' take a breather and post again in a few minutes.')); } - $banned = common_config('profile', 'banned'); - - if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) { - common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id)."); - return _('You are banned from posting notices on this site.'); + if (!$profile->hasRight(Right::NEWNOTICE)) { + common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname); + throw new ClientException(_('You are banned from posting notices on this site.')); } $notice = new Notice(); $notice->profile_id = $profile_id; - $blacklist = common_config('public', 'blacklist'); $autosource = common_config('public', 'autosource'); - # Blacklisted are non-false, but not 1, either + # Sandboxed are non-false, but not 1, either - if (($blacklist && in_array($profile_id, $blacklist)) || + if (!$profile->hasRight(Right::PUBLICNOTICE) || ($source && $autosource && in_array($source, $autosource))) { $notice->is_local = Notice::LOCAL_NONPUBLIC; } else { @@ -188,18 +220,38 @@ class Notice extends Memcached_DataObject $notice->created = common_sql_now(); } - $notice->content = $final; - $notice->rendered = common_render_content($final, $notice); - $notice->source = $source; - $notice->uri = $uri; + $notice->content = $final; + $notice->rendered = common_render_content($final, $notice); + $notice->source = $source; + $notice->uri = $uri; - $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final); + $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final); if (!empty($notice->reply_to)) { $reply = Notice::staticGet('id', $notice->reply_to); $notice->conversation = $reply->conversation; } + if (!empty($lat) && !empty($lon)) { + $notice->lat = $lat; + $notice->lon = $lon; + $notice->location_id = $location_id; + $notice->location_ns = $location_ns; + } else if (!empty($location_ns) && !empty($location_id)) { + $location = Location::fromId($location_id, $location_ns); + if (!empty($location)) { + $notice->lat = $location->lat; + $notice->lon = $location->lon; + $notice->location_id = $location_id; + $notice->location_ns = $location_ns; + } + } else { + $notice->lat = $profile->lat; + $notice->lon = $profile->lon; + $notice->location_id = $profile->location_id; + $notice->location_ns = $profile->location_ns; + } + if (Event::handle('StartNoticeSave', array(&$notice))) { // XXX: some of these functions write to the DB @@ -210,7 +262,7 @@ class Notice extends Memcached_DataObject if (!$id) { common_log_db_error($notice, 'INSERT', __FILE__); - return _('Problem saving notice.'); + throw new ServerException(_('Problem saving notice.')); } // Update ID-dependent columns: URI, conversation @@ -235,13 +287,12 @@ class Notice extends Memcached_DataObject if ($changed) { if (!$notice->update($orig)) { common_log_db_error($notice, 'UPDATE', __FILE__); - return _('Problem saving notice.'); + throw new ServerException(_('Problem saving notice.')); } } // XXX: do we need to change this for remote users? - $notice->saveReplies(); $notice->saveTags(); $notice->addToInboxes(); @@ -279,11 +330,11 @@ class Notice extends Memcached_DataObject static function checkDupes($profile_id, $content) { $profile = Profile::staticGet($profile_id); - if (!$profile) { + if (empty($profile)) { return false; } $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW); - if ($notice) { + if (!empty($notice)) { $last = 0; while ($notice->fetch()) { if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) { @@ -309,7 +360,7 @@ class Notice extends Memcached_DataObject static function checkEditThrottle($profile_id) { $profile = Profile::staticGet($profile_id); - if (!$profile) { + if (empty($profile)) { return false; } # Get the Nth notice @@ -630,7 +681,7 @@ class Notice extends Memcached_DataObject $cache = common_memcache(); - if (!$cache) { + if (empty($cache)) { return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null); } @@ -691,7 +742,7 @@ class Notice extends Memcached_DataObject # If there are no hits, just return the value - if (!$notice) { + if (empty($notice)) { return $notice; } @@ -854,66 +905,76 @@ class Notice extends Memcached_DataObject function addToInboxes() { - $enabled = common_config('inboxes', 'enabled'); + // XXX: loads constants - if ($enabled === true || $enabled === 'transitional') { + $inbox = new Notice_inbox(); - // XXX: loads constants + $users = $this->getSubscribedUsers(); - $inbox = new Notice_inbox(); + // FIXME: kind of ignoring 'transitional'... + // we'll probably stop supporting inboxless mode + // in 0.9.x - $users = $this->getSubscribedUsers(); + $ni = array(); - // FIXME: kind of ignoring 'transitional'... - // we'll probably stop supporting inboxless mode - // in 0.9.x + foreach ($users as $id) { + $ni[$id] = NOTICE_INBOX_SOURCE_SUB; + } - $ni = array(); + $groups = $this->saveGroups(); + foreach ($groups as $group) { + $users = $group->getUserMembers(); foreach ($users as $id) { - $ni[$id] = NOTICE_INBOX_SOURCE_SUB; - } - - $groups = $this->saveGroups(); - - foreach ($groups as $group) { - $users = $group->getUserMembers(); - foreach ($users as $id) { - if (!array_key_exists($id, $ni)) { + if (!array_key_exists($id, $ni)) { + $user = User::staticGet('id', $id); + if (!$user->hasBlocked($notice->profile_id)) { $ni[$id] = NOTICE_INBOX_SOURCE_GROUP; } } } + } - $cnt = 0; + $recipients = $this->saveReplies(); - $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES '; - $qry = $qryhdr; + foreach ($recipients as $recipient) { - foreach ($ni as $id => $source) { - if ($cnt > 0) { - $qry .= ', '; - } - $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') "; - $cnt++; - if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) { - // FIXME: Causes lag in replicated servers - // Notice_inbox::gc($id); - } - if ($cnt >= MAX_BOXCARS) { - $inbox = new Notice_inbox(); - $inbox->query($qry); - $qry = $qryhdr; - $cnt = 0; + if (!array_key_exists($recipient, $ni)) { + $recipientUser = User::staticGet('id', $recipient); + if (!empty($recipientUser)) { + $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY; } } + } + $cnt = 0; + + $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES '; + $qry = $qryhdr; + + foreach ($ni as $id => $source) { if ($cnt > 0) { + $qry .= ', '; + } + $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') "; + $cnt++; + if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) { + // FIXME: Causes lag in replicated servers + // Notice_inbox::gc($id); + } + if ($cnt >= MAX_BOXCARS) { $inbox = new Notice_inbox(); $inbox->query($qry); + $qry = $qryhdr; + $cnt = 0; } } + if ($cnt > 0) { + $inbox = new Notice_inbox(); + $inbox->query($qry); + } + return; } @@ -948,11 +1009,6 @@ class Notice extends Memcached_DataObject { $groups = array(); - $enabled = common_config('inboxes', 'enabled'); - if ($enabled !== true && $enabled !== 'transitional') { - return $groups; - } - /* extract all !group */ $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/', strtolower($this->content), @@ -1043,12 +1099,12 @@ class Notice extends Memcached_DataObject for ($i=0; $i<count($names); $i++) { $nickname = $names[$i]; $recipient = common_relative_profile($sender, $nickname, $this->created); - if (!$recipient) { + if (empty($recipient)) { continue; } // Don't save replies from blocked profile to local user $recipient_user = User::staticGet('id', $recipient->id); - if ($recipient_user && $recipient_user->hasBlocked($sender)) { + if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) { continue; } $reply = new Reply(); @@ -1059,7 +1115,7 @@ class Notice extends Memcached_DataObject $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message); common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message)); - return; + return array(); } else { $replied[$recipient->id] = 1; } @@ -1083,7 +1139,7 @@ class Notice extends Memcached_DataObject $id = $reply->insert(); if (!$id) { common_log_db_error($reply, 'INSERT', __FILE__); - return; + return array(); } else { $replied[$recipient->id] = 1; } @@ -1092,12 +1148,16 @@ class Notice extends Memcached_DataObject } } - foreach (array_keys($replied) as $recipient) { + $recipientIds = array_keys($replied); + + foreach ($recipientIds as $recipient) { $user = User::staticGet('id', $recipient); if ($user) { mail_notify_attn($user, $this); } } + + return $recipientIds; } function asAtomEntry($namespace=false, $source=false) @@ -1121,10 +1181,9 @@ class Notice extends Memcached_DataObject $xs->element('link', array('href' => $profile->profileurl)); $user = User::staticGet('id', $profile->id); if (!empty($user)) { - $atom_feed = common_local_url('api', - array('apiaction' => 'statuses', - 'method' => 'user_timeline', - 'argument' => $profile->nickname.'.atom')); + $atom_feed = common_local_url('ApiTimelineUser', + array('format' => 'atom', + 'id' => $profile->nickname)); $xs->element('link', array('rel' => 'self', 'type' => 'application/atom+xml', 'href' => $profile->profileurl)); @@ -1181,16 +1240,23 @@ class Notice extends Memcached_DataObject $attachments = $this->attachments(); if($attachments){ foreach($attachments as $attachment){ - if ($attachment->isEnclosure()) { - $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size); - if($attachment->title){ - $attributes['title']=$attachment->title; + $enclosure=$attachment->getEnclosure(); + if ($enclosure) { + $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size); + if($enclosure->title){ + $attributes['title']=$enclosure->title; } $xs->element('link', $attributes, null); } } } + if (!empty($this->lat) && !empty($this->lon)) { + $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss')); + $xs->element('georss:point', null, $this->lat . ' ' . $this->lon); + $xs->elementEnd('geo'); + } + $xs->elementEnd('entry'); return $xs->getString(); @@ -1335,4 +1401,37 @@ class Notice extends Memcached_DataObject return $last->id; } } + + static function maxContent() + { + $contentlimit = common_config('notice', 'contentlimit'); + // null => use global limit (distinct from 0!) + if (is_null($contentlimit)) { + $contentlimit = common_config('site', 'textlimit'); + } + return $contentlimit; + } + + static function contentTooLong($content) + { + $contentlimit = self::maxContent(); + return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit)); + } + + function getLocation() + { + $location = null; + + if (!empty($this->location_id) && !empty($this->location_ns)) { + $location = Location::fromId($this->location_id, $this->location_ns); + } + + if (is_null($location)) { // no ID, or Location::fromId() failed + if (!empty($this->lat) && !empty($this->lon)) { + $location = Location::fromLatLon($this->lat, $this->lon); + } + } + + return $location; + } } diff --git a/classes/Plugin_DataObject.php b/classes/Plugin_DataObject.php new file mode 100644 index 000000000..d5cecf0f7 --- /dev/null +++ b/classes/Plugin_DataObject.php @@ -0,0 +1,195 @@ +<?php +/* + * StatusNet - the distributed open-source microblogging tool + * Copyright (C) 2008, 2009, StatusNet, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } + +require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; + +abstract class Plugin_DataObject extends Memcached_DataObject +{ + function table() { + static $table = null; + if($table == null) { + $table = array(); + $DB = $this->getDatabaseConnection(); + $dbtype = $DB->phptype; + $tableDef = $this->tableDef(); + foreach($tableDef->columns as $columnDef){ + switch(strtoupper($columnDef->type)) { + /*shamelessly copied from DB_DataObject_Generator*/ + case 'INT': + case 'INT2': // postgres + case 'INT4': // postgres + case 'INT8': // postgres + case 'SERIAL4': // postgres + case 'SERIAL8': // postgres + case 'INTEGER': + case 'TINYINT': + case 'SMALLINT': + case 'MEDIUMINT': + case 'BIGINT': + $type = DB_DATAOBJECT_INT; + if ($columnDef->size == 1) { + $type += DB_DATAOBJECT_BOOL; + } + break; + + case 'REAL': + case 'DOUBLE': + case 'DOUBLE PRECISION': // double precision (firebird) + case 'FLOAT': + case 'FLOAT4': // real (postgres) + case 'FLOAT8': // double precision (postgres) + case 'DECIMAL': + case 'MONEY': // mssql and maybe others + case 'NUMERIC': + case 'NUMBER': // oci8 + $type = DB_DATAOBJECT_INT; // should really by FLOAT!!! / MONEY... + break; + + case 'YEAR': + $type = DB_DATAOBJECT_INT; + break; + + case 'BIT': + case 'BOOL': + case 'BOOLEAN': + + $type = DB_DATAOBJECT_BOOL; + // postgres needs to quote '0' + if ($dbtype == 'pgsql') { + $type += DB_DATAOBJECT_STR; + } + break; + + case 'STRING': + case 'CHAR': + case 'VARCHAR': + case 'VARCHAR2': + case 'TINYTEXT': + + case 'ENUM': + case 'SET': // not really but oh well + + case 'POINT': // mysql geometry stuff - not really string - but will do.. + + case 'TIMESTAMPTZ': // postgres + case 'BPCHAR': // postgres + case 'INTERVAL': // postgres (eg. '12 days') + + case 'CIDR': // postgres IP net spec + case 'INET': // postgres IP + case 'MACADDR': // postgress network Mac address. + + case 'INTEGER[]': // postgres type + case 'BOOLEAN[]': // postgres type + + $type = DB_DATAOBJECT_STR; + break; + + case 'TEXT': + case 'MEDIUMTEXT': + case 'LONGTEXT': + + $type = DB_DATAOBJECT_STR + DB_DATAOBJECT_TXT; + break; + + + case 'DATE': + $type = DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE; + break; + + case 'TIME': + $type = DB_DATAOBJECT_STR + DB_DATAOBJECT_TIME; + break; + + + case 'DATETIME': + + $type = DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME; + break; + + case 'TIMESTAMP': // do other databases use this??? + + $type = ($dbtype == 'mysql') ? + DB_DATAOBJECT_MYSQLTIMESTAMP : + DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME; + break; + + + case 'BLOB': /// these should really be ignored!!!??? + case 'TINYBLOB': + case 'MEDIUMBLOB': + case 'LONGBLOB': + + case 'CLOB': // oracle character lob support + + case 'BYTEA': // postgres blob support.. + $type = DB_DATAOBJECT_STR + DB_DATAOBJECT_BLOB; + break; + + default: + throw new Exception("Cannot handle datatype: $columnDef->type"); + } + if(! $columnDef->nullable) { + $type+=DB_DATAOBJECT_NOTNULL; + } + $table[$columnDef->name]=$type; + } + } + return $table; + } + + function keys() { + static $keys = null; + if($keys == null) { + $keys = array(); + $tableDef = $this->tableDef(); + foreach($tableDef->columns as $columnDef){ + if($columnDef->key != null){ + $keys[] = $columnDef->name; + } + } + } + return $keys; + } + + function sequenceKey() { + static $sequenceKey = null; + if($sequenceKey == null) { + $sequenceKey = array(false,false); + $tableDef = $this->tableDef(); + foreach($tableDef->columns as $columnDef){ + if($columnDef->key == 'PRI' && $columnDef->auto_increment){ + $sequenceKey=array($columnDef->name,true); + } + } + } + return $sequenceKey; + } + + /** + * Get the TableDef object that represents the table backing this class + * Ideally, this function would a static function, but PHP doesn't allow + * abstract static functions + * @return TableDef TableDef instance + */ + abstract function tableDef(); +} + diff --git a/classes/Profile.php b/classes/Profile.php index 8385ebf88..4b2e09006 100644 --- a/classes/Profile.php +++ b/classes/Profile.php @@ -35,18 +35,28 @@ class Profile extends Memcached_DataObject public $fullname; // varchar(255) multiple_key public $profileurl; // varchar(255) public $homepage; // varchar(255) multiple_key - public $bio; // varchar(140) multiple_key + public $bio; // text() multiple_key public $location; // varchar(255) multiple_key + public $lat; // decimal(10,7) + public $lon; // decimal(10,7) + public $location_id; // int(4) + public $location_ns; // int(4) public $created; // datetime() not_null public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP /* Static get */ - function staticGet($k,$v=null) - { return Memcached_DataObject::staticGet('Profile',$k,$v); } + function staticGet($k,$v=NULL) { + return Memcached_DataObject::staticGet('Profile',$k,$v); + } /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE + function getUser() + { + return User::staticGet('id', $this->id); + } + function getAvatar($width, $height=null) { if (is_null($height)) { @@ -300,10 +310,12 @@ class Profile extends Memcached_DataObject 'AND subscription.subscribed != subscription.subscriber ' . 'ORDER BY subscription.created DESC '; - if (common_config('db','type') == 'pgsql') { - $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $qry .= ' LIMIT ' . $offset . ', ' . $limit; + if ($offset>0 && !is_null($limit)){ + if (common_config('db','type') == 'pgsql') { + $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; + } else { + $qry .= ' LIMIT ' . $offset . ', ' . $limit; + } } $profile = new Profile(); @@ -323,11 +335,13 @@ class Profile extends Memcached_DataObject 'AND subscription.subscribed != subscription.subscriber ' . 'ORDER BY subscription.created DESC '; - if ($offset) { - if (common_config('db','type') == 'pgsql') { - $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $qry .= ' LIMIT ' . $offset . ', ' . $limit; + if ($offset>0 && !is_null($limit)){ + if ($offset) { + if (common_config('db','type') == 'pgsql') { + $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; + } else { + $qry .= ' LIMIT ' . $offset . ', ' . $limit; + } } } @@ -462,6 +476,22 @@ class Profile extends Memcached_DataObject } } + static function maxBio() + { + $biolimit = common_config('profile', 'biolimit'); + // null => use global limit (distinct from 0!) + if (is_null($biolimit)) { + $biolimit = common_config('site', 'textlimit'); + } + return $biolimit; + } + + static function bioTooLong($bio) + { + $biolimit = self::maxBio(); + return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit)); + } + function delete() { $this->_deleteNotices(); @@ -536,4 +566,154 @@ class Profile extends Memcached_DataObject $block->blocked = $this->id; $block->delete(); } + + // XXX: identical to Notice::getLocation. + + function getLocation() + { + $location = null; + + if (!empty($this->location_id) && !empty($this->location_ns)) { + $location = Location::fromId($this->location_id, $this->location_ns); + } + + if (is_null($location)) { // no ID, or Location::fromId() failed + if (!empty($this->lat) && !empty($this->lon)) { + $location = Location::fromLatLon($this->lat, $this->lon); + } + } + + if (is_null($location)) { // still haven't found it! + if (!empty($this->location)) { + $location = Location::fromName($this->location); + } + } + + return $location; + } + + function hasRole($name) + { + $has_role = false; + if (Event::handle('StartHasRole', array($this, $name, &$has_role))) { + $role = Profile_role::pkeyGet(array('profile_id' => $this->id, + 'role' => $name)); + $has_role = !empty($role); + Event::handle('EndHasRole', array($this, $name, $has_role)); + } + return $has_role; + } + + function grantRole($name) + { + $role = new Profile_role(); + + $role->profile_id = $this->id; + $role->role = $name; + $role->created = common_sql_now(); + + $result = $role->insert(); + + if (!$result) { + common_log_db_error($role, 'INSERT', __FILE__); + return false; + } + + return true; + } + + function revokeRole($name) + { + $role = Profile_role::pkeyGet(array('profile_id' => $this->id, + 'role' => $name)); + + if (empty($role)) { + throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.'); + } + + $result = $role->delete(); + + if (!$result) { + common_log_db_error($role, 'DELETE', __FILE__); + throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.'); + } + + return true; + } + + function isSandboxed() + { + return $this->hasRole(Profile_role::SANDBOXED); + } + + function isSilenced() + { + return $this->hasRole(Profile_role::SILENCED); + } + + function sandbox() + { + $this->grantRole(Profile_role::SANDBOXED); + } + + function unsandbox() + { + $this->revokeRole(Profile_role::SANDBOXED); + } + + function silence() + { + $this->grantRole(Profile_role::SILENCED); + } + + function unsilence() + { + $this->revokeRole(Profile_role::SILENCED); + } + + /** + * Does this user have the right to do X? + * + * With our role-based authorization, this is merely a lookup for whether the user + * has a particular role. The implementation currently uses a switch statement + * to determine if the user has the pre-defined role to exercise the right. Future + * implementations may allow per-site roles, and different mappings of roles to rights. + * + * @param $right string Name of the right, usually a constant in class Right + * @return boolean whether the user has the right in question + */ + + function hasRight($right) + { + $result = false; + if (Event::handle('UserRightsCheck', array($this, $right, &$result))) { + switch ($right) + { + case Right::DELETEOTHERSNOTICE: + case Right::SANDBOXUSER: + case Right::SILENCEUSER: + case Right::DELETEUSER: + $result = $this->hasRole(Profile_role::MODERATOR); + break; + case Right::CONFIGURESITE: + $result = $this->hasRole(Profile_role::ADMINISTRATOR); + break; + case Right::NEWNOTICE: + case Right::NEWMESSAGE: + case Right::SUBSCRIBE: + $result = !$this->isSilenced(); + break; + case Right::PUBLICNOTICE: + case Right::EMAILONREPLY: + case Right::EMAILONSUBSCRIBE: + case Right::EMAILONFAVE: + $result = !$this->isSandboxed(); + break; + default: + $result = false; + break; + } + } + return $result; + } } diff --git a/classes/Profile_role.php b/classes/Profile_role.php new file mode 100644 index 000000000..afa7fb74e --- /dev/null +++ b/classes/Profile_role.php @@ -0,0 +1,55 @@ +<?php +/* + * StatusNet - the distributed open-source microblogging tool + * Copyright (C) 2009, StatusNet, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +/** + * Table Definition for profile_role + */ + +require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; + +class Profile_role extends Memcached_DataObject +{ + ###START_AUTOCODE + /* the code below is auto generated do not remove the above tag */ + + public $__table = 'profile_role'; // table name + public $profile_id; // int(4) primary_key not_null + public $role; // varchar(32) primary_key not_null + public $created; // datetime not_null default_0000-00-00%2000%3A00%3A00 + + /* Static get */ + function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Profile_role',$k,$v); } + + /* the code above is auto generated do not remove the tag below */ + ###END_AUTOCODE + + function &pkeyGet($kv) + { + return Memcached_DataObject::pkeyGet('Profile_role', $kv); + } + + const MODERATOR = 'moderator'; + const ADMINISTRATOR = 'administrator'; + const SANDBOXED = 'sandboxed'; + const SILENCED = 'silenced'; +} diff --git a/classes/Status_network.php b/classes/Status_network.php index fe4f0b0c5..b3117640d 100644 --- a/classes/Status_network.php +++ b/classes/Status_network.php @@ -57,14 +57,16 @@ class Status_network extends DB_DataObject $config['db']['ini_'.$dbname] = INSTALLDIR.'/classes/status_network.ini'; $config['db']['table_status_network'] = $dbname; - self::$cache = new Memcache(); + if (class_exists('Memcache')) { + self::$cache = new Memcache(); - if (is_array($servers)) { - foreach($servers as $server) { - self::$cache->addServer($server); + if (is_array($servers)) { + foreach($servers as $server) { + self::$cache->addServer($server); + } + } else { + self::$cache->addServer($servers); } - } else { - self::$cache->addServer($servers); } self::$base = $dbname; @@ -76,6 +78,10 @@ class Status_network extends DB_DataObject static function memGet($k, $v) { + if (!self::$cache) { + return self::staticGet($k, $v); + } + $ck = self::cacheKey($k, $v); $sn = self::$cache->get($ck); @@ -92,10 +98,12 @@ class Status_network extends DB_DataObject function decache() { - $keys = array('nickname', 'hostname', 'pathname'); - foreach ($keys as $k) { - $ck = self::cacheKey($k, $this->$k); - self::$cache->delete($ck); + if (self::$cache) { + $keys = array('nickname', 'hostname', 'pathname'); + foreach ($keys as $k) { + $ck = self::cacheKey($k, $this->$k); + self::$cache->delete($ck); + } } } diff --git a/classes/User.php b/classes/User.php index 7ab9f307a..f905ea2b7 100644 --- a/classes/User.php +++ b/classes/User.php @@ -103,10 +103,7 @@ class User extends Memcached_DataObject } $toupdate = implode(', ', $parts); - $table = $this->tableName(); - if(common_config('db','quote_identifiers')) { - $table = '"' . $table . '"'; - } + $table = common_database_tablename($this->tableName()); $qry = 'UPDATE ' . $table . ' SET ' . $toupdate . ' WHERE id = ' . $this->id; $orig->decache(); @@ -117,16 +114,26 @@ class User extends Memcached_DataObject return $result; } - function allowed_nickname($nickname) + static function allowed_nickname($nickname) { // XXX: should already be validated for size, content, etc. - static $blacklist = array('rss', 'xrds', 'doc', 'main', - 'settings', 'notice', 'user', - 'search', 'avatar', 'tag', 'tags', - 'api', 'message', 'group', 'groups', - 'local'); - $merged = array_merge($blacklist, common_config('nickname', 'blacklist')); - return !in_array($nickname, $merged); + $blacklist = common_config('nickname', 'blacklist'); + + //all directory and file names should be blacklisted + $d = dir(INSTALLDIR); + while (false !== ($entry = $d->read())) { + $blacklist[]=$entry; + } + $d->close(); + + //all top level names in the router should be blacklisted + $router = Router::get(); + foreach(array_keys($router->m->getPaths()) as $path){ + if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){ + $blacklist[]=$matches[1]; + } + } + return !in_array($nickname, $blacklist); } function getCurrentNotice($dt=null) @@ -183,7 +190,17 @@ class User extends Memcached_DataObject $profile->query('BEGIN'); + if(!empty($email)) + { + $email = common_canonical_email($email); + } + + $nickname = common_canonical_nickname($nickname); $profile->nickname = $nickname; + if(! User::allowed_nickname($nickname)){ + common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname), + __FILE__); + } $profile->profileurl = common_profile_url($nickname); if (!empty($fullname)) { @@ -197,6 +214,15 @@ class User extends Memcached_DataObject } if (!empty($location)) { $profile->location = $location; + + $loc = Location::fromName($location); + + if (!empty($loc)) { + $profile->lat = $loc->lat; + $profile->lon = $loc->lon; + $profile->location_id = $loc->location_id; + $profile->location_ns = $loc->location_ns; + } } $profile->created = common_sql_now(); @@ -226,12 +252,14 @@ class User extends Memcached_DataObject } } - $inboxes = common_config('inboxes', 'enabled'); - - if ($inboxes === true || $inboxes == 'transitional') { - $user->inboxed = 1; + if(isset($email_confirmed) && $email_confirmed) { + $user->email = $email; } + // This flag is ignored but still set to 1 + + $user->inboxed = 1; + $user->created = common_sql_now(); $user->uri = common_user_uri($user); @@ -320,6 +348,7 @@ class User extends Memcached_DataObject common_config('site', 'name'), $user->nickname), 'system'); + common_broadcast_notice($notice); } } @@ -432,55 +461,16 @@ class User extends Memcached_DataObject function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) { - $enabled = common_config('inboxes', 'enabled'); - - // Complicated code, depending on whether we support inboxes yet - // XXX: make this go away when inboxes become mandatory + $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false); - if ($enabled === false || - ($enabled == 'transitional' && $this->inboxed == 0)) { - $qry = - 'SELECT notice.* ' . - 'FROM notice JOIN subscription ON notice.profile_id = subscription.subscribed ' . - 'WHERE subscription.subscriber = %d ' . - 'AND notice.is_local != ' . Notice::GATEWAY; - return Notice::getStream(sprintf($qry, $this->id), - 'user:notices_with_friends:' . $this->id, - $offset, $limit, $since_id, $before_id, - $order, $since); - } else if ($enabled === true || - ($enabled == 'transitional' && $this->inboxed == 1)) { - - $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false); - - return Notice::getStreamByIds($ids); - } + return Notice::getStreamByIds($ids); } function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) { - $enabled = common_config('inboxes', 'enabled'); + $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true); - // Complicated code, depending on whether we support inboxes yet - // XXX: make this go away when inboxes become mandatory - - if ($enabled === false || - ($enabled == 'transitional' && $this->inboxed == 0)) { - $qry = - 'SELECT notice.* ' . - 'FROM notice JOIN subscription ON notice.profile_id = subscription.subscribed ' . - 'WHERE subscription.subscriber = %d '; - return Notice::getStream(sprintf($qry, $this->id), - 'user:notices_with_friends:' . $this->id, - $offset, $limit, $since_id, $before_id, - $order, $since); - } else if ($enabled === true || - ($enabled == 'transitional' && $this->inboxed == 1)) { - - $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true); - - return Notice::getStreamByIds($ids); - } + return Notice::getStreamByIds($ids); } function blowFavesCache() @@ -587,11 +577,13 @@ class User extends Memcached_DataObject 'WHERE group_member.profile_id = %d ' . 'ORDER BY group_member.created DESC '; - if ($offset) { - if (common_config('db','type') == 'pgsql') { - $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $qry .= ' LIMIT ' . $offset . ', ' . $limit; + if ($offset>0 && !is_null($limit)) { + if ($offset) { + if (common_config('db','type') == 'pgsql') { + $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; + } else { + $qry .= ' LIMIT ' . $offset . ', ' . $limit; + } } } @@ -630,11 +622,7 @@ class User extends Memcached_DataObject 'ORDER BY subscription.created DESC '; if ($offset) { - if (common_config('db','type') == 'pgsql') { - $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $qry .= ' LIMIT ' . $offset . ', ' . $limit; - } + $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; } $profile = new Profile(); @@ -657,11 +645,7 @@ class User extends Memcached_DataObject 'AND subscription.subscribed != subscription.subscriber ' . 'ORDER BY subscription.created DESC '; - if (common_config('db','type') == 'pgsql') { - $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $qry .= ' LIMIT ' . $offset . ', ' . $limit; - } + $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; $profile = new Profile(); @@ -670,38 +654,32 @@ class User extends Memcached_DataObject return $profile; } - function hasOpenID() + function getDesign() { - $oid = new User_openid(); - - $oid->user_id = $this->id; - - $cnt = $oid->find(); - - return ($cnt > 0); + return Design::staticGet('id', $this->design_id); } - function getDesign() + function hasRight($right) { - return Design::staticGet('id', $this->design_id); + $profile = $this->getProfile(); + return $profile->hasRight($right); } function delete() { $profile = $this->getProfile(); - $profile->delete(); + if ($profile) { + $profile->delete(); + } $related = array('Fave', - 'User_openid', 'Confirm_address', 'Remember_me', 'Foreign_link', 'Invitation', + 'Notice_inbox', ); - - if (common_config('inboxes', 'enabled')) { - $related[] = 'Notice_inbox'; - } + Event::handle('UserDeleteRelated', array($this, &$related)); foreach ($related as $cls) { $inst = new $cls(); @@ -729,4 +707,34 @@ class User extends Memcached_DataObject $block->delete(); // XXX delete group block? Reset blocker? } + + function hasRole($name) + { + $profile = $this->getProfile(); + return $profile->hasRole($name); + } + + function grantRole($name) + { + $profile = $this->getProfile(); + return $profile->grantRole($name); + } + + function revokeRole($name) + { + $profile = $this->getProfile(); + return $profile->revokeRole($name); + } + + function isSandboxed() + { + $profile = $this->getProfile(); + return $profile->isSandboxed(); + } + + function isSilenced() + { + $profile = $this->getProfile(); + return $profile->isSilenced(); + } } diff --git a/classes/User_group.php b/classes/User_group.php index ea19cbb97..c86eadf8f 100644 --- a/classes/User_group.php +++ b/classes/User_group.php @@ -13,7 +13,7 @@ class User_group extends Memcached_DataObject public $nickname; // varchar(64) unique_key public $fullname; // varchar(255) public $homepage; // varchar(255) - public $description; // varchar(140) + public $description; // text() public $location; // varchar(255) public $original_logo; // varchar(255) public $homepage_logo; // varchar(255) @@ -34,7 +34,7 @@ class User_group extends Memcached_DataObject static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', AVATAR_STREAM_SIZE => 'stream', AVATAR_MINI_SIZE => 'mini'); - return theme_path('default-avatar-'.$sizenames[$size].'.png'); + return Theme::path('default-avatar-'.$sizenames[$size].'.png'); } function homeUrl() @@ -298,6 +298,22 @@ class User_group extends Memcached_DataObject return $ids; } + static function maxDescription() + { + $desclimit = common_config('group', 'desclimit'); + // null => use global limit (distinct from 0!) + if (is_null($desclimit)) { + $desclimit = common_config('site', 'textlimit'); + } + return $desclimit; + } + + static function descriptionTooLong($desc) + { + $desclimit = self::maxDescription(); + return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit)); + } + function asAtomEntry($namespace=false, $source=false) { $xs = new XMLStringer(true); @@ -338,4 +354,66 @@ class User_group extends Memcached_DataObject return $xs->getString(); } + + static function register($fields) { + + // MAGICALLY put fields into current scope + + extract($fields); + + $group = new User_group(); + + $group->query('BEGIN'); + + $group->nickname = $nickname; + $group->fullname = $fullname; + $group->homepage = $homepage; + $group->description = $description; + $group->location = $location; + $group->created = common_sql_now(); + + $result = $group->insert(); + + if (!$result) { + common_log_db_error($group, 'INSERT', __FILE__); + $this->serverError( + _('Could not create group.'), + 500, + $this->format + ); + return; + } + $result = $group->setAliases($aliases); + + if (!$result) { + $this->serverError( + _('Could not create aliases.'), + 500, + $this->format + ); + return; + } + + $member = new Group_member(); + + $member->group_id = $group->id; + $member->profile_id = $userid; + $member->is_admin = 1; + $member->created = $group->created; + + $result = $member->insert(); + + if (!$result) { + common_log_db_error($member, 'INSERT', __FILE__); + $this->serverError( + _('Could not set group membership.'), + 500, + $this->format + ); + return; + } + + $group->query('COMMIT'); + return $group; + } } diff --git a/classes/User_openid.php b/classes/User_openid.php deleted file mode 100644 index f4fda1c72..000000000 --- a/classes/User_openid.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php -/** - * Table Definition for user_openid - */ -require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; - -class User_openid extends Memcached_DataObject -{ - ###START_AUTOCODE - /* the code below is auto generated do not remove the above tag */ - - public $__table = 'user_openid'; // table name - public $canonical; // varchar(255) primary_key not_null - public $display; // varchar(255) unique_key not_null - public $user_id; // int(4) not_null - public $created; // datetime() not_null - public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP - - /* Static get */ - function staticGet($k,$v=null) - { return Memcached_DataObject::staticGet('User_openid',$k,$v); } - - /* the code above is auto generated do not remove the tag below */ - ###END_AUTOCODE -} diff --git a/classes/statusnet.ini b/classes/statusnet.ini index 766bed75d..b2509dac5 100644 --- a/classes/statusnet.ini +++ b/classes/statusnet.ini @@ -16,6 +16,15 @@ width = K height = K url = U +[config] +section = 130 +setting = 130 +value = 2 + +[config__keys] +section = K +setting = K + [confirm_address] code = 130 user_id = 129 @@ -38,6 +47,17 @@ modified = 384 [consumer__keys] consumer_key = K +[deleted_notice] +id = 129 +profile_id = 129 +uri = 2 +created = 142 +deleted = 142 + +[deleted_notice__keys] +id = K +uri = U + [design] id = 129 backgroundcolor = 1 @@ -78,6 +98,7 @@ id = N file_id = 129 version = 2 type = 2 +mimetype = 2 provider = 2 provider_url = 2 width = 1 @@ -223,12 +244,30 @@ created = 142 [invitation__keys] code = K +[location_namespace] +id = 129 +description = 2 +created = 142 +modified = 384 + +[location_namespace__keys] +id = K + +[login_token] +user_id = 129 +token = 130 +created = 142 +modified = 384 + +[login_token__keys] +user_id = K + [message] id = 129 uri = 2 from_profile = 129 to_profile = 129 -content = 2 +content = 34 rendered = 34 url = 2 created = 142 @@ -255,7 +294,7 @@ ts = K id = 129 profile_id = 129 uri = 2 -content = 2 +content = 34 rendered = 34 url = 2 created = 142 @@ -264,6 +303,10 @@ reply_to = 1 is_local = 17 source = 2 conversation = 1 +lat = 1 +lon = 1 +location_id = 1 +location_ns = 1 [notice__keys] id = N @@ -303,8 +346,12 @@ nickname = 130 fullname = 2 profileurl = 2 homepage = 2 -bio = 2 +bio = 34 location = 2 +lat = 1 +lon = 1 +location_id = 1 +location_ns = 1 created = 142 modified = 384 @@ -320,6 +367,15 @@ modified = 384 blocker = K blocked = K +[profile_role] +profile_id = 129 +role = 130 +created = 142 + +[profile_role__keys] +profile_id = K +role = K + [profile_tag] tagger = 129 tagged = 129 @@ -475,7 +531,7 @@ id = 129 nickname = 2 fullname = 2 homepage = 2 -description = 2 +description = 34 location = 2 original_logo = 2 homepage_logo = 2 @@ -486,15 +542,4 @@ created = 142 modified = 384 [user_group__keys] -id = N - -[user_openid] -canonical = 130 -display = 130 -user_id = 129 -created = 142 -modified = 384 - -[user_openid__keys] -canonical = K -display = U +id = N
\ No newline at end of file |