source: trunk/include/ws_functions/pwg.users.php @ 25459

Last change on this file since 25459 was 25459, checked in by plg, 10 years ago

feature 2976: add output fields for pwg.users.getList. registration_date,
registration_date_string, registration_date_since, last_visit,
last_visit_string, last_visit_since.

bug fixed: format_date(), removing leading zero on day number

File size: 14.1 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2013 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24/**
25 * API method
26 * Returns a list of users
27 * @param mixed[] $params
28 *    @option int[] user_id (optional)
29 *    @option string username (optional)
30 *    @option string[] status (optional)
31 *    @option int min_level (optional)
32 *    @option int[] group_id (optional)
33 *    @option int per_page
34 *    @option int page
35 *    @option string order
36 */
37function ws_users_getList($params, &$service)
38{
39  global $conf;
40
41  $where_clauses = array('1=1');
42
43  if (!empty($params['user_id']))
44  {
45    $where_clauses[] = 'u.'.$conf['user_fields']['id'].' IN('. implode(',', $params['user_id']) .')';
46  }
47
48  if (!empty($params['username']))
49  {
50    $where_clauses[] = 'u.'.$conf['user_fields']['username'].' LIKE \''.pwg_db_real_escape_string($params['username']).'\'';
51  }
52
53  if (!empty($params['status']))
54  {
55    $params['status'] = array_intersect($params['status'], get_enums(USER_INFOS_TABLE, 'status'));
56    if (count($params['status']) > 0)
57    {
58      $where_clauses[] = 'ui.status IN("'. implode('","', $params['status']) .'")';
59    }
60  }
61
62  if (!empty($params['min_level']))
63  {
64    if ( !in_array($params['min_level'], $conf['available_permission_levels']) )
65    {
66      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid level');
67    }
68    $where_clauses[] = 'ui.level >= '.$params['min_level'];
69  }
70
71  if (!empty($params['group_id']))
72  {
73    $where_clauses[] = 'ug.group_id IN('. implode(',', $params['group_id']) .')';
74  }
75
76  $display = array('u.'.$conf['user_fields']['id'] => 'id');
77
78  if ($params['display'] != 'none')
79  {
80    $params['display'] = explode(',', $params['display']);
81
82    if (in_array('all', $params['display']))
83    {
84      $params['display'] = array_merge($params['display'], array(
85        'username','email','status','level','groups','language','theme',
86        'nb_image_page','recent_period','expand','show_nb_comments','show_nb_hits',
87        'enabled_high','registration_date','registration_date_string',
88        'registration_date_since', 'last_visit', 'last_visit_string',
89        'last_visit_since'
90        ));
91    }
92    else if (in_array('basics', $params['display']))
93    {
94      $params['display'] = array_merge($params['display'], array(
95        'username','email','status','level','groups',
96        ));
97    }
98
99    if (in_array('username', $params['display']))
100    {
101      $display['u.'.$conf['user_fields']['username']] = 'username';
102    }
103    if (in_array('email', $params['display']))
104    {
105      $display['u.'.$conf['user_fields']['email']] = 'email';
106    }
107
108    $ui_fields = array(
109      'status','level','language','theme','nb_image_page','recent_period','expand',
110      'show_nb_comments','show_nb_hits','enabled_high','registration_date'
111      );
112    foreach ($ui_fields as $field)
113    {
114      if (in_array($field, $params['display']))
115      {
116        $display['ui.'.$field] = $field;
117      }
118    }
119  }
120  else
121  {
122    $params['display'] = array();
123  }
124
125  $query = '
126SELECT DISTINCT ';
127
128  $first = true;
129  foreach ($display as $field => $name)
130  {
131    if (!$first) $query.= ', ';
132    else $first = false;
133    $query.= $field .' AS '. $name;
134  }
135  if (in_array('groups', $params['display']))
136  {
137    if (!$first) $query.= ', ';
138    $query.= '"" AS groups';
139  }
140
141  $query.= '
142  FROM '. USERS_TABLE .' AS u
143    INNER JOIN '. USER_INFOS_TABLE .' AS ui
144      ON u.'. $conf['user_fields']['id'] .' = ui.user_id
145    LEFT JOIN '. USER_GROUP_TABLE .' AS ug
146      ON u.'. $conf['user_fields']['id'] .' = ug.user_id
147  WHERE
148    '. implode(' AND ', $where_clauses) .'
149  ORDER BY '. $params['order'] .'
150  LIMIT '. $params['per_page'] .'
151  OFFSET '. ($params['per_page']*$params['page']) .'
152;';
153
154  $users = hash_from_query($query, 'id');
155
156  if (count($users) > 0 and in_array('groups', $params['display']))
157  {
158    $query = '
159SELECT user_id, group_id
160  FROM '. USER_GROUP_TABLE .'
161  WHERE user_id IN ('. implode(',', array_keys($users)) .')
162;';
163    $result = pwg_query($query);
164
165    while ($row = pwg_db_fetch_assoc($result))
166    {
167      $users[ $row['user_id'] ]['groups'][] = $row['group_id'];
168    }
169  }
170
171  if (count($users) > 0 and in_array('registration_date_string', $params['display']))
172  {
173    foreach ($users as $cur_user)
174    {
175      $users[ $cur_user['id'] ]['registration_date_string'] = format_date($cur_user['registration_date'], false, false);
176    }
177  }
178
179  if (count($users) > 0 and in_array('registration_date_since', $params['display']))
180  {
181    foreach ($users as $cur_user)
182    {
183      $users[ $cur_user['id'] ]['registration_date_since'] = time_since($cur_user['registration_date'], 'month');
184    }
185  }
186
187  if (count($users) > 0 and in_array('last_visit', $params['display']))
188  {
189    $query = '
190SELECT
191    MAX(id) as history_id
192  FROM '.HISTORY_TABLE.'
193  WHERE user_id IN ('.implode(',', array_keys($users)).')
194  GROUP BY user_id
195;';
196    $history_ids = array_from_query($query, 'history_id');
197
198    if (count($history_ids) == 0)
199    {
200      $history_ids[] = -1;
201    }
202   
203    $query = '
204SELECT
205    user_id,
206    date,
207    time
208  FROM '.HISTORY_TABLE.'
209  WHERE id IN ('.implode(',', $history_ids).')
210;';
211    $result = pwg_query($query);
212    while ($row = pwg_db_fetch_assoc($result))
213    {
214      $last_visit = $row['date'].' '.$row['time'];
215      $users[ $row['user_id'] ]['last_visit'] = $last_visit;
216
217      if (in_array('last_visit_string', $params['display']))
218      {
219        $users[ $row['user_id'] ]['last_visit_string'] = format_date($last_visit, false, false);
220      }
221     
222      if (in_array('last_visit_since', $params['display']))
223      {
224        $users[ $row['user_id'] ]['last_visit_since'] = time_since($last_visit, 'day');
225      }
226    }
227  }
228
229  return array(
230    'paging' => new PwgNamedStruct(
231      array(
232        'page' => $params['page'],
233        'per_page' => $params['per_page'],
234        'count' => count($users)
235        )
236      ),
237    'users' => new PwgNamedArray(array_values($users), 'user')
238    );
239}
240
241/**
242 * API method
243 * Adds a user
244 * @param mixed[] $params
245 *    @option string username
246 *    @option string password (optional)
247 *    @option string email (optional)
248 */
249function ws_users_add($params, &$service)
250{
251  global $conf;
252
253  if ($conf['double_password_type_in_admin'])
254  {
255    if ($params['password'] != $params['password_confirm'])
256    {
257      return new PwgError(WS_ERR_INVALID_PARAM, l10n('The passwords do not match'));
258    }
259  }
260
261  $user_id = register_user(
262    $params['username'],
263    $params['password'],
264    $params['email'],
265    false, // notify admin
266    $errors,
267    $params['send_password_by_mail']
268    );
269
270  if (!$user_id)
271  {
272    return new PwgError(WS_ERR_INVALID_PARAM, $errors[0]);
273  }
274
275  return $service->invoke('pwg.users.getList', array('user_id'=>$user_id));
276}
277
278/**
279 * API method
280 * Deletes users
281 * @param mixed[] $params
282 *    @option int[] user_id
283 *    @option string pwg_token
284 */
285function ws_users_delete($params, &$service)
286{
287  if (get_pwg_token() != $params['pwg_token'])
288  {
289    return new PwgError(403, 'Invalid security token');
290  }
291
292  global $conf, $user;
293
294  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
295
296  // protect some users
297  $params['user_id'] = array_diff(
298    $params['user_id'],
299    array(
300      $user['id'],
301      $conf['guest_id'],
302      $conf['default_user_id'],
303      $conf['webmaster_id'],
304      )
305    );
306
307  foreach ($params['user_id'] as $user_id)
308  {
309    delete_user($user_id);
310  }
311
312  return l10n_dec(
313        '%d user deleted', '%d users deleted',
314        count($params['user_id'])
315        );
316}
317
318/**
319 * API method
320 * Updates users
321 * @param mixed[] $params
322 *    @option int[] user_id
323 *    @option string username (optional)
324 *    @option string password (optional)
325 *    @option string email (optional)
326 *    @option string status (optional)
327 *    @option int level (optional)
328 *    @option string language (optional)
329 *    @option string theme (optional)
330 *    @option int nb_image_page (optional)
331 *    @option int recent_period (optional)
332 *    @option bool expand (optional)
333 *    @option bool show_nb_comments (optional)
334 *    @option bool show_nb_hits (optional)
335 *    @option bool enabled_high (optional)
336 */
337function ws_users_setInfo($params, &$service)
338{
339  global $conf, $user;
340
341  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
342
343  $updates = $updates_infos = array();
344  $update_status = null;
345
346  if (count($params['user_id']) == 1)
347  {
348    if (get_username($params['user_id'][0]) === false)
349    {
350      return new PwgError(WS_ERR_INVALID_PARAM, 'This user does not exist.');
351    }
352
353    if (!empty($params['username']))
354    {
355      $user_id = get_userid($params['username']);
356      if ($user_id and $user_id != $params['user_id'][0])
357      {
358        return new PwgError(WS_ERR_INVALID_PARAM, l10n('this login is already used'));
359      }
360      if ($params['username'] != strip_tags($params['username']))
361      {
362        return new PwgError(WS_ERR_INVALID_PARAM, l10n('html tags are not allowed in login'));
363      }
364      $updates[ $conf['user_fields']['username'] ] = $params['username'];
365    }
366
367    if (!empty($params['email']))
368    {
369      if ( ($error = validate_mail_address($params['user_id'][0], $params['email'])) != '')
370      {
371        return new PwgError(WS_ERR_INVALID_PARAM, $error);
372      }
373      $updates[ $conf['user_fields']['email'] ] = $params['email'];
374    }
375
376    if (!empty($params['password']))
377    {
378      $updates[ $conf['user_fields']['password'] ] = $conf['password_hash']($params['password']);
379    }
380  }
381
382  if (!empty($params['status']))
383  {
384    if ( $params['status'] == 'webmaster' and !is_webmaster() )
385    {
386      return new PwgError(403, 'Only webmasters can grant "webmaster" status');
387    }
388    if ( !in_array($params['status'], array('guest','generic','normal','admin','webmaster')) )
389    {
390      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid status');
391    }
392
393    // status update query is separated from the rest as not applying to the same
394    // set of users (current, guest and webmaster can't be changed)
395    $params['user_id_for_status'] = array_diff(
396      $params['user_id'],
397      array(
398        $user['id'],
399        $conf['guest_id'],
400        $conf['webmaster_id'],
401        )
402      );
403
404    $update_status = $params['status'];
405  }
406
407  if (!empty($params['level']) or @$params['level']===0)
408  {
409    if ( !in_array($params['level'], $conf['available_permission_levels']) )
410    {
411      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid level');
412    }
413    $updates_infos['level'] = $params['level'];
414  }
415
416  if (!empty($params['language']))
417  {
418    if ( !in_array($params['language'], array_keys(get_languages())) )
419    {
420      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid language');
421    }
422    $updates_infos['language'] = $params['language'];
423  }
424
425  if (!empty($params['theme']))
426  {
427    if ( !in_array($params['theme'], array_keys(get_pwg_themes())) )
428    {
429      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid theme');
430    }
431    $updates_infos['theme'] = $params['theme'];
432  }
433
434  if (!empty($params['nb_image_page']))
435  {
436    $updates_infos['nb_image_page'] = $params['nb_image_page'];
437  }
438
439  if (!empty($params['recent_period']) or @$params['recent_period']===0)
440  {
441    $updates_infos['recent_period'] = $params['recent_period'];
442  }
443
444  if (!empty($params['expand']) or @$params['expand']===false)
445  {
446    $updates_infos['expand'] = boolean_to_string($params['expand']);
447  }
448
449  if (!empty($params['show_nb_comments']) or @$params['show_nb_comments']===false)
450  {
451    $updates_infos['show_nb_comments'] = boolean_to_string($params['show_nb_comments']);
452  }
453
454  if (!empty($params['show_nb_hits']) or @$params['show_nb_hits']===false)
455  {
456    $updates_infos['show_nb_hits'] = boolean_to_string($params['show_nb_hits']);
457  }
458
459  if (!empty($params['enabled_high']) or @$params['enabled_high']===false)
460  {
461    $updates_infos['enabled_high'] = boolean_to_string($params['enabled_high']);
462  }
463
464  // perform updates
465  single_update(
466    USERS_TABLE,
467    $updates,
468    array($conf['user_fields']['id'] => $params['user_id'][0])
469    );
470
471  if (isset($update_status) and count($params['user_id_for_status']) > 0)
472  {
473    $query = '
474UPDATE '. USER_INFOS_TABLE .' SET
475    status = "'. $update_status .'"
476  WHERE user_id IN('. implode(',', $params['user_id_for_status']) .')
477;';
478    pwg_query($query);
479  }
480
481  if (count($updates_infos) > 0)
482  {
483    $query = '
484UPDATE '. USER_INFOS_TABLE .' SET ';
485
486    $first = true;
487    foreach ($updates_infos as $field => $value)
488    {
489      if (!$first) $query.= ', ';
490      else $first = false;
491      $query.= $field .' = "'. $value .'"';
492    }
493
494    $query.= '
495  WHERE user_id IN('. implode(',', $params['user_id']) .')
496;';
497    pwg_query($query);
498  }
499
500  return $service->invoke('pwg.users.getList', array(
501    'user_id' => $params['user_id'],
502    'display' => 'basics,'.implode(',', array_keys($updates_infos)),
503    ));
504}
505
506?>
Note: See TracBrowser for help on using the repository browser.