]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Sample/SamplePlugin.php
Convert SamplePlugin to new-style table defs, tweak some stuff to test basic checkschema
[quix0rs-gnu-social.git] / plugins / Sample / SamplePlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009, StatusNet, Inc.
5  *
6  * A sample module to show best practices for StatusNet plugins
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  Sample
24  * @package   StatusNet
25  * @author    Brion Vibber <brionv@status.net>
26  * @author    Evan Prodromou <evan@status.net>
27  * @copyright 2009 StatusNet, Inc.
28  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
29  * @link      http://status.net/
30  */
31
32 if (!defined('STATUSNET')) {
33     // This check helps protect against security problems;
34     // your code file can't be executed directly from the web.
35     exit(1);
36 }
37
38 /**
39  * Sample plugin main class
40  *
41  * Each plugin requires a main class to interact with the StatusNet system.
42  *
43  * The main class usually extends the Plugin class that comes with StatusNet.
44  *
45  * The class has standard-named methods that will be called when certain events
46  * happen in the code base. These methods have names like 'onX' where X is an
47  * event name (see EVENTS.txt for the list of available events). Event handlers
48  * have pre-defined arguments, based on which event they're handling. A typical
49  * event handler:
50  *
51  *    function onSomeEvent($paramA, &$paramB)
52  *    {
53  *        if ($paramA == 'jed') {
54  *            throw new Exception(sprintf(_m("Invalid parameter %s"), $paramA));
55  *        }
56  *        $paramB = 'spock';
57  *        return true;
58  *    }
59  *
60  * Event handlers must return a boolean value. If they return false, all other
61  * event handlers for this event (in other plugins) will be skipped, and in some
62  * cases the default processing for that event would be skipped. This is great for
63  * replacing the default action of an event.
64  *
65  * If the handler returns true, processing of other event handlers and the default
66  * processing will continue. This is great for extending existing functionality.
67  *
68  * If the handler throws an exception, processing will stop, and the exception's
69  * error will be shown to the user.
70  *
71  * To install a plugin (like this one), site admins add the following code to
72  * their config.php file:
73  *
74  *     addPlugin('Sample');
75  *
76  * Plugins must be installed in one of the following directories:
77  *
78  *     local/plugins/{$pluginclass}.php
79  *     local/plugins/{$name}/{$pluginclass}.php
80  *     local/{$pluginclass}.php
81  *     local/{$name}/{$pluginclass}.php
82  *     plugins/{$pluginclass}.php
83  *     plugins/{$name}/{$pluginclass}.php
84  *
85  * Here, {$name} is the name of the plugin, like 'Sample', and {$pluginclass} is
86  * the name of the main class, like 'SamplePlugin'. Plugins that are part of the
87  * main StatusNet distribution go in 'plugins' and third-party or local ones go
88  * in 'local'.
89  *
90  * Simple plugins can be implemented as a single module. Others are more complex
91  * and require additional modules; these should use their own directory, like
92  * 'local/plugins/{$name}/'. All files related to the plugin, including images,
93  * JavaScript, CSS, external libraries or PHP modules should go in the plugin
94  * directory.
95  *
96  * @category  Sample
97  * @package   StatusNet
98  * @author    Brion Vibber <brionv@status.net>
99  * @author    Evan Prodromou <evan@status.net>
100  * @copyright 2009 StatusNet, Inc.
101  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
102  * @link      http://status.net/
103  */
104 class SamplePlugin extends Plugin
105 {
106     /**
107      * Plugins are configured using public instance attributes. To set
108      * their values, site administrators use this syntax:
109      *
110      * addPlugin('Sample', array('attr1' => 'foo', 'attr2' => 'bar'));
111      *
112      * The same plugin class can be initialized multiple times with different
113      * arguments:
114      *
115      * addPlugin('EmailNotify', array('sendTo' => 'evan@status.net'));
116      * addPlugin('EmailNotify', array('sendTo' => 'brionv@status.net'));
117      *
118      */
119
120     public $attr1 = null;
121     public $attr2 = null;
122
123     /**
124      * Initializer for this plugin
125      *
126      * Plugins overload this method to do any initialization they need,
127      * like connecting to remote servers or creating paths or so on.
128      *
129      * @return boolean hook value; true means continue processing, false means stop.
130      */
131     function initialize()
132     {
133         return true;
134     }
135
136     /**
137      * Cleanup for this plugin
138      *
139      * Plugins overload this method to do any cleanup they need,
140      * like disconnecting from remote servers or deleting temp files or so on.
141      *
142      * @return boolean hook value; true means continue processing, false means stop.
143      */
144     function cleanup()
145     {
146         return true;
147     }
148
149     /**
150      * Database schema setup
151      *
152      * Plugins can add their own tables to the StatusNet database. Plugins
153      * should use StatusNet's schema interface to add or delete tables. The
154      * ensureTable() method provides an easy way to ensure a table's structure
155      * and availability.
156      *
157      * By default, the schema is checked every time StatusNet is run (say, when
158      * a Web page is hit). Admins can configure their systems to only check the
159      * schema when the checkschema.php script is run, greatly improving performance.
160      * However, they need to remember to run that script after installing or
161      * upgrading a plugin!
162      *
163      * @see Schema
164      * @see ColumnDef
165      *
166      * @return boolean hook value; true means continue processing, false means stop.
167      */
168     function onCheckSchema()
169     {
170         $schema = Schema::get();
171
172         // For storing user-submitted flags on profiles
173
174         $schema->ensureTable('user_greeting_count',
175             array(
176                 'fields' => array(
177                     'user_id' => array('type' => 'int', 'not null' => true),
178                     'greeting_count' => array('type' => 'int'),
179                 ),
180                 'primary key' => array('user_id'),
181                 'foreign keys' => array(
182                     // Not all databases will support foreign keys, but even
183                     // when not enforced it's helpful to include these definitions
184                     // as documentation.
185                     'user_greeting_count_user_id_fkey' => array('user', array('user_id' => 'id')),
186                 ),
187             )
188         );
189
190         return true;
191     }
192
193     /**
194      * Load related modules when needed
195      *
196      * Most non-trivial plugins will require extra modules to do their work. Typically
197      * these include data classes, action classes, widget classes, or external libraries.
198      *
199      * This method receives a class name and loads the PHP file related to that class. By
200      * tradition, action classes typically have files named for the action, all lower-case.
201      * Data classes are in files with the data class name, initial letter capitalized.
202      *
203      * Note that this method will be called for *all* overloaded classes, not just ones
204      * in this plugin! So, make sure to return true by default to let other plugins, and
205      * the core code, get a chance.
206      *
207      * @param string $cls Name of the class to be loaded
208      *
209      * @return boolean hook value; true means continue processing, false means stop.
210      */
211     function onAutoload($cls)
212     {
213         $dir = dirname(__FILE__);
214
215         switch ($cls)
216         {
217         case 'HelloAction':
218             include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
219             return false;
220         case 'User_greeting_count':
221             include_once $dir . '/'.$cls.'.php';
222             return false;
223         default:
224             return true;
225         }
226     }
227
228     /**
229      * Map URLs to actions
230      *
231      * This event handler lets the plugin map URLs on the site to actions (and
232      * thus an action handler class). Note that the action handler class for an
233      * action will be named 'FoobarAction', where action = 'foobar'. The class
234      * must be loaded in the onAutoload() method.
235      *
236      * @param Net_URL_Mapper $m path-to-action mapper
237      *
238      * @return boolean hook value; true means continue processing, false means stop.
239      */
240     function onRouterInitialized($m)
241     {
242         $m->connect('main/hello',
243                     array('action' => 'hello'));
244         return true;
245     }
246
247     /**
248      * Modify the default menu to link to our custom action
249      *
250      * Using event handlers, it's possible to modify the default UI for pages
251      * almost without limit. In this method, we add a menu item to the default
252      * primary menu for the interface to link to our action.
253      *
254      * The Action class provides a rich set of events to hook, as well as output
255      * methods.
256      *
257      * @param Action $action The current action handler. Use this to
258      *                       do any output.
259      *
260      * @return boolean hook value; true means continue processing, false means stop.
261      *
262      * @see Action
263      */
264     function onEndPrimaryNav($action)
265     {
266         // common_local_url() gets the correct URL for the action name
267         // we provide
268
269         $action->menuItem(common_local_url('hello'),
270                           _m('Hello'), _m('A warm greeting'), false, 'nav_hello');
271         return true;
272     }
273
274     function onPluginVersion(&$versions)
275     {
276         $versions[] = array('name' => 'Sample',
277                             'version' => STATUSNET_VERSION,
278                             'author' => 'Brion Vibber, Evan Prodromou',
279                             'homepage' => 'http://status.net/wiki/Plugin:Sample',
280                             'rawdescription' =>
281                             _m('A sample plugin to show basics of development for new hackers.'));
282         return true;
283     }
284 }