~quam-plures-core/quam-plures/admin_look_and_feel

« back to all changes in this revision

Viewing changes to qp_plugins/twitter_plugin/_twitter.plugin.php

  • Committer: yabs
  • Author(s): EdB
  • Date: 2010-10-20 14:55:54 UTC
  • mfrom: (7557.7.2 twitter_plugin)
  • Revision ID: yabs@innervisions.org.uk-20101020145554-uz2iv6h742uoeeq0
Added twitter plugin wuth oauth

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
<?php
2
2
/**
3
 
 * This file implements the Twitter plugin.
4
 
 *
5
 
 * For the most recent and complete Plugin API documentation
6
 
 * see {@link Plugin} in ../evocore/_plugin.class.php.
7
 
 *
8
 
 * This plugin will post to your twitter account when you have added a post to your blog.
9
 
 *
10
 
 * @todo (legacy): use OAuth -- http://www.jaisenmathai.com/blog/2009/03/31/how-to-quickly-integrate-with-twitters-oauth-api-using-php/
11
 
 * @todo (legacy): Tblue> Do not use cURL, or at least do not depend on it! We could
12
 
 *              clone/modify {@link fetch_remote_page()} to be able to do
13
 
 *
 
3
 * This file implements the Twitter plugin for Quam Plures
 
4
 *
 
5
 * READ THE README! That's where all the answers to all your questions are!
 
6
 *
 
7
 * Some folk think licensing matters.  I guess maybe it does, but so does a 45
 
8
 * caliber semi-automatic pistol. Just sayin'  Anyway let's talk licensing.
 
9
 * This plugin is based on and built on three different programs, all of which
 
10
 * have some sort of licensing crap in them.
 
11
 * 
 
12
 * -----------------------------------------------------------------------------
 
13
 * 
 
14
 * First, this exact file is built on the corpse of a dead plugin with the same
 
15
 * name.  It claimed copyright by 2 persons and 1 entity, and claimed release
 
16
 * under a GPL2 license.  Were the contributions of each person and party
 
17
 * identified? No. Did it say exactly who decided it was GPL2? No. Near as I can
 
18
 * tell it's all a bunch of crap designed to make sure a lawyer could charge a
 
19
 * fortune of hourly time just reading this rubbish, but whatever: here for your
 
20
 * entertainment is the original tidbits from the original version of this file:
 
21
 * 
14
22
 * This file is part of the Quam Plures project - {@link http://quamplures.net/}
15
 
 *
 
23
 * 
16
24
 * @copyright (c) 2009 by the Quam Plures developers - {@link http://quamplures.net/}
17
25
 * @copyright (c)2009 by Francois PLANQUE - {@link http://fplanque.net/}
18
26
 * @copyright (c)2007 by Lee Turner - {@link http://leeturner.org/}.
19
 
 *
20
 
 * @license GNU General Public License 2 (GPL) - http://www.opensource.org/licenses/gpl-license.php
21
 
 *
22
 
 * @author Lee Turner
23
 
 * @author fplanque: Francois PLANQUE.
24
 
 *
 
27
 * 
 
28
 * @license GNU General Public License 2 (GPL) - http://www.opensource.org/licenses/gpl-license.php
 
29
 * 
 
30
 * -----------------------------------------------------------------------------
 
31
 * 
 
32
 * Next up is a version of this file found by downloading b2evolution's future
 
33
 * stuff.  Stuff that may or may not ever see a public release but guess what:
 
34
 * don't put it on the internet if you don't want someone downloading it!
 
35
 * That file actually was the basis for this file even though that file failed
 
36
 * in some very fundamental ways. The connection to twitter was not done in
 
37
 * accordance with both oauth and twitter's expectations. I fixed that because
 
38
 * I care about quality code.  Anyway that file claims 2 authors, and a GPL2
 
39
 * license.  Here, again for your entertainment, is the lines that lawyers get
 
40
 * wood over:
 
41
 * @copyright (c)2009 by Francois PLANQUE - {@link http://fplanque.net/}
 
42
 * @copyright (c)2007 by Lee Turner - {@link http://leeturner.org/}.
 
43
 * 
 
44
 * @license GNU General Public License 2 (GPL) - http://www.opensource.org/licenses/gpl-license.php
 
45
 * 
 
46
 * -----------------------------------------------------------------------------
 
47
 * 
 
48
 * Finally, we come to a file that I actually liked.  I used none of their
 
49
 * code, but most certainly drew strongly from what that author did.
 
50
 * Have you ever heard of Wordpress?  It's another open source blog app that
 
51
 * seems to be somewhat popular.  Anyway some nice folks wrote a plugin for
 
52
 * that app called tweetable
 
53
 * http://www.webmaster-source.com/tweetable-twitter-plugin-wordpress/
 
54
 * It was cool because it connected to twitter the right way, but it wasn't
 
55
 * geared towards multiple blogs and bloggers so there was only one thing I
 
56
 * could get from it.  Anyway since we're pretending licensing crap matters,
 
57
 * and noticing that their downloadable package includes ANOTHER copy of a
 
58
 * GPL license, I've included their file here as tweetable.GPL.txt.
 
59
 * Lots of bytes + no value added = pure bloat but so what! It's all about the lawyers...
 
60
 * 
 
61
 * -----------------------------------------------------------------------------
 
62
 * 
 
63
 * What, you may ask, have I done for this code?
 
64
 * 1) I made a plugin that works in Quam Plures based on bits and pieces of
 
65
 * three different open source plugins.
 
66
 * 2) I made it connect to twitter the way ouath and twitter expect (no storing
 
67
 * keys in code)
 
68
 * 3) I wrote the steps that walk the installation owner through registering
 
69
 * with twitter.
 
70
 * 4) I made it work with multiple bloggers on multiple blogs in one
 
71
 * installation.
 
72
 * 5) I made it capable of showing your twitter status in 3 locations instead
 
73
 * of just one.
 
74
 * 7) I skipped number six.
 
75
 * 8) I made the callback file recognize the different sources one might
 
76
 * authorize the registered app so it could return the blogger to the right
 
77
 * place.
 
78
 * 9) I wrote all this stupid crap.
 
79
 * 10) I wrote the songs that make the whole world sing.
 
80
 * 
 
81
 * NEW LICENSING REQUIREMENTS!
 
82
 * Given that bits and pieces of source material that have been identified above
 
83
 * are licensed under varying licensing schemes, and noting that nobody actually
 
84
 * cares about it anyway except for lawyers but I don't care about lawyers, I
 
85
 * hereby decree that this file (noting any restrictions that a normal human
 
86
 * might magically think the GPL licenses associated with the original concepts
 
87
 * that became this plugin might contain) hereby release unto the world this
 
88
 * creative work to do with as you see fit including modify, adapt, build on,
 
89
 * use as a basis for your own creative work, use to make money, or use to
 
90
 * impress cute members of the gender of your choice for the purpose of wild
 
91
 * yet emotionally unsatisfying gratuitous sex HOWEVER you must always keep this
 
92
 * license notice intact in it's entirety.
 
93
 *
 
94
 * IF you fail to keep this licence notice intact in it's entirety then I swear
 
95
 * with words yet unwritten by Gods yet unborn that I shall lay upon your seed
 
96
 * a curse for all eternity that their operating systems will reboot randomly,
 
97
 * that the porn they download is not what they thought it was after waiting
 
98
 * forever due to seeds with crappy connections, that their apps will interfere
 
99
 * with efficient texting, that no one shall read their tweets, and that they
 
100
 * shall suffer great emotional harm from these undesirable conditions.
 
101
 *
 
102
 * Will you be able to sleep at night if you bring such a strong curse upon your
 
103
 * heir's heir's heir's heads? If so then hey that's cool.  Have a nice day :)
 
104
 * 
 
105
 * I'm EdB {{http://wonderwinds.com/}} and I approve this message
 
106
 * 
25
107
 * @package plugins
26
108
 * @subpackage Twitter
27
109
 */
 
110
 
28
111
if( !defined('QP_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
29
112
 
30
 
 
31
113
/**
 
114
 * Twitter Plugin
 
115
 *
32
116
 * @package plugins
33
117
 * @subpackage Twitter
34
118
 */
35
119
class twitter_plugin extends Plugin
36
120
{
37
 
        var $author = 'Lee Turner';
38
 
        var $author_url = 'http://www.leeturner.org/';
 
121
        var $author = 'EdB';
 
122
        var $author_url = 'http://wonderwinds.com/';
39
123
        var $code = 'twitter';
40
124
        var $group = 'pingers';
 
125
        var $help_url = 'http://1912webworks.com/plugins.php';
41
126
        var $number_of_installs = 1;
42
127
        var $priority = 50;
43
128
        var $version = '0.1';
44
129
 
45
 
 
46
130
        /**
47
131
         * @see Plugin::PluginInit()
48
132
         */
49
133
        function PluginInit( & $params )
50
134
        {
51
135
                $this->name = $this->T_('Twitter');
52
 
                $this->short_desc = $this->T_('Posts to your Twitter account when you post to your blog');
53
 
                $this->long_desc = $this->T_('Posts to your Twitter account to update Twitter.com with (configurable) details of your blog post.');
 
136
                $this->short_desc = $this->T_('Tweet when you post :)');
 
137
                $this->long_desc = $this->T_('User ID#1 must first register your installation as an application. After that each user will be able to trust the application on their profile page or the write page. When a post is made it will tweet in your name whatever you set up for the message parameter. The default is $twitcerpt$, which will create an excerpt and link that total 140 characters.');
54
138
 
55
139
                $this->ping_service_name = 'twitter.com';
56
 
                $this->ping_service_note = $this->T_('Update your twitter account with details about the new post.');
 
140
                $this->ping_service_note = $this->T_('Update the blogger\'s twitter account with each new post.');
57
141
        }
58
142
 
59
143
 
60
144
        /**
61
 
         * Check if the plugin can be enabled:
62
 
         *
63
 
         * @return string|NULL
 
145
         * @see Plugin::BeforeEnable()
64
146
         */
65
147
        function BeforeEnable()
66
148
        {
67
149
 
68
 
                if( empty($this->code) )
 
150
                if( !extension_loaded( 'curl') )
69
151
                {
70
 
                        return $this->T_('The twitter plugin needs a non-empty code.');
 
152
                        return $this->T_('The twitter plugin requires curl extension.');
71
153
                }
72
154
 
73
 
                // OK:
74
155
                return true;
75
156
        }
76
157
 
77
158
 
78
159
        /**
 
160
         * @see Plugin::GetDbLayout()
 
161
         */
 
162
        function GetDbLayout()
 
163
        {
 
164
                return array(
 
165
                        "CREATE TABLE IF NOT EXISTS ".$this->get_sql_table( 'twitter' )." (
 
166
                                t_key VARCHAR(32) NOT NULL default '',
 
167
                                t_secret VARCHAR(52) NOT NULL default '',
 
168
                                t_number VARCHAR(10) NOT NULL default '',
 
169
                                PRIMARY KEY( t_key )
 
170
                        )"
 
171
                );
 
172
        }
 
173
 
 
174
 
 
175
        /**
 
176
         * @see Plugin::AdminAfterMenuInit()
 
177
         */
 
178
        function AdminAfterMenuInit()
 
179
        {
 
180
                $this->register_menu_entry( $this->T_('Twitter Keys') );
 
181
        }
 
182
 
 
183
 
 
184
        /**
 
185
         * @see Plugin::AdminTabAction()
 
186
         */
 
187
        function AdminTabAction( $params )
 
188
        {
 
189
 
 
190
                global $DB;
 
191
                global $current_User;
 
192
 
 
193
                // this is adding keys
 
194
                if( param( $this->get_class_id( 'what' ) ) == 'add' )
 
195
                { 
 
196
                        $key = param( $this->get_class_id('key') );
 
197
                        $secret = param( $this->get_class_id('secret') );
 
198
                        $number = param( $this->get_class_id('number') );
 
199
 
 
200
                        if( $key == '' || $secret == '' )
 
201
                        {
 
202
                                $this->msg( $this->T_('The "key" and "secret" fields are required!'), 'error' );
 
203
                                return;
 
204
                        }
 
205
 
 
206
                        $query = "INSERT INTO ".$this->get_sql_table('twitter')." SET t_key = '".$DB->escape( $key )."', t_secret = '".$DB->escape( $secret )."', t_number = '".$DB->escape( $number )."'";
 
207
                        if( $DB->query( $query ) )
 
208
                        {
 
209
                                $this->msg( $this->T_('Your application keys have been added to your database!'), 'success' );
 
210
                        }
 
211
                        else
 
212
                        {
 
213
                                $this->msg( $this->T_('This is bad: we tried to add the keys to your database but failed :('), 'error' );
 
214
                        }
 
215
                }
 
216
 
 
217
                // this is dropping keys
 
218
                if( param( $this->get_class_id( 'what' ) ) == 'reset' )
 
219
                {
 
220
                        $DB->query( "TRUNCATE TABLE ".$this->get_sql_table('twitter') );
 
221
                }
 
222
 
 
223
                // if the keys are stored we're okay
 
224
                $this->keys_check = false;
 
225
                $query = "SELECT * FROM ".$this->get_sql_table('twitter');
 
226
                if( $results = $DB->get_results( $query ) )
 
227
                {
 
228
                        $this->keys_check = true;
 
229
                }
 
230
 
 
231
        }
 
232
 
 
233
 
 
234
        /**
 
235
         * @see Plugin::AdminTabPayload()
 
236
         */
 
237
        function AdminTabPayload( $params )
 
238
        {
 
239
 
 
240
                global $DB;
 
241
                global $current_User;
 
242
 
 
243
                if( $this->keys_check )
 
244
                { // we have registration keys
 
245
                        $query = "SELECT * FROM ".$this->get_sql_table('twitter');
 
246
                        if( $app_data = $DB->get_row( $query, ARRAY_A ) )
 
247
                        { // get the user's twitter authentication status
 
248
                                $user_id = $current_User->ID;
 
249
                                $status = $this->get_twitter_link( $user_id, 'status' );
 
250
                                $Form = & new Form( NULL, 'twitter_keys_a', 'post', 'compact' );
 
251
                                $Form->begin_form( 'fform', $this->T_('Have you authorized this app to tweet in your name, or do you want/need to?') );
 
252
                                $Form->hidden_ctrl();
 
253
                                $Form->hiddens_by_key( get_memorized() );
 
254
                                $Form->begin_fieldset( '' );
 
255
                                $Form->info_field( 'Your twitter status', $status );
 
256
                                $Form->end_fieldset( 'foo' );
 
257
                                $Form->end_form();
 
258
 
 
259
                                if( $current_User->ID == '1' )
 
260
                                { // user ID#1 can drop the keys if desired, and gets a link to the app details page
 
261
                                        $Form = & new Form( NULL, 'twitter_keys_b', 'post', 'compact' );
 
262
                                        $Form->begin_form( 'fform', $this->T_('Application Info') );
 
263
                                        $Form->hidden_ctrl();
 
264
                                        $Form->hiddens_by_key( get_memorized() );
 
265
                                        $Form->begin_fieldset( '' );
 
266
                                        $Form->info_field( 'opens new window', '<a href="http://dev.twitter.com/apps/'.$app_data['t_number'].'" target="_blank">'.$this->T_('Application Info (link launches new window)').'</a>' );
 
267
                                        $Form->end_fieldset( 'foo' );
 
268
                                        $Form->end_form();
 
269
 
 
270
                                        $Form = & new Form( NULL, 'twitter_keys_c', 'post', 'compact' );
 
271
                                        $Form->begin_form( 'fform', $this->T_('Drop Application Keys') );
 
272
                                        $Form->hidden_ctrl();
 
273
                                        $Form->hiddens_by_key( get_memorized() );
 
274
                                        $Form->hidden( $this->get_class_id().'_what', 'reset' );
 
275
                                        $Form->info_field( 'Warning', 'If you do this all of your bloggers will have to authenticate again.' );
 
276
                                        $Form->button_input( array( 'value' => $this->T_('Wipe out my keys so I can do it again (WARNING: THIS CAN NOT BE UNDONE!)') ) );
 
277
                                        $Form->end_form();
 
278
 
 
279
                                }
 
280
 
 
281
                        }
 
282
 
 
283
                }
 
284
                elseif( $current_User->ID == '1' )
 
285
                { // no keys so walk through adding them
 
286
                        global $basedomain;
 
287
                        global $basesubpath;
 
288
                        global $app_baseurl;
 
289
                        global $Settings;
 
290
                        global $BlogCache;
 
291
 
 
292
                        $default_blog_on_index = $Settings->get('default_blog_ID');
 
293
                        $default_Blog = & $BlogCache->get_by_ID( $default_blog_on_index, false );
 
294
                        $callback = $this->get_plugin_url( true ).'_callback.php';
 
295
 
 
296
                        echo '<p>'.$this->T_('Twitter uses the OAuth protocol to authenticate and access Twitter accounts.').' '
 
297
                                .$this->T_('That means you have to register your blog as an application with Twitter.').' '
 
298
                                .$this->T_('Why? <strong>Because twitter says so</strong>. The link below will open a new window, but first...').'</p>';
 
299
 
 
300
                        echo '<h3>'.$this->T_('...some things to know before you register:').'</h3>';
 
301
                        echo '<ol style="list-style:decimal; margin: 0 1ex 1ex 2ex;line-height:1.3em;">';
 
302
                        echo '<li>'.$this->T_('<strong>Application Icon</strong> is not required and will be shown to your bloggers when they decide to trust your app or not.').'</li>';
 
303
                        echo '<li>'.$this->T_('<strong>Application Name</strong> (<em class="red">required</em>) must be "unique to twitter". Maybe your base URL minus the http part and trailing slash?');
 
304
                        echo '<br /><code style="font-size:1.2em;background-color:white;margin-left:4ex;padding:2px;">'.substr( $basedomain.$basesubpath, 0, -1 ).'</code></li>';
 
305
                        echo '<li>'.$this->T_('<strong>Application Description</strong> (<em class="red">required</em>). Maybe the tagline or short description from your primary blog?');
 
306
                        echo '<ul style="margin: 0 1ex 1ex 2ex;line-height:1.3em;">';
 
307
                        echo '<li><strong>'.$this->T_('TAGLINE').':</strong><code style="font-size:1.2em;background-color:white;margin-left:1ex;padding:2px;">'.$default_Blog->get( 'tagline' ).'</code></li>';
 
308
                        echo '<li><strong>'.$this->T_('SHORT DESCRIPTION').':</strong><code style="font-size:1.2em;background-color:white;margin-left:1ex;padding:2px;">'.$default_Blog->get( 'description' ).'</code></li>';
 
309
                        echo '</ul></li>';
 
310
                        echo '<li>'.$this->T_('<strong>Application Website</strong> (<em class="red">required</em>) should be the same as your $app_baseurl value:');
 
311
                        echo '<br /><code style="font-size:1.2em;background-color:white;margin-left:4ex;padding:2px;">'.$app_baseurl.'</code></li>';
 
312
                        echo '<li>'.$this->T_('<strong>Organization</strong> is not required but should be because they assume it exists. Your bloggers will be asked to trust "application name by organization". Maybe your preferred name? Or a business name?</li>');
 
313
                        echo '<li>'.$this->T_('<strong>Website</strong> is not required and hey didn\'t we just do this in step 4?');
 
314
                        echo '<br /><code style="font-size:1.2em;background-color:white;margin-left:4ex;padding:2px;">'.$app_baseurl.'</code></li>';
 
315
                        echo '<li>'.$this->T_('<strong>Application Type</strong> should be and needs to be <strong>Browser.</strong></li>');
 
316
                        echo '<li>'.$this->T_('<strong>Callback URL</strong> is where twitter will come back to after one of your bloggers posts (and tweets) something.');
 
317
                        echo '<br /><code style="font-size:1.2em;background-color:white;margin-left:4ex;padding:2px;">'.$callback.'</code></li>';
 
318
                        echo '<li>'.$this->T_('<strong>Default Access type</strong> needs to be <strong>Read &amp; Write.</strong> but won\'t be so make sure you set it correctly.</li>');
 
319
                        echo '<li>'.$this->T_('Do their stupid captcha thing, press the "Save" button, then you can copy/paste some info back to this form.</li>');
 
320
                        echo '</ol>';
 
321
 
 
322
                        echo '<h4 style="text-align:center"><a href="http://twitter.com/oauth_clients/new" target="_blank">[_Register your installation as a new Application_]</a></h4>';
 
323
 
 
324
                        $Form = & new Form( NULL, 'twitter_keys', 'post', 'compact' );
 
325
                        $Form->begin_form( 'fform', $this->T_('Add twitter keys') );
 
326
                        $Form->hidden_ctrl();
 
327
                        $Form->hiddens_by_key( get_memorized() );
 
328
                        $Form->hidden( $this->get_class_id().'_what', 'add' );
 
329
                        $Form->text_input( $this->get_class_id().'_key', '', '32', $this->T_('Consumer key'), $this->T_('<em class="red">required</em>: copy/paste from twitter'), array( 'maxlength' => '32' ) );
 
330
                        $Form->text_input( $this->get_class_id().'_secret', '', '52', $this->T_('Consumer secret'), $this->T_('<em class="red">required</em>: copy/paste from twitter'), array( 'maxlength' => '52' ) );
 
331
                        $Form->text_input( $this->get_class_id().'_number', '', '52', $this->T_('Application ID#'), $this->T_('<em class="green">optional</em>: find this in the URL if registration is successful'), array( 'maxlength' => '52' ) );
 
332
                        $Form->button_input( array( 'value' => $this->T_('Roll them bones') ) );
 
333
                        $Form->end_form();
 
334
 
 
335
                }
 
336
                else
 
337
                { // other users get nothing
 
338
                        return;
 
339
                }
 
340
 
 
341
        }
 
342
 
 
343
 
 
344
        /**
 
345
         * @see Plugin::GetDefaultSettings()
 
346
         */
 
347
        function GetDefaultSettings( & $params )
 
348
        {
 
349
                global $DB;
 
350
                // if the keys are stored we don't need settings
 
351
                $query = "SELECT * FROM ".$this->get_sql_table('twitter');
 
352
                if( $results = $DB->get_results( $query ) )
 
353
                {
 
354
                        return;
 
355
                }
 
356
 
 
357
                $default_settings = array(
 
358
                        'twitter_contact' => array(
 
359
                                'label' => $this->T_('foo'),
 
360
                                'type' => 'info',
 
361
                                'info' => $this->T_('1) Hit the "Tools -> Twitter Keys" page first to register your installation.<br />2) Each blogger will have to approve this application on their profile page.'),
 
362
                        ),
 
363
                );
 
364
                return $default_settings;
 
365
        }
 
366
 
 
367
 
 
368
        /**
 
369
         * @see Plugin::GetDefaultUserSettings()
 
370
         */
 
371
        function GetDefaultUserSettings( & $params )
 
372
        {
 
373
                global $current_User;
 
374
 
 
375
                $user_id = 0;
 
376
                $info = NULL;
 
377
                if( is_logged_in() )
 
378
                {
 
379
                        $user_id = $current_User->ID;
 
380
                }
 
381
                if( $user_id )
 
382
                { // initialize info only once, when needs to display the link (user_id is set)
 
383
                        $info = $this->get_twitter_link( $user_id );
 
384
                        $user_settings = array(
 
385
                                'twitter_contact' => array(
 
386
                                        'label' => $this->T_('Twitter account status'),
 
387
                                        'info' => $info,
 
388
                                        'type' => 'info',
 
389
                                ),
 
390
                                'twitter_msg_format' => array(
 
391
                                        'label' => $this->T_('Message format'),
 
392
                                        'type' => 'text',
 
393
                                        'size' => 30,
 
394
                                        'maxlength' => 140,
 
395
                                        'defaultvalue' => $this->T_('$twitcerpt$'),
 
396
                                        'note' => $this->T_('$twitcerpt$ is an excerpt + URL that totals 140 characters'),
 
397
                                ),
 
398
                        );
 
399
                        return $user_settings;
 
400
                }
 
401
        }
 
402
 
 
403
 
 
404
        /**
79
405
         * @see Plugin::ItemSendPing()
80
406
         */
81
407
        function ItemSendPing( & $params )
82
408
        {
83
 
    /**
84
 
                 * @var Blog
85
 
                 */
86
 
                $item_Blog = $params['Item']->get_Blog();
87
 
 
88
 
                // Try to get twitter account for Blog:
89
 
                $username = $this->get_coll_setting( 'twitter_username', $item_Blog );
90
 
                $password = $this->get_coll_setting( 'twitter_password', $item_Blog );
91
 
                if( empty($username) || empty($password) )
92
 
                { // Not found, fallback to Trying to get twitter account for User:
93
 
                        $username = $this->UserSettings->get( 'twitter_username' );
94
 
                        $password = $this->UserSettings->get( 'twitter_password' );
95
 
                        if( empty($username) || empty($password) )
96
 
                        {       // Still no twitter account found:
97
 
                                $params['xmlrpcresp'] = $this->T_('You must configure a twitter username/password before you can post to twitter.');
98
 
                                return false;
99
 
                        }
100
 
                        else
101
 
                                {       // Get additional params from User Setttings:
102
 
                                $msg = $this->UserSettings->get( 'twitter_msg_format' );
103
 
                        }
 
409
                global $DB;
 
410
                // if the keys are not stored we get out
 
411
                $query = "SELECT * FROM ".$this->get_sql_table('twitter');
 
412
                if( ! $results = $DB->get_results( $query ) )
 
413
                {
 
414
                        return false;
 
415
                }
 
416
 
 
417
                // get the keys
 
418
                $query = "SELECT * FROM ".$this->get_sql_table('twitter');
 
419
                if( $app_data = $DB->get_row( $query, ARRAY_A ) )
 
420
                {
 
421
                        $consumer_key = $app_data['t_key'];
 
422
                        $consumer_secret = $app_data['t_secret'];
 
423
                }
 
424
 
 
425
                // get twitter account info
 
426
                $oauth_token = $this->UserSettings->get( 'twitter_token' );
 
427
                $oauth_token_secret = $this->UserSettings->get( 'twitter_secret' );
 
428
                if( empty($oauth_token) || empty($oauth_token_secret) )
 
429
                { // no twitter account :(
 
430
                        $params['xmlrpcresp'] = $this->T_('You must configure a twitter username/password before you can post to twitter.');
 
431
                        return false;
104
432
                }
105
433
                else
106
 
                {       // Get additional params from Blog Setttings:
107
 
                        $msg = $this->get_coll_setting( 'twitter_msg_format', $item_Blog );
 
434
                { // get the message format
 
435
                        $msg = $this->UserSettings->get( 'twitter_msg_format' );
108
436
                }
109
437
 
 
438
                // converitate the $message$ bits
110
439
                $title =  $params['Item']->dget('title', 'xml');
111
440
                $excerpt =  $params['Item']->dget('excerpt', 'xml');
112
441
                $url = $params['Item']->get_permanent_url();
 
442
                $short_url = $params['Item']->Blog->gen_blogurl().'?p='.$params['Item']->ID;
 
443
                $clip_to = 140 - ( evo_strlen( $short_url ) + 4 );
 
444
                $twitcerpt = trim( evo_substr( $excerpt, 0, $clip_to ) ).'... '.$short_url;
113
445
 
114
446
                $msg = str_replace( '$title$', $title, $msg );
115
447
                $msg = str_replace( '$excerpt$', $excerpt, $msg );
116
448
                $msg = str_replace( '$url$', $url, $msg );
117
 
 
118
 
                if( extension_loaded( 'curl' ) )
119
 
                { // CURL available
120
 
                        $session = curl_init();
121
 
                        curl_setopt( $session, CURLOPT_URL, 'http://twitter.com/statuses/update.xml' );
122
 
                        curl_setopt( $session, CURLOPT_POSTFIELDS, 'status='.urlencode($msg));
123
 
                        curl_setopt( $session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
124
 
                        curl_setopt( $session, CURLOPT_HEADER, false );
125
 
                        curl_setopt( $session, CURLOPT_CONNECTTIMEOUT, 5);
126
 
                        curl_setopt( $session, CURLOPT_USERPWD, $username.':'.$password );
127
 
                        curl_setopt( $session, CURLOPT_RETURNTRANSFER, 1 );
128
 
                        curl_setopt( $session, CURLOPT_POST, 1);
129
 
                        $result = curl_exec ( $session ); // will be an XML message
130
 
                        curl_close( $session );
131
 
                }
132
 
                else
133
 
                { // fallback to fsockopen
134
 
                        $host = 'twitter.com';
135
 
                        $url = '/statuses/update.xml?status='.urlencode( $msg );
136
 
                        // Build the header
137
 
                        $header  = 'POST '.$url.' HTTP/1.0'."\r\n";
138
 
                        $header .= 'Host: '.$host."\r\n";
139
 
                        $header .= 'Authorization: Basic '.base64_encode( $username.':'.$password )."\r\n";
140
 
                        $header .= 'Connection: Close'."\r\n\r\n";
141
 
                        if( $fp = fsockopen($host, 80) )
142
 
                        {
143
 
                                fputs($fp, $header );
144
 
                                $result = '';
145
 
                                while( !feof( $fp ) )
146
 
                                {
147
 
                                        $result .= fgets( $fp, 1024 );
148
 
                                }
149
 
                                fclose($fp);
150
 
                        }
151
 
                        else
152
 
                        { // unable to tweet
153
 
                                $params['xmlrpcresp'] = $this->T_('No ping method available, please contact your host about using CURL or fsockopen');
154
 
                        }
155
 
                }
 
449
                $msg = str_replace( '$twitcerpt$', $twitcerpt, $msg );
 
450
 
 
451
                require_once 'twitteroauth/twitteroauth.php';
 
452
                $connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret );
 
453
 
 
454
                $result = $connection->post('statuses/update', array( 'status' => $msg ));
156
455
 
157
456
                if( empty($result) )
158
457
                {
159
458
                        return false;
160
459
                }
161
 
                elseif( preg_match( '�<error>(.*)</error>�', $result, $matches ) )
162
 
                {
163
 
                        $params['xmlrpcresp'] = $matches[1];
164
 
                        return false;
165
 
                }
166
 
 
167
 
                $params['xmlrpcresp'] = $this->T_('Posted to account: @').$username;
 
460
 
 
461
                $account = $connection->get('account/verify_credentials');
 
462
 
 
463
                $params['xmlrpcresp'] = $this->T_('Posted to account: @').$account->screen_name;
 
464
 
168
465
                return true;
169
466
        }
170
467
 
171
468
 
172
469
        /**
173
 
         * @see Plugin::GetDefaultUserSettings()
 
470
         * @see Plugin::AdminDisplayFieldsetSidebar()
174
471
         */
175
 
        function GetDefaultUserSettings( & $params )
 
472
        function AdminDisplayFieldsetSidebar( & $params )
176
473
        {
177
 
                return array(
178
 
                                'twitter_username' => array(
179
 
                                        'label' => $this->T_('Twitter username'),
180
 
                                        'type' => 'text',
181
 
                                ),
182
 
                                'twitter_password' => array(
183
 
                                        'label' => $this->T_('Twitter password'),
184
 
                                        'type' => 'password',
185
 
                                ),
186
 
                                'twitter_msg_format' => array(
187
 
                                        'label' => $this->T_('Message format'),
188
 
                                        'type' => 'text',
189
 
                                        'size' => 30,
190
 
                                        'maxlength' => 140,
191
 
                                        'defaultvalue' => $this->T_('Just posted $title$ $url$ #b2p'),
192
 
                                        'note' => $this->T_('$title$, $excerpt$ and $url$ will be replaced appropriately.'),
193
 
                                ),
194
 
                        );
 
474
                // use cat_ID to get blog_ID to get pingers...
 
475
                global $DB;
 
476
                $main_cat_ID = $params['Item']->main_cat_ID;
 
477
                $query = "SELECT cat_blog_ID FROM T_categories WHERE cat_ID = '{$main_cat_ID}'";
 
478
                $this_blog_id = $DB->get_var( $query );
 
479
                $query = "SELECT cset_value FROM T_coll_settings WHERE cset_coll_ID ='{$this_blog_id}' AND cset_name = 'ping_plugins'";
 
480
                $ping_string = $DB->get_var( $query );
 
481
                $ping_plugins = array_unique( explode( ',', $ping_string ) );
 
482
 
 
483
                // get out if this blog doesn't have this pinger
 
484
                if( ! in_array( $this->code, $ping_plugins ) )
 
485
                {
 
486
                        return;
 
487
                }
 
488
 
 
489
                // get the user's twitter authentication status
 
490
                global $current_User;
 
491
                $user_id = $current_User->ID;
 
492
                $status = $this->get_twitter_link( $user_id, 'status' );
 
493
 
 
494
                $params['Form']->begin_fieldset( $this->T_('twitter status') );
 
495
                $params['Form']->info_field( '', $status );
 
496
                $params['Form']->end_fieldset( 'foo' );
 
497
 
195
498
        }
196
499
 
197
500
 
198
501
        /**
199
 
         * Define here default collection/blog settings that are to be made available in the backoffice.
200
 
         *
201
 
         * @todo (legacy): ideally we'd want a warning if the twitter ping is not enabled
202
 
         *
203
 
         * @return array See {@link Plugin::GetDefaultSettings()}.
 
502
         * Get link to twitter oAuth
204
503
         */
205
 
        function get_coll_setting_definitions( & $params )
 
504
        function get_twitter_link( $user_id, $give = 'info' )
206
505
        {
207
 
                return array(
208
 
                                'twitter_username' => array(
209
 
                                        'label' => $this->T_('Twitter username'),
210
 
                                        'type' => 'text',
211
 
                                ),
212
 
                                'twitter_password' => array(
213
 
                                        'label' => $this->T_('Twitter password'),
214
 
                                        'type' => 'password',
215
 
                                ),
216
 
                                'twitter_msg_format' => array(
217
 
                                        'label' => $this->T_('Message format'),
218
 
                                        'type' => 'text',
219
 
                                        'size' => 30,
220
 
                                        'maxlength' => 140,
221
 
                                        'defaultvalue' => $this->T_('Just posted $title$ $url$ #b2p'),
222
 
                                        'note' => $this->T_('$title$, $excerpt$ and $url$ will be replaced appropriately.'),
223
 
                                ),
224
 
                        );
 
506
                global $DB;
 
507
                // if the keys are not stored we get out
 
508
                $query = "SELECT * FROM ".$this->get_sql_table('twitter');
 
509
                if( ! $results = $DB->get_results( $query ) )
 
510
                {
 
511
                        if( $give == 'info' )
 
512
                        {
 
513
                                return $this->T_('This installation has not registered as an application with twitter yet.<br />Tell the admin to get off his/her lazy ass and register so you can tweet when you post.');
 
514
                        }
 
515
                        elseif( $give == 'status' )
 
516
                        {
 
517
                                return $this->T_('This installation is not registered!');
 
518
                        }
 
519
                }
 
520
 
 
521
                // get the keys
 
522
                $query = "SELECT * FROM ".$this->get_sql_table('twitter');
 
523
                if( $app_data = $DB->get_row( $query, ARRAY_A ) )
 
524
                {
 
525
                        $consumer_key = $app_data['t_key'];
 
526
                        $consumer_secret = $app_data['t_secret'];
 
527
                }
 
528
 
 
529
                require_once 'twitteroauth/twitteroauth.php';
 
530
                global $BlogCache;
 
531
 
 
532
                // get and set UserSettings
 
533
                if( empty ( $this->UserSettings ) )
 
534
                {
 
535
                        if( $give == 'info' )
 
536
                        {
 
537
                                return NULL;
 
538
                        }
 
539
                }
 
540
 
 
541
                $oauth_token = $this->UserSettings->get( 'twitter_token', $user_id );
 
542
                if( !empty( $oauth_token ) )
 
543
                { // user has already approved app, get token secret
 
544
                        $oauth_token_secret = $this->UserSettings->get( 'twitter_secret', $user_id );
 
545
                        $connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret );
 
546
                        // get linked user account
 
547
                        $account = $connection->get('account/verify_credentials');
 
548
 
 
549
                        // if they turn off approval via twitter forget everything
 
550
                        if( isset( $account->error ) )
 
551
                        {
 
552
                                global $Session;
 
553
                                $Session->delete( 'oauth_token' );
 
554
                                $Session->delete( 'oauth_token_secret' );
 
555
                                $Session->dbsave();
 
556
                        }
 
557
                        else
 
558
                        {
 
559
                                $result = $this->T_('Linked to').': @'.$account->screen_name;
 
560
                        }
 
561
 
 
562
                }
 
563
 
 
564
                // create new connection
 
565
                $connection = new TwitterOAuth($consumer_key, $consumer_secret);
 
566
 
 
567
                // set callback params
 
568
                $callback = $this->get_plugin_url( true ).'_callback.php';
 
569
 
 
570
                $req_token = $connection->getRequestToken( $callback );
 
571
 
 
572
                $token = $req_token['oauth_token'];
 
573
 
 
574
                /* Save temporary credentials to session. */
 
575
                global $Session;
 
576
                $Session->delete( 'oauth_token' );
 
577
                $Session->delete( 'oauth_token_secret' );
 
578
                $Session->set( 'user_id', $user_id );
 
579
                $Session->set( 'plugin_id', $this->ID );
 
580
                $Session->set( 'oauth_token', $req_token['oauth_token'] );
 
581
                $Session->set( 'oauth_token_secret', $req_token['oauth_token_secret'] );
 
582
                $Session->set( 'consumer_key', $consumer_key );
 
583
                $Session->set( 'consumer_secret', $consumer_secret );
 
584
 
 
585
                // info so that we can return to the write page
 
586
                $redir = 'foo';
 
587
                if( $give == 'status' )
 
588
                {
 
589
                        $this_action = isset($_GET['action']) ? $_GET['action'] : '';
 
590
                        if( $this_action == 'edit' )
 
591
                        {
 
592
                                $redir = 'ctrl=items&action=edit&p='.$_GET['p'];
 
593
                        }
 
594
                        elseif( $this_action == 'new' )
 
595
                        {
 
596
                                $redir = 'ctrl=items&action=new&blog='.$_GET['blog'];
 
597
                        }
 
598
                }
 
599
 
 
600
                $Session->set( 'redir', $redir );
 
601
 
 
602
                $Session->dbsave();
 
603
 
 
604
                if( empty( $result ) )
 
605
                { // wasn't linked to twitter
 
606
                        $result = '<a href="'.$connection->getAuthorizeURL( $req_token, false ).'" title="'.$this->T_('sign in with twitter').'"><img src="'.$this->get_plugin_url( true ).'twitter_button.png" width="151" height="24" alt="'.T_('sign in with twitter').'" /></a>';
 
607
                }
 
608
                else
 
609
                { // was linked so show it with an option to switch on user profile page
 
610
                        if( $give == 'info' )
 
611
                        {
 
612
                                $result = $result.' <a href='.$connection->getAuthorizeURL( $req_token, false ).'>'.$this->T_('Link to another account').'</a>';
 
613
                        }
 
614
                }
 
615
 
 
616
                return $result;
225
617
        }
226
618
 
227
619
}