Merge branch '1.0.x' into profile-fixups

This commit is contained in:
Zach Copley 2011-03-10 14:22:41 -08:00
commit 78dc4f3a3d
10 changed files with 355 additions and 43 deletions

View File

@ -309,7 +309,8 @@ abstract class MicroAppPlugin extends Plugin
'is_local' => Notice::REMOTE_OMB, 'is_local' => Notice::REMOTE_OMB,
'source' => 'ostatus'); 'source' => 'ostatus');
$this->saveNoticeFromActivity($activity, $actor); // $actor is an ostatus_profile
$this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
return false; return false;
} }
@ -365,7 +366,8 @@ abstract class MicroAppPlugin extends Plugin
'is_local' => Notice::REMOTE_OMB, 'is_local' => Notice::REMOTE_OMB,
'source' => 'ostatus'); 'source' => 'ostatus');
$this->saveNoticeFromActivity($activity, $actor, $options); // $actor is an ostatus_profile
$this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
return false; return false;
} }
@ -389,6 +391,7 @@ abstract class MicroAppPlugin extends Plugin
$options = array('source' => 'atompub'); $options = array('source' => 'atompub');
// $user->getProfile() is a Profile
$this->saveNoticeFromActivity($activity, $this->saveNoticeFromActivity($activity,
$user->getProfile(), $user->getProfile(),
$options); $options);
@ -421,6 +424,7 @@ abstract class MicroAppPlugin extends Plugin
'url' => $object->link, 'url' => $object->link,
'source' => 'restore'); 'source' => 'restore');
// $user->getProfile() is a Profile
$saved = $this->saveNoticeFromActivity($activity, $saved = $this->saveNoticeFromActivity($activity,
$user->getProfile(), $user->getProfile(),
$options); $options);

View File

@ -1,4 +1,15 @@
$(document).ready(function(){ (function(SN, $) {
var origInit = SN.Init.NoticeFormSetup;
SN.Init.NoticeFormSetup = function(form) {
origInit(form);
// Only attach to traditional-style forms
var textarea = form.find('.notice_data-text:first');
if (textarea.length == 0) {
return;
}
function fullName(row) { function fullName(row) {
if (typeof row.fullname == "string" && row.fullname != '') { if (typeof row.fullname == "string" && row.fullname != '') {
return row.nickname + ' (' + row.fullname + ')'; return row.nickname + ' (' + row.fullname + ')';
@ -6,7 +17,9 @@ $(document).ready(function(){
return row.nickname; return row.nickname;
} }
} }
$('#notice_data-text').autocomplete($('address .url')[0].href+'main/autocomplete/suggest', {
var apiUrl = $('#autocomplete-api').attr('data-url');
textarea.autocomplete(apiUrl, {
multiple: true, multiple: true,
multipleSeparator: " ", multipleSeparator: " ",
minChars: 1, minChars: 1,
@ -35,4 +48,6 @@ $(document).ready(function(){
} }
} }
}); });
}); };
})(SN, jQuery);

View File

@ -51,6 +51,8 @@ class AutocompletePlugin extends Plugin
function onEndShowScripts($action){ function onEndShowScripts($action){
if (common_logged_in()) { if (common_logged_in()) {
$action->element('span', array('id' => 'autocomplete-api',
'data-url' => common_local_url('autocomplete')));
$action->script($this->path('jquery-autocomplete/jquery.autocomplete.pack.js')); $action->script($this->path('jquery-autocomplete/jquery.autocomplete.pack.js'));
$action->script($this->path('Autocomplete.js')); $action->script($this->path('Autocomplete.js'));
} }

View File

@ -47,15 +47,26 @@
return true; return true;
return false; return false;
}; };
$(document).ready(function(){ var origInit = SN.Init.NoticeFormSetup;
var tArea = $("#notice_data-text"); SN.Init.NoticeFormSetup = function(form) {
origInit(form);
var tArea = form.find(".notice_data-text:first");
if (tArea.length > 0) {
var tCleaner = new RegExp('@[^ ]+|![^ ]+|#[^ ]+|^RT[: ]{1}| RT | RT: |^RD[: ]{1}| RD | RD: |[♺♻:]+', 'g') var tCleaner = new RegExp('@[^ ]+|![^ ]+|#[^ ]+|^RT[: ]{1}| RT | RT: |^RD[: ]{1}| RD | RD: |[♺♻:]+', 'g')
tArea.keyup(function(){ var ping = function(){
var cleaned = tArea.val().replace(tCleaner, '').replace(/^[ ]+/, ''); var cleaned = tArea.val().replace(tCleaner, '').replace(/^[ ]+/, '');
if($().isRTL(cleaned)) if($().isRTL(cleaned))
tArea.css('direction', 'rtl'); tArea.css('direction', 'rtl');
else else
tArea.css('direction', 'ltr'); tArea.css('direction', 'ltr');
};
tArea.bind('keyup cut paste', function() {
// cut/paste trigger before the change
window.setTimeout(ping, 0);
}); });
form.bind('reset', function() {
tArea.css('direction', 'ltr');
}); });
}
};
})(jQuery); })(jQuery);

View File

@ -128,8 +128,8 @@ class AlphaNav extends Widget
$current = $this->action->arg('filter'); $current = $this->action->arg('filter');
// Highlight the selected filter. If there is no selected // Highlight the selected filter. If there is no selected
// filter, highlight the first filter in the list // filter, highlight the last filter in the list (all)
if (!isset($current) && $i == 0 if (!isset($current) && $i == ($size - 1)
|| $current === strtolower($filter)) { || $current === strtolower($filter)) {
$classes .= 'current '; $classes .= 'current ';
} }

View File

@ -47,6 +47,7 @@ class Poll extends Managed_DataObject
{ {
public $__table = 'poll'; // table name public $__table = 'poll'; // table name
public $id; // char(36) primary key not null -> UUID public $id; // char(36) primary key not null -> UUID
public $uri;
public $profile_id; // int -> profile.id public $profile_id; // int -> profile.id
public $question; // text public $question; // text
public $options; // text; newline(?)-delimited public $options; // text; newline(?)-delimited
@ -127,6 +128,23 @@ class Poll extends Managed_DataObject
return explode("\n", $this->options); return explode("\n", $this->options);
} }
/**
* Is this a valid selection index?
*
* @param numeric $selection (1-based)
* @return boolean
*/
function isValidSelection($selection)
{
if ($selection != intval($selection)) {
return false;
}
if ($selection < 1 || $selection > count($this->getOptions())) {
return false;
}
return true;
}
function getNotice() function getNotice()
{ {
return Notice::staticGet('uri', $this->uri); return Notice::staticGet('uri', $this->uri);

View File

@ -47,7 +47,10 @@ if (!defined('STATUSNET')) {
class PollPlugin extends MicroAppPlugin class PollPlugin extends MicroAppPlugin
{ {
const VERSION = '0.1'; const VERSION = '0.1';
// @fixme which domain should we use for these namespaces?
const POLL_OBJECT = 'http://apinamespace.org/activitystreams/object/poll'; const POLL_OBJECT = 'http://apinamespace.org/activitystreams/object/poll';
const POLL_RESPONSE_OBJECT = 'http://apinamespace.org/activitystreams/object/poll-response';
/** /**
* Database schema setup * Database schema setup
@ -124,8 +127,15 @@ class PollPlugin extends MicroAppPlugin
function onRouterInitialized($m) function onRouterInitialized($m)
{ {
$m->connect('main/poll/new', $m->connect('main/poll/new',
array('action' => 'newpoll'), array('action' => 'newpoll'));
array('id' => '[0-9]+'));
$m->connect('main/poll/:id',
array('action' => 'showpoll'),
array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
$m->connect('main/poll/response/:id',
array('action' => 'showpollresponse'),
array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
$m->connect('main/poll/:id/respond', $m->connect('main/poll/:id/respond',
array('action' => 'respondpoll'), array('action' => 'respondpoll'),
@ -155,7 +165,7 @@ class PollPlugin extends MicroAppPlugin
function types() function types()
{ {
return array(self::POLL_OBJECT); return array(self::POLL_OBJECT, self::POLL_RESPONSE_OBJECT);
} }
/** /**
@ -190,17 +200,124 @@ class PollPlugin extends MicroAppPlugin
function saveNoticeFromActivity($activity, $profile, $options=array()) function saveNoticeFromActivity($activity, $profile, $options=array())
{ {
// @fixme // @fixme
common_log(LOG_DEBUG, "XXX activity: " . var_export($activity, true));
common_log(LOG_DEBUG, "XXX profile: " . var_export($profile, true));
common_log(LOG_DEBUG, "XXX options: " . var_export($options, true));
// Ok for now, we can grab stuff from the XML entry directly.
// This won't work when reading from JSON source
if ($activity->entry) {
$pollElements = $activity->entry->getElementsByTagNameNS(self::POLL_OBJECT, 'poll');
$responseElements = $activity->entry->getElementsByTagNameNS(self::POLL_OBJECT, 'response');
if ($pollElements->length) {
$data = $pollElements->item(0);
$question = $data->getAttribute('question');
$opts = array();
foreach ($data->attributes as $node) {
$name = $node->nodeName;
if (substr($name, 0, 6) == 'option') {
$n = intval(substr($name, 6));
if ($n > 0) {
$opts[$n - 1] = $node->nodeValue;
}
}
}
common_log(LOG_DEBUG, "YYY question: $question");
common_log(LOG_DEBUG, "YYY opts: " . var_export($opts, true));
try {
$notice = Poll::saveNew($profile, $question, $opts, $options);
common_log(LOG_DEBUG, "YYY ok: " . $notice->id);
return $notice;
} catch (Exception $e) {
common_log(LOG_DEBUG, "YYY fail: " . $e->getMessage());
}
} else if ($responseElements->length) {
$data = $responseElements->item(0);
$pollUri = $data->getAttribute('poll');
$selection = intval($data->getAttribute('selection'));
if (!$pollUri) {
throw new Exception('Invalid poll response: no poll reference.');
}
$poll = Poll::staticGet('uri', $pollUri);
if (!$poll) {
throw new Exception('Invalid poll response: poll is unknown.');
}
try {
$notice = Poll_response::saveNew($profile, $poll, $selection, $options);
common_log(LOG_DEBUG, "YYY response ok: " . $notice->id);
return $notice;
} catch (Exception $e) {
common_log(LOG_DEBUG, "YYY response fail: " . $e->getMessage());
}
} else {
common_log(LOG_DEBUG, "YYY no poll data");
}
}
} }
function activityObjectFromNotice($notice) function activityObjectFromNotice($notice)
{ {
assert($this->isMyNotice($notice)); assert($this->isMyNotice($notice));
switch ($notice->object_type) {
case self::POLL_OBJECT:
return $this->activityObjectFromNoticePoll($notice);
case self::POLL_RESPONSE_OBJECT:
return $this->activityObjectFromNoticePollResponse($notice);
default:
throw new Exception('Unexpected type for poll plugin: ' . $notice->object_type);
}
}
function activityObjectFromNoticePollResponse($notice)
{
$object = new ActivityObject(); $object = new ActivityObject();
$object->id = $notice->uri; $object->id = $notice->uri;
$object->type = self::POLL_OBJECT; $object->type = self::POLL_OBJECT;
$object->title = 'Poll title'; $object->title = $notice->content;
$object->summary = 'Poll summary'; $object->summary = $notice->content;
$object->link = $notice->bestUrl();
$response = Poll_response::getByNotice($notice);
if (!$response) {
common_log(LOG_DEBUG, "QQQ notice uri: $notice->uri");
} else {
$poll = $response->getPoll();
/**
* For the moment, using a kind of icky-looking schema that happens to
* work with out code for generating both Atom and JSON forms, though
* I don't like it:
*
* <poll:response xmlns:poll="http://apinamespace.org/activitystreams/object/poll"
* poll="http://..../poll/...."
* selection="3" />
*
* "poll:response": {
* "xmlns:poll": http://apinamespace.org/activitystreams/object/poll
* "uri": "http://..../poll/...."
* "selection": 3
* }
*
*/
// @fixme there's no way to specify an XML node tree here, like <poll><option/><option/></poll>
// @fixme there's no way to specify a JSON array or multi-level tree unless you break the XML attribs
// @fixme XML node contents don't get shown in JSON
$data = array('xmlns:poll' => self::POLL_OBJECT,
'poll' => $poll->uri,
'selection' => intval($response->selection));
$object->extra[] = array('poll:response', $data, '');
}
return $object;
}
function activityObjectFromNoticePoll($notice)
{
$object = new ActivityObject();
$object->id = $notice->uri;
$object->type = self::POLL_RESPONSE_OBJECT;
$object->title = $notice->content;
$object->summary = $notice->content;
$object->link = $notice->bestUrl(); $object->link = $notice->bestUrl();
$poll = Poll::getByNotice($notice); $poll = Poll::getByNotice($notice);
@ -218,7 +335,7 @@ class PollPlugin extends MicroAppPlugin
* option2="Option two" * option2="Option two"
* option3="Option three"></poll:data> * option3="Option three"></poll:data>
* *
* "poll:data": { * "poll:response": {
* "xmlns:poll": http://apinamespace.org/activitystreams/object/poll * "xmlns:poll": http://apinamespace.org/activitystreams/object/poll
* "question": "Who wants a poll question?" * "question": "Who wants a poll question?"
* "option1": "Option one" * "option1": "Option one"
@ -235,7 +352,7 @@ class PollPlugin extends MicroAppPlugin
foreach ($poll->getOptions() as $i => $opt) { foreach ($poll->getOptions() as $i => $opt) {
$data['option' . ($i + 1)] = $opt; $data['option' . ($i + 1)] = $opt;
} }
$object->extra[] = array('poll:data', $data, ''); $object->extra[] = array('poll:poll', $data, '');
return $object; return $object;
} }
@ -245,6 +362,18 @@ class PollPlugin extends MicroAppPlugin
* and Bookmark plugin for if that's right. * and Bookmark plugin for if that's right.
*/ */
function showNotice($notice, $out) function showNotice($notice, $out)
{
switch ($notice->object_type) {
case self::POLL_OBJECT:
return $this->showNoticePoll($notice, $out);
case self::POLL_RESPONSE_OBJECT:
return $this->showNoticePollResponse($notice, $out);
default:
throw new Exception('Unexpected type for poll plugin: ' . $notice->object_type);
}
}
function showNoticePoll($notice, $out)
{ {
$user = common_current_user(); $user = common_current_user();
@ -275,6 +404,18 @@ class PollPlugin extends MicroAppPlugin
$out->elementStart('div', array('class' => 'entry-content')); $out->elementStart('div', array('class' => 'entry-content'));
} }
function showNoticePollResponse($notice, $out)
{
$user = common_current_user();
// @hack we want regular rendering, then just add stuff after that
$nli = new NoticeListItem($notice, $out);
$nli->showNotice();
// @fixme
$out->elementStart('div', array('class' => 'entry-content'));
}
function entryForm($out) function entryForm($out)
{ {
return new NewPollForm($out); return new NewPollForm($out);

View File

@ -46,7 +46,8 @@ if (!defined('STATUSNET')) {
class Poll_response extends Managed_DataObject class Poll_response extends Managed_DataObject
{ {
public $__table = 'poll_response'; // table name public $__table = 'poll_response'; // table name
public $poll_id; // char(36) primary key not null -> UUID public $id; // char(36) primary key not null -> UUID
public $poll_id; // char(36) -> poll.id UUID
public $profile_id; // int -> profile.id public $profile_id; // int -> profile.id
public $selection; // int -> choice # public $selection; // int -> choice #
public $created; // datetime public $created; // datetime
@ -94,12 +95,16 @@ class Poll_response extends Managed_DataObject
return array( return array(
'description' => 'Record of responses to polls', 'description' => 'Record of responses to polls',
'fields' => array( 'fields' => array(
'poll_id' => array('type' => 'char', 'length' => 36, 'not null' => true, 'description' => 'UUID'), 'id' => array('type' => 'char', 'length' => 36, 'not null' => true, 'description' => 'UUID of the response'),
'uri' => array('type' => 'varchar', 'length' => 255, 'not null' => true, 'description' => 'UUID to the response notice'),
'poll_id' => array('type' => 'char', 'length' => 36, 'not null' => true, 'description' => 'UUID of poll being responded to'),
'profile_id' => array('type' => 'int'), 'profile_id' => array('type' => 'int'),
'selection' => array('type' => 'int'), 'selection' => array('type' => 'int'),
'created' => array('type' => 'datetime', 'not null' => true), 'created' => array('type' => 'datetime', 'not null' => true),
), ),
'primary key' => array('id'),
'unique keys' => array( 'unique keys' => array(
'poll_uri_key' => array('uri'),
'poll_response_poll_id_profile_id_key' => array('poll_id', 'profile_id'), 'poll_response_poll_id_profile_id_key' => array('poll_id', 'profile_id'),
), ),
'indexes' => array( 'indexes' => array(
@ -107,4 +112,115 @@ class Poll_response extends Managed_DataObject
) )
); );
} }
/**
* Get a poll response based on a notice
*
* @param Notice $notice Notice to check for
*
* @return Poll_response found response or null
*/
function getByNotice($notice)
{
return self::staticGet('uri', $notice->uri);
}
/**
* Get the notice that belongs to this response...
*
* @return Notice
*/
function getNotice()
{
return Notice::staticGet('uri', $this->uri);
}
function bestUrl()
{
return $this->getNotice()->bestUrl();
}
/**
*
* @return Poll
*/
function getPoll()
{
return Poll::staticGet('id', $this->poll_id);
}
/**
* Save a new poll notice
*
* @param Profile $profile
* @param Poll $poll the poll being responded to
* @param int $selection (1-based)
* @param array $opts (poll responses)
*
* @return Notice saved notice
*/
static function saveNew($profile, $poll, $selection, $options=null)
{
if (empty($options)) {
$options = array();
}
if (!$poll->isValidSelection($selection)) {
throw new ClientException(_m('Invalid poll selection.'));
}
$opts = $poll->getOptions();
$answer = $opts[$selection - 1];
$pr = new Poll_response();
$pr->id = UUID::gen();
$pr->profile_id = $profile->id;
$pr->poll_id = $poll->id;
$pr->selection = $selection;
if (array_key_exists('created', $options)) {
$pr->created = $options['created'];
} else {
$pr->created = common_sql_now();
}
if (array_key_exists('uri', $options)) {
$pr->uri = $options['uri'];
} else {
$pr->uri = common_local_url('showpollresponse',
array('id' => $pr->id));
}
common_log(LOG_DEBUG, "Saving poll response: $pr->id $pr->uri");
$pr->insert();
$content = sprintf(_m('voted for "%s"'),
$answer);
$rendered = sprintf(_m('voted for “<a href="%s">%s</a>”'),
htmlspecialchars($poll->uri),
htmlspecialchars($answer));
$tags = array();
$replies = array();
$options = array_merge(array('urls' => array(),
'rendered' => $rendered,
'tags' => $tags,
'replies' => $replies,
'reply_to' => $poll->getNotice()->id,
'object_type' => PollPlugin::POLL_RESPONSE_OBJECT),
$options);
if (!array_key_exists('uri', $options)) {
$options['uri'] = $pr->uri;
}
$saved = Notice::saveNew($profile->id,
$content,
array_key_exists('source', $options) ?
$options['source'] : 'web',
$options);
return $saved;
}
} }

View File

@ -75,6 +75,9 @@ class RespondPollAction extends Action
function prepare($argarray) function prepare($argarray)
{ {
parent::prepare($argarray); parent::prepare($argarray);
if ($this->boolean('ajax')) {
StatusNet::setApi(true);
}
$this->user = common_current_user(); $this->user = common_current_user();
@ -132,20 +135,16 @@ class RespondPollAction extends Action
function respondPoll() function respondPoll()
{ {
try { try {
$response = new Poll_response(); $notice = Poll_response::saveNew($this->user->getProfile(),
$response->poll_id = $this->poll->id; $this->poll,
$response->profile_id = $this->user->id; $this->selection);
$response->selection = $this->selection;
$response->created = common_sql_now();
$response->insert();
} catch (ClientException $ce) { } catch (ClientException $ce) {
$this->error = $ce->getMessage(); $this->error = $ce->getMessage();
$this->showPage(); $this->showPage();
return; return;
} }
if ($this->arg('ajax')) { if ($this->boolean('ajax')) {
header('Content-Type: text/xml;charset=utf-8'); header('Content-Type: text/xml;charset=utf-8');
$this->xw->startDocument('1.0', 'UTF-8'); $this->xw->startDocument('1.0', 'UTF-8');
$this->elementStart('html'); $this->elementStart('html');

View File

@ -290,9 +290,14 @@ class TinyMCEPlugin extends Plugin
// our AJAX form submission. Manually moving it to trigger // our AJAX form submission. Manually moving it to trigger
// on our send button click. // on our send button click.
$scr = <<<END_OF_SCRIPT $scr = <<<END_OF_SCRIPT
$().ready(function() { (function() {
var noticeForm = $('#form_notice'); var origInit = SN.Init.NoticeFormSetup;
$('textarea#notice_data-text').tinymce({ SN.Init.NoticeFormSetup = function(form) {
origInit(form);
var noticeForm = form;
var textarea = form.find('.notice_data-text');
if (textarea.length == 0) return;
textarea.tinymce({
script_url : '{$path}', script_url : '{$path}',
// General options // General options
theme : "advanced", theme : "advanced",
@ -306,7 +311,7 @@ class TinyMCEPlugin extends Plugin
setup: function(ed) { setup: function(ed) {
noticeForm.append('<input type="hidden" name="richedit" value="1">'); noticeForm.append('<input type="hidden" name="richedit" value="1">');
$('#notice_action-submit').click(function() { form.find('.submit:first').click(function() {
tinymce.triggerSave(); tinymce.triggerSave();
}); });
@ -319,14 +324,15 @@ class TinyMCEPlugin extends Plugin
SN.U.Counter(noticeForm); SN.U.Counter(noticeForm);
}); });
$('#'+SN.C.S.NoticeDataAttach).change(function() { form.find('input[type=file]').change(function() {
var img = '<img src="{$placeholder}" class="placeholder" width="320" height="240">'; var img = '<img src="{$placeholder}" class="placeholder" width="320" height="240">';
var html = tinyMCE.activeEditor.getContent(); var html = tinyMCE.activeEditor.getContent();
ed.setContent(html + img); ed.setContent(html + img);
}); });
} }
}); });
}); };
})();
END_OF_SCRIPT; END_OF_SCRIPT;
return $scr; return $scr;