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

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

feature 2976: ability to set group association with pwg.users.setInfo

File size: 15.6 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 *    @option string display
37 */
38function ws_users_getList($params, &$service)
39{
40  global $conf;
41
42  $where_clauses = array('1=1');
43
44  if (!empty($params['user_id']))
45  {
46    $where_clauses[] = 'u.'.$conf['user_fields']['id'].' IN('. implode(',', $params['user_id']) .')';
47  }
48
49  if (!empty($params['username']))
50  {
51    $where_clauses[] = 'u.'.$conf['user_fields']['username'].' LIKE \''.pwg_db_real_escape_string($params['username']).'\'';
52  }
53
54  if (!empty($params['status']))
55  {
56    $params['status'] = array_intersect($params['status'], get_enums(USER_INFOS_TABLE, 'status'));
57    if (count($params['status']) > 0)
58    {
59      $where_clauses[] = 'ui.status IN("'. implode('","', $params['status']) .'")';
60    }
61  }
62
63  if (!empty($params['min_level']))
64  {
65    if ( !in_array($params['min_level'], $conf['available_permission_levels']) )
66    {
67      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid level');
68    }
69    $where_clauses[] = 'ui.level >= '.$params['min_level'];
70  }
71
72  if (!empty($params['group_id']))
73  {
74    $where_clauses[] = 'ug.group_id IN('. implode(',', $params['group_id']) .')';
75  }
76
77  $display = array('u.'.$conf['user_fields']['id'] => 'id');
78
79  if ($params['display'] != 'none')
80  {
81    $params['display'] = array_map('trim', explode(',', $params['display']));
82
83    if (in_array('all', $params['display']))
84    {
85      $params['display'] = array(
86        'username','email','status','level','groups','language','theme',
87        'nb_image_page','recent_period','expand','show_nb_comments','show_nb_hits',
88        'enabled_high','registration_date','registration_date_string',
89        'registration_date_since', 'last_visit', 'last_visit_string',
90        'last_visit_since'
91        );
92    }
93    else if (in_array('basics', $params['display']))
94    {
95      $params['display'] = array_merge($params['display'], array(
96        'username','email','status','level','groups',
97        ));
98    }
99    $params['display'] = array_flip($params['display']);
100
101    // if registration_date_string or registration_date_since is requested,
102    // then registration_date is automatically added
103    if (isset($params['display']['registration_date_string']) or isset($params['display']['registration_date_since']))
104    {
105      $params['display']['registration_date'] = true;
106    }
107
108    // if last_visit_string or last_visit_since is requested, then
109    // last_visit is automatically added
110    if (isset($params['display']['last_visit_string']) or isset($params['display']['last_visit_since']))
111    {
112      $params['display']['last_visit'] = true;
113    }
114
115    if (isset($params['display']['username']))
116    {
117      $display['u.'.$conf['user_fields']['username']] = 'username';
118    }
119    if (isset($params['display']['email']))
120    {
121      $display['u.'.$conf['user_fields']['email']] = 'email';
122    }
123
124    $ui_fields = array(
125      'status','level','language','theme','nb_image_page','recent_period','expand',
126      'show_nb_comments','show_nb_hits','enabled_high','registration_date'
127      );
128    foreach ($ui_fields as $field)
129    {
130      if (isset($params['display'][$field]))
131      {
132        $display['ui.'.$field] = $field;
133      }
134    }
135  }
136  else
137  {
138    $params['display'] = array();
139  }
140
141  $query = '
142SELECT DISTINCT ';
143
144  $first = true;
145  foreach ($display as $field => $name)
146  {
147    if (!$first) $query.= ', ';
148    else $first = false;
149    $query.= $field .' AS '. $name;
150  }
151  if (isset($params['display']['groups']))
152  {
153    if (!$first) $query.= ', ';
154    $query.= '"" AS groups';
155  }
156
157  $query.= '
158  FROM '. USERS_TABLE .' AS u
159    INNER JOIN '. USER_INFOS_TABLE .' AS ui
160      ON u.'. $conf['user_fields']['id'] .' = ui.user_id
161    LEFT JOIN '. USER_GROUP_TABLE .' AS ug
162      ON u.'. $conf['user_fields']['id'] .' = ug.user_id
163  WHERE
164    '. implode(' AND ', $where_clauses) .'
165  ORDER BY '. $params['order'] .'
166  LIMIT '. $params['per_page'] .'
167  OFFSET '. ($params['per_page']*$params['page']) .'
168;';
169
170  $users = hash_from_query($query, 'id');
171
172  if (count($users) > 0)
173  {
174    if (isset($params['display']['groups']))
175    {
176      $query = '
177SELECT user_id, group_id
178  FROM '. USER_GROUP_TABLE .'
179  WHERE user_id IN ('. implode(',', array_keys($users)) .')
180;';
181      $result = pwg_query($query);
182     
183      while ($row = pwg_db_fetch_assoc($result))
184      {
185        $users[ $row['user_id'] ]['groups'][] = $row['group_id'];
186      }
187    }
188   
189    if (isset($params['display']['registration_date_string']))
190    {
191      foreach ($users as $cur_user)
192      {
193        $users[$cur_user['id']]['registration_date_string'] = format_date($cur_user['registration_date'], false, false);
194      }
195    }
196
197    if (isset($params['display']['registration_date_since']))
198    {
199      foreach ($users as $cur_user)
200      {
201        $users[ $cur_user['id'] ]['registration_date_since'] = time_since($cur_user['registration_date'], 'month');
202      }
203    }
204
205    if (isset($params['display']['last_visit']))
206    {
207      $query = '
208SELECT
209    MAX(id) as history_id
210  FROM '.HISTORY_TABLE.'
211  WHERE user_id IN ('.implode(',', array_keys($users)).')
212  GROUP BY user_id
213;';
214      $history_ids = array_from_query($query, 'history_id');
215     
216      if (count($history_ids) == 0)
217      {
218        $history_ids[] = -1;
219      }
220     
221      $query = '
222SELECT
223    user_id,
224    date,
225    time
226  FROM '.HISTORY_TABLE.'
227  WHERE id IN ('.implode(',', $history_ids).')
228;';
229      $result = pwg_query($query);
230      while ($row = pwg_db_fetch_assoc($result))
231      {
232        $last_visit = $row['date'].' '.$row['time'];
233        $users[ $row['user_id'] ]['last_visit'] = $last_visit;
234       
235        if (isset($params['display']['last_visit_string']))
236        {
237          $users[ $row['user_id'] ]['last_visit_string'] = format_date($last_visit, false, false);
238        }
239       
240        if (isset($params['display']['last_visit_since']))
241        {
242          $users[ $row['user_id'] ]['last_visit_since'] = time_since($last_visit, 'day');
243        }
244      }
245    }
246  }
247
248  return array(
249    'paging' => new PwgNamedStruct(
250      array(
251        'page' => $params['page'],
252        'per_page' => $params['per_page'],
253        'count' => count($users)
254        )
255      ),
256    'users' => new PwgNamedArray(array_values($users), 'user')
257    );
258}
259
260/**
261 * API method
262 * Adds a user
263 * @param mixed[] $params
264 *    @option string username
265 *    @option string password (optional)
266 *    @option string email (optional)
267 */
268function ws_users_add($params, &$service)
269{
270  global $conf;
271
272  if ($conf['double_password_type_in_admin'])
273  {
274    if ($params['password'] != $params['password_confirm'])
275    {
276      return new PwgError(WS_ERR_INVALID_PARAM, l10n('The passwords do not match'));
277    }
278  }
279
280  $user_id = register_user(
281    $params['username'],
282    $params['password'],
283    $params['email'],
284    false, // notify admin
285    $errors,
286    $params['send_password_by_mail']
287    );
288
289  if (!$user_id)
290  {
291    return new PwgError(WS_ERR_INVALID_PARAM, $errors[0]);
292  }
293
294  return $service->invoke('pwg.users.getList', array('user_id'=>$user_id));
295}
296
297/**
298 * API method
299 * Deletes users
300 * @param mixed[] $params
301 *    @option int[] user_id
302 *    @option string pwg_token
303 */
304function ws_users_delete($params, &$service)
305{
306  if (get_pwg_token() != $params['pwg_token'])
307  {
308    return new PwgError(403, 'Invalid security token');
309  }
310
311  global $conf, $user;
312
313  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
314
315  // protect some users
316  $params['user_id'] = array_diff(
317    $params['user_id'],
318    array(
319      $user['id'],
320      $conf['guest_id'],
321      $conf['default_user_id'],
322      $conf['webmaster_id'],
323      )
324    );
325
326  foreach ($params['user_id'] as $user_id)
327  {
328    delete_user($user_id);
329  }
330
331  return l10n_dec(
332        '%d user deleted', '%d users deleted',
333        count($params['user_id'])
334        );
335}
336
337/**
338 * API method
339 * Updates users
340 * @param mixed[] $params
341 *    @option int[] user_id
342 *    @option string username (optional)
343 *    @option string password (optional)
344 *    @option string email (optional)
345 *    @option string status (optional)
346 *    @option int level (optional)
347 *    @option string language (optional)
348 *    @option string theme (optional)
349 *    @option int nb_image_page (optional)
350 *    @option int recent_period (optional)
351 *    @option bool expand (optional)
352 *    @option bool show_nb_comments (optional)
353 *    @option bool show_nb_hits (optional)
354 *    @option bool enabled_high (optional)
355 */
356function ws_users_setInfo($params, &$service)
357{
358  global $conf, $user;
359
360  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
361
362  $updates = $updates_infos = array();
363  $update_status = null;
364
365  if (count($params['user_id']) == 1)
366  {
367    if (get_username($params['user_id'][0]) === false)
368    {
369      return new PwgError(WS_ERR_INVALID_PARAM, 'This user does not exist.');
370    }
371
372    if (!empty($params['username']))
373    {
374      $user_id = get_userid($params['username']);
375      if ($user_id and $user_id != $params['user_id'][0])
376      {
377        return new PwgError(WS_ERR_INVALID_PARAM, l10n('this login is already used'));
378      }
379      if ($params['username'] != strip_tags($params['username']))
380      {
381        return new PwgError(WS_ERR_INVALID_PARAM, l10n('html tags are not allowed in login'));
382      }
383      $updates[ $conf['user_fields']['username'] ] = $params['username'];
384    }
385
386    if (!empty($params['email']))
387    {
388      if ( ($error = validate_mail_address($params['user_id'][0], $params['email'])) != '')
389      {
390        return new PwgError(WS_ERR_INVALID_PARAM, $error);
391      }
392      $updates[ $conf['user_fields']['email'] ] = $params['email'];
393    }
394
395    if (!empty($params['password']))
396    {
397      $updates[ $conf['user_fields']['password'] ] = $conf['password_hash']($params['password']);
398    }
399  }
400
401  if (!empty($params['status']))
402  {
403    if ( $params['status'] == 'webmaster' and !is_webmaster() )
404    {
405      return new PwgError(403, 'Only webmasters can grant "webmaster" status');
406    }
407    if ( !in_array($params['status'], array('guest','generic','normal','admin','webmaster')) )
408    {
409      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid status');
410    }
411
412    // status update query is separated from the rest as not applying to the same
413    // set of users (current, guest and webmaster can't be changed)
414    $params['user_id_for_status'] = array_diff(
415      $params['user_id'],
416      array(
417        $user['id'],
418        $conf['guest_id'],
419        $conf['webmaster_id'],
420        )
421      );
422
423    $update_status = $params['status'];
424  }
425
426  if (!empty($params['level']) or @$params['level']===0)
427  {
428    if ( !in_array($params['level'], $conf['available_permission_levels']) )
429    {
430      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid level');
431    }
432    $updates_infos['level'] = $params['level'];
433  }
434
435  if (!empty($params['language']))
436  {
437    if ( !in_array($params['language'], array_keys(get_languages())) )
438    {
439      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid language');
440    }
441    $updates_infos['language'] = $params['language'];
442  }
443
444  if (!empty($params['theme']))
445  {
446    if ( !in_array($params['theme'], array_keys(get_pwg_themes())) )
447    {
448      return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid theme');
449    }
450    $updates_infos['theme'] = $params['theme'];
451  }
452
453  if (!empty($params['nb_image_page']))
454  {
455    $updates_infos['nb_image_page'] = $params['nb_image_page'];
456  }
457
458  if (!empty($params['recent_period']) or @$params['recent_period']===0)
459  {
460    $updates_infos['recent_period'] = $params['recent_period'];
461  }
462
463  if (!empty($params['expand']) or @$params['expand']===false)
464  {
465    $updates_infos['expand'] = boolean_to_string($params['expand']);
466  }
467
468  if (!empty($params['show_nb_comments']) or @$params['show_nb_comments']===false)
469  {
470    $updates_infos['show_nb_comments'] = boolean_to_string($params['show_nb_comments']);
471  }
472
473  if (!empty($params['show_nb_hits']) or @$params['show_nb_hits']===false)
474  {
475    $updates_infos['show_nb_hits'] = boolean_to_string($params['show_nb_hits']);
476  }
477
478  if (!empty($params['enabled_high']) or @$params['enabled_high']===false)
479  {
480    $updates_infos['enabled_high'] = boolean_to_string($params['enabled_high']);
481  }
482
483  // perform updates
484  single_update(
485    USERS_TABLE,
486    $updates,
487    array($conf['user_fields']['id'] => $params['user_id'][0])
488    );
489
490  if (isset($update_status) and count($params['user_id_for_status']) > 0)
491  {
492    $query = '
493UPDATE '. USER_INFOS_TABLE .' SET
494    status = "'. $update_status .'"
495  WHERE user_id IN('. implode(',', $params['user_id_for_status']) .')
496;';
497    pwg_query($query);
498  }
499
500  if (count($updates_infos) > 0)
501  {
502    $query = '
503UPDATE '. USER_INFOS_TABLE .' SET ';
504
505    $first = true;
506    foreach ($updates_infos as $field => $value)
507    {
508      if (!$first) $query.= ', ';
509      else $first = false;
510      $query.= $field .' = "'. $value .'"';
511    }
512
513    $query.= '
514  WHERE user_id IN('. implode(',', $params['user_id']) .')
515;';
516    pwg_query($query);
517  }
518
519  // manage association to groups
520  if (!empty($params['group_id']))
521  {
522    $query = '
523DELETE
524  FROM '.USER_GROUP_TABLE.'
525  WHERE user_id IN ('.implode(',', $params['user_id']).')
526;';
527    pwg_query($query);
528
529    // we remove all provided groups that do not really exist
530    $query = '
531SELECT
532    id
533  FROM '.GROUPS_TABLE.'
534  WHERE id IN ('.implode(',', $params['group_id']).')
535;';
536    $group_ids = array_from_query($query, 'id');
537
538    // if only -1 (a group id that can't exist) is in the list, then no
539    // group is associated
540   
541    if (count($group_ids) > 0)
542    {
543      $inserts = array();
544     
545      foreach ($group_ids as $group_id)
546      {
547        foreach ($params['user_id'] as $user_id)
548        {
549          $inserts[] = array('user_id' => $user_id, 'group_id' => $group_id);
550        }
551      }
552
553      mass_inserts(USER_GROUP_TABLE, array_keys($inserts[0]), $inserts);
554    }
555  }
556
557  return $service->invoke('pwg.users.getList', array(
558    'user_id' => $params['user_id'],
559    'display' => 'basics,'.implode(',', array_keys($updates_infos)),
560    ));
561}
562
563?>
Note: See TracBrowser for help on using the repository browser.