Usermeta: usermeta.php

File usermeta.php, 12.6 KB (added by squish, 6 years ago)

Usermeta 0.4

Line 
1<?php
2/*
3Plugin Name: Usermeta
4Plugin URI: http://dev.wp-plugins.org/wiki/Usermeta
5Description: Adds user meta tables and API
6Author: James Ponder
7Version: 0.4
8Author URI: http://www.squish.net/
9*/
10
11/*
12
13=== Usermeta ===
14Tags: profiles, users, acl, categories
15
16== What does this plug-in do? ==
17
18This plug-in adds an API for WordPress 1.5, or provides an alternative API
19for WP 2.0 so that other plug-ins can associate arbitrary meta information
20to users very easily.
21
22== Installation ==
23
241. Upload to your plugins folder, usually wp-content/plugins/
252. Activate the plugin on the plugin screen
263. Click "Create/Update usermeta tables" in Options -> Usermeta
27
28== Examples ==
29
30  === Get the Usermeta object ===
31 
32      $usermeta = get_usermeta_object();
33
34  === Associate something with a user ===
35
36      $usermeta->set($user_id, "myplugin_thingy", "myvalue");
37
38 === Get the value for the author of a post (in the Loop) ===
39
40      $val = $usermeta->get(get_the_author_ID(), "myplugin_thingy", true);
41      if (is_null($val)) {
42        do default action when no meta data
43      } else {
44        echo $val
45      }
46
47  === Adding more info to a post... ===
48
49      <p>This post written by <?php the_author(); ?> who lives at
50      <?php $usermeta = new Usermeta();
51        echo $usermeta->get(get_the_author_ID(), "address", true); ?></p>
52
53  === Add a few bits of information to the current user ===
54
55      global $user_ID;
56      get_currentuserinfo();
57      $usermeta->add($user_ID, "myplugin_listofthings", "myval_1");
58      $usermeta->add($user_ID, "myplugin_listofthings", "myval_2");
59      $usermeta->add($user_ID, "myplugin_listofthings", "myval_3");
60
61== API ==
62
63  $bool = $usermeta->database_exists()
64
65    Check to see if our tables exist, returns true if so
66
67  $out = $usermeta->ensure_database()
68
69    Ensure that the usermeta table has been created.  Returns an array
70    of messages of actions taken, if any.  (Comes from Wordpress' dbDelta
71    function.)
72
73  $bool = $usermeta->add($user_id, $key, $value)
74  $bool = $usermeta->add($user_id, $key, $value, $unique)
75
76    Adds in the given value for this user/key when unique is false (or not
77    passed in).  If unique is true, a check is made to see if the user/key
78    already exists and if it does, no new entry is added.  If anything was
79    added true is returned, false otherwise.
80
81  $bool = $usermeta->delete($user_id, $key)
82  $bool = $usermeta->delete($user_id, $key, $value)
83
84    If no value is given, deletes all values for the given user/key.  If a
85    value is given, only tries to delete that value.  If anything was
86    deleted, returns true.
87
88  $bool = $usermeta->get($user_id, $key, $single)
89
90    If single is false, returns an array of all values for this user/key,
91    however if single is true, returns the first found entry for this
92    user/key or NULL if there are none.
93
94  $bool = $usermeta->set($user_id, $key, $value)
95
96    Sets all occurances of user_id/key to the given value.  If no such
97    user_id/key exists, a new entry is added. Always true on success.
98
99  $bool = $usermeta->update($user_id, $key, $value)
100  $bool = $usermeta->update($user_id, $key, $value, $prev_value)
101
102    Updates all occurances of this user/key with the new value.  If optional
103    fourth param is passed in, then only matches with that value are changed.
104    Returns true if any items were changed, false otherwise.
105
106== License ==
107
108Copyright (c) 2005, 2006 James Ponder <james@squish.net>
109
110Permission to use, copy, modify, and distribute this software for any
111purpose with or without fee is hereby granted, provided that the above
112copyright notice and this permission notice appear in all copies.
113
114THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
115WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
116MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
117ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
118WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
119ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
120OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
121
122== Upgrading from WordPress 1.5 to 2.0 ===
123
124If you used Usermeta 0.1 or 0.2 you must run this before you upgrade to
125WP 2.0:
126
127  ALTER TABLE wp_usermeta CHANGE meta_id umeta_id bigint(20)
128    NOT NULL auto_increment
129
130You do not need to do this with Usermeta 0.3 which is compatible with both
131versions.
132
133=== Failed upgrades to WP 2.0 ===
134
135Unfortunately due to some interaction between WP 2.0 and the tables which
136were used up in Usermeta 0.1 if you upgrade to WP 2.0 having used an old
137version of Usermeta it will fail to correctly create the necessary data in
138wp_usermeta.  You may see the error:
139
140  WordPress database error: [Key column 'umeta_id' doesn't exist in table]
141
142The simplest fix is to restore your database and then follow the
143instructions above.  The problem any other way is that you need to go
144through the upgrade process again to populate the wp_usermeta table with WP
1452.0 parameters (if you really want to try, see upgrade_160() in WordPress
146API.
147
148*/
149
150function get_usermeta_object() {
151  static $usermeta;
152  if (!isset($usermeta))
153    $usermeta = new Usermeta;
154  return $usermeta;
155}
156
157class Usermeta {
158
159  var $table;
160  var $cache;
161  var $types;
162
163  /* Usermeta - class initialiser */
164
165  function Usermeta() {
166    global $table_prefix;
167    $this->table = "${table_prefix}usermeta";
168  }
169
170  /* database_exists() - check to see if our tables exist, returns true
171     if so */
172
173  function database_exists() {
174    global $wpdb;
175    if ($wpdb->get_var("SHOW TABLES LIKE '$this->table'") != $this->table)
176      return false;
177    return true;
178  }
179 
180  /* ensure_database() - ensures that the necessary table has been
181     created */
182
183  function ensure_database() {
184    require_once(ABSPATH.'wp-admin/upgrade-functions.php');
185    return dbDelta("CREATE TABLE $this->table (
186    umeta_id bigint(20) NOT NULL auto_increment,
187    user_id bigint(20) NOT NULL default '0',
188    meta_key varchar(255) default NULL,
189    meta_value longtext,
190    PRIMARY KEY  (umeta_id),
191    KEY user_id (user_id),
192    KEY meta_key (meta_key)
193    ) TYPE=MyISAM;");
194  }
195
196  /* add(user_id, key, value, unique) - adds in the given value for this
197     user/key when unique is false.  If unique is true, a check is made to
198     see if the user/key already exists and if it does, no new entry is
199     added.  If anything was added true is returned, false otherwise. */
200
201  function add($user_id, $key, $value, $unique = false) {
202    global $wpdb;
203    if ($unique) {
204      if( $wpdb->get_var("SELECT meta_key FROM $this->table
205                          WHERE meta_key='$key' AND user_id = '$user_id'") ) {
206        return false;
207      }
208    }
209    $wpdb->query("INSERT INTO $this->table (user_id,meta_key,meta_value)
210                  VALUES ('$user_id','$key','$value')");
211    return true;
212  }
213
214  /* delete(user_id, key, value) - if no value is given, deletes all values
215     for the given user/key.  If a value is given, only tries to delete that
216     value.  If anything was deleted, returns true. */
217
218  function delete($user_id, $key, $value = NULL) {
219    global $wpdb;
220    if (is_null($value)) {
221      $wpdb->query("DELETE FROM $this->table WHERE user_id='$user_id'
222                    AND meta_key='$key'");
223    } else {
224      $wpdb->query("DELETE FROM $this->table WHERE user_id='$user_id'
225                    AND meta_key='$key' AND meta_value='$value'");
226    }
227    if ($wpdb->rows_affected < 1)
228      return false;
229    $this->update_cache($user_id, $key);
230    return true;
231  }
232
233  /* get(user_id, key, single) - if single is false, returns an array of all
234     values for this user/key, however if single is true, returns the first
235     found entry for this user/key or NULL if there are none */
236     
237  function get($user_id, $key, $single = false) {
238    if (isset($this->cache[$user_id][$key])) {
239      $values = $this->cache[$user_id][$key];
240      if (is_null($values))
241        return NULL;
242      return $single ? $values[0] : $values;
243    }
244    $values = $this->update_cache($user_id, $key, $single);
245    if ($single)
246      return is_null($values) ? NULL : $values[0];
247    return $values;
248  }
249
250  /* set(user_id, key, value) - sets all occurances of user_id/key to the
251     given value.  If no such user_id/key exists, a new entry is added.
252     Always true on success. */
253
254  function set($user_id, $key, $value) {
255    if (is_null($this->get($user_id, $key, true))) {
256      $this->add($user_id, $key, $value, false);
257      return true;
258    }
259    $this->update($user_id, $key, $value);
260    return true;
261  }
262
263  /* update_cache(user_id, key) - updates the cache and returns an array of
264     current values, or NULL if there are no values */
265
266  function update_cache($user_id, $key) {
267    global $wpdb;
268    $metalist = $wpdb->get_results("SELECT meta_value FROM $this->table
269                                    WHERE user_id='$user_id'
270                                    AND meta_key='$key'", ARRAY_N);
271    $values = NULL;
272    if ($metalist) {
273      $values = array();
274      foreach ($metalist as $metarow)
275        $values[] = $metarow[0];
276    }
277    $this->cache[$user_id][$key] = $values;
278    return $values;
279  }
280
281  /* update(user_id, key, value[, prev_value]) - updates all occurances of
282     this user/key with the new value.  If optional fourth param is passed in,
283     then only matches with that value are changed.  Returns true if any
284     items were changed, false otherwise. */
285     
286  function update($user_id, $key, $value, $prev_value = NULL) {
287    global $wpdb;
288    if (is_null($prev_value)) {
289      $wpdb->query("UPDATE $this->table SET meta_value='$value'
290                    WHERE meta_key='$key' AND user_id='$user_id'");
291    } else {
292      $wpdb->query("UPDATE $this->table SET meta_value = '$value'
293                    WHERE meta_key = '$key' AND user_id = '$user_id'
294                    AND meta_value = '$prev_value'");
295    }
296    if ($wpdb->rows_affected < 1)
297      return false;
298    $this->update_cache($user_id, $key);
299    return true;
300  }
301
302  /* get_fieldinfo($field_name) - return information on the field named.
303     Returns an array with the keys:
304       description => a description of the field
305       type => the type of the field: Text, Text Box, Toggle, Option List
306       options => the options
307       default => the default for this field
308       useredit => No or Yes
309     Note that this only returns information for a field which has been
310     defined by the user in the main Usermeta options page.
311  */
312
313  function display_updated($text) {
314    echo '<div class="updated"><p>';
315    echo $this->T($text, 'usermeta');
316    echo '</p></div>';
317  }
318
319  function T($text) {
320    return __($text, 'usermeta');
321  }
322
323  function H($text) {
324    return htmlspecialchars($text, ENT_QUOTES);
325  }
326
327  function HT($text) {
328    return htmlspecialchars($this->T($text), ENT_QUOTES);
329  }
330
331  function EHT($text) {
332    echo $this->HT($text);
333  }
334
335  function options_usermeta() {
336    $this->options_usermeta_checkaction();
337    $this->options_usermeta_display();
338  }
339
340  function options_usermeta_checkaction() {
341    switch ($_REQUEST['action']) {
342      case 'ensure_database':
343        /* make sure database exists */
344        $out = $this->ensure_database();
345        foreach ($out as $message) {
346          $this->display_updated($message);
347        }
348        if (count($out) == 0)
349          $this->display_updated('Tables up to date, nothing to do.');
350        break;
351    }
352  }
353
354  function options_usermeta_display() {
355    ?>
356    <div class="wrap">
357      <h2><?php $this->EHT('Database management') ?></h2>
358      <form method="post">
359        <input type="hidden" name="action" value="ensure_database" />
360        <fieldset class="options">
361          <legend><?php $this->EHT('Maintenance') ?></legend>
362          <?php if ($this->database_exists() == false) {
363            echo '<p><strong>';
364            echo $this->H("WARNING: Table $this->table not found.");
365            $this->EHT('Please click button below to create '.
366                       'necessary tables.');
367            echo '</strong></p>';
368          } else {
369            echo '<p>';
370            $this->EHT('Usermeta tables are installed.');
371            echo '</p>';
372
373          } ?>
374          <div class="submit"><input type="submit" value="<?php
375            echo $this->H($this->T('Create/Update usermeta tables')).
376                 ' &raquo;' ?>" /></div>
377        </fieldset>
378      </form>
379    </div>
380    <?
381  }
382
383  function action_admin_menu() {
384    add_options_page($this->T('User attributes'),
385                     $this->T('Usermeta'),
386                     8, basename(__FILE__), array(&$this, 'options_usermeta'));
387  }
388
389}
390
391global $user_level;
392
393load_plugin_textdomain('usermeta');
394$usermeta = get_usermeta_object();
395add_action('admin_menu', array(&$usermeta, 'action_admin_menu'));
396?>