source: trunk/admin/include/languages.class.php @ 9518

Last change on this file since 9518 was 9518, checked in by patdenice, 13 years ago

feature:2210
Improve language management.

  • Property svn:eol-style set to LF
File size: 13.5 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2011 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
24class languages
25{
26  var $fs_languages = array();
27  var $db_languages = array();
28  var $server_languages = array();
29
30  /**
31   * Initialize $fs_languages and $db_languages
32  */
33  function languages($target_charset = null)
34  {
35    $this->fs_languages = $this->get_fs_languages($target_charset);
36  }
37
38  /**
39   * Set tabsheet for languages pages.
40   * @param string selected page.
41   */
42  function set_tabsheet($selected)
43  {
44    include_once(PHPWG_ROOT_PATH.'admin/include/tabsheet.class.php');
45
46    $link = get_root_url().'admin.php?page=';
47
48    $tabsheet = new tabsheet();
49    $tabsheet->add('languages_installed', l10n('Installed Languages'), $link.'languages_installed');
50    $tabsheet->add('languages_new', l10n('Add New Language'), $link.'languages_new');
51    $tabsheet->select($selected);
52    $tabsheet->assign();
53  }
54
55  /**
56   * Perform requested actions
57   * @param string - action
58   * @param string - language id
59   * @param array - errors
60   */
61  function perform_action($action, $language_id)
62  {
63    global $conf;
64
65    if (isset($this->db_languages[$language_id]))
66    {
67      $crt_db_language = $this->db_languages[$language_id];
68    }
69
70    $errors = array();
71
72    switch ($action)
73    {
74      case 'activate':
75        if (isset($crt_db_language))
76        {
77          array_push($errors, 'CANNOT ACTIVATE - LANGUAGE IS ALREADY ACTIVATED');
78          break;
79        }
80
81        $query = '
82INSERT INTO '.LANGUAGES_TABLE.'
83  (id, version, name)
84  VALUES(\''.$language_id.'\',
85         \''.$this->fs_languages[$language_id]['version'].'\',
86         \''.$this->fs_languages[$language_id]['name'].'\')
87;';
88        pwg_query($query);
89        break;
90
91      case 'deactivate':
92        if (!isset($crt_db_language))
93        {
94          array_push($errors, 'CANNOT DEACTIVATE - LANGUAGE IS ALREADY DEACTIVATED');
95          break;
96        }
97
98        if ($language_id == get_default_language())
99        {
100          array_push($errors, 'CANNOT DEACTIVATE - LANGUAGE IS DEFAULT LANGUAGE');
101          break;
102        }
103
104        $query = '
105DELETE
106  FROM '.LANGUAGES_TABLE.'
107  WHERE id= \''.$language_id.'\'
108;';
109        pwg_query($query);
110        break;
111
112      case 'delete':
113        if (!empty($crt_db_language))
114        {
115          array_push($errors, 'CANNOT DELETE - LANGUAGE IS ACTIVATED');
116          break;
117        }
118        if (!isset($this->fs_languages[$language_id]))
119        {
120          array_push($errors, 'CANNOT DELETE - LANGUAGE DOES NOT EXIST');
121          break;
122        }
123
124        // Set default language to user who are using this language
125        $query = '
126UPDATE '.USER_INFOS_TABLE.'
127  SET language = \''.get_default_language().'\'
128  WHERE language = \''.$language_id.'\'
129;';
130        pwg_query($query);
131
132        if (!$this->deltree(PHPWG_ROOT_PATH.'language/'.$language_id))
133        {
134          $this->send_to_trash(PHPWG_ROOT_PATH.'language/'.$language_id);
135        }
136        break;
137
138      case 'set_default':
139        $query = '
140UPDATE '.USER_INFOS_TABLE.'
141  SET language = \''.$language_id.'\'
142  WHERE user_id = '.$conf['default_user_id'].'
143;';
144        pwg_query($query);
145        break;
146    }
147    return $errors;
148  }
149
150  /**
151  *  Get languages defined in the language directory
152  */
153  function get_fs_languages($target_charset = null)
154  {
155    if ( empty($target_charset) )
156    {
157      $target_charset = get_pwg_charset();
158    }
159    $target_charset = strtolower($target_charset);
160
161    $dir = opendir(PHPWG_ROOT_PATH.'language');
162    while ($file = readdir($dir))
163    {
164      if ($file!='.' and $file!='..')
165      {
166        $path = PHPWG_ROOT_PATH.'language/'.$file;
167        if (is_dir($path) and !is_link($path)
168            and preg_match('/^[a-zA-Z0-9-_]+$/', $file )
169            and file_exists($path.'/common.lang.php')
170            )
171        {
172          $language = array(
173              'code'=>$file,
174              'version'=>'0',
175              'uri'=>'',
176              'author'=>'',
177            );
178          $plg_data = implode( '', file($path.'/common.lang.php') );
179
180          if ( preg_match("|Language Name: (.*)|", $plg_data, $val) )
181          {
182            $language['name'] = trim( $val[1] );
183            $language['name'] = convert_charset($language['name'], 'utf-8', $target_charset);
184          }
185          if (preg_match("|Version: (.*)|", $plg_data, $val))
186          {
187            $language['version'] = trim($val[1]);
188          }
189          if ( preg_match("|Language URI: (.*)|", $plg_data, $val) )
190          {
191            $language['uri'] = trim($val[1]);
192          }
193          if ( preg_match("|Author: (.*)|", $plg_data, $val) )
194          {
195            $language['author'] = trim($val[1]);
196          }
197          if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
198          {
199            $language['author uri'] = trim($val[1]);
200          }
201          if (!empty($language['uri']) and strpos($language['uri'] , 'extension_view.php?eid='))
202          {
203            list( , $extension) = explode('extension_view.php?eid=', $language['uri']);
204            if (is_numeric($extension)) $language['extension'] = $extension;
205          }
206          // IMPORTANT SECURITY !
207          $language = array_map('htmlspecialchars', $language);
208          $this->fs_languages[$file] = $language;
209        }
210      }
211    }
212    closedir($dir);
213    @uasort($this->fs_languages, 'name_compare');
214
215    return $this->fs_languages;
216  }
217
218  function get_db_languages()
219  {
220    $query = '
221  SELECT id, name
222    FROM '.LANGUAGES_TABLE.'
223    ORDER BY name ASC
224  ;';
225    $result = pwg_query($query);
226
227    while ($row = pwg_db_fetch_assoc($result))
228    {
229      $this->db_languages[ $row['id'] ] = $row['name'];
230    }
231  }
232
233  /**
234   * Retrieve PEM server datas to $server_languages
235   */
236  function get_server_languages($new=false)
237  {
238    global $user;
239
240    $get_data = array(
241      'category_id' => 8,
242      'format' => 'php',
243    );
244
245    // Retrieve PEM versions
246    $version = PHPWG_VERSION;
247    $versions_to_check = array();
248    $url = PEM_URL . '/api/get_version_list.php';
249    if (fetchRemote($url, $result, $get_data) and $pem_versions = @unserialize($result))
250    {
251      if (!preg_match('/^\d+\.\d+\.\d+/', $version))
252      {
253        $version = $pem_versions[0]['name'];
254      }
255      $branch = substr($version, 0, strrpos($version, '.'));
256      foreach ($pem_versions as $pem_version)
257      {
258        if (strpos($pem_version['name'], $branch) === 0)
259        {
260          $versions_to_check[] = $pem_version['id'];
261        }
262      }
263    }
264    if (empty($versions_to_check))
265    {
266      return false;
267    }
268
269    // Languages to check
270    $languages_to_check = array();
271    foreach($this->fs_languages as $fs_language)
272    {
273      if (isset($fs_language['extension']))
274      {
275        $languages_to_check[] = $fs_language['extension'];
276      }
277    }
278
279    // Retrieve PEM languages infos
280    $url = PEM_URL . '/api/get_revision_list.php';
281    $get_data = array_merge($get_data, array(
282      'last_revision_only' => 'true',
283      'version' => implode(',', $versions_to_check),
284      'lang' => $user['language'],
285      )
286    );
287    if (!empty($languages_to_check))
288    {
289      if ($new)
290      {
291        $get_data['extension_exclude'] = implode(',', $languages_to_check);
292      }
293      else
294      {
295        $get_data['extension_include'] = implode(',', $languages_to_check);
296      }
297    }
298
299    if (fetchRemote($url, $result, $get_data))
300    {
301      $pem_languages = @unserialize($result);
302      if (!is_array($pem_languages))
303      {
304        return false;
305      }
306      foreach ($pem_languages as $language)
307      {
308        if (preg_match('/^.*? \[[A-Z]{2}\]$/', $language['extension_name']))
309        {
310          $this->server_languages[$language['extension_name']] = $language;
311        }
312      }
313      @ksort($this->server_languages);
314      return true;
315    }
316    return false;
317  }
318
319  /**
320   * Extract language files from archive
321   *
322   * @param string - install or upgrade
323   * @param string - remote revision identifier (numeric)
324   * @param string - language id or extension id
325   */
326  function extract_language_files($action, $revision, $dest='')
327  {
328    if ($archive = tempnam( PHPWG_ROOT_PATH.'language', 'zip'))
329    {
330      $url = PEM_URL . '/download.php';
331      $get_data = array(
332        'rid' => $revision,
333        'origin' => 'piwigo_'.$action,
334      );
335
336      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
337      {
338        fclose($handle);
339        include(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
340        $zip = new PclZip($archive);
341        if ($list = $zip->listContent())
342        {
343          foreach ($list as $file)
344          {
345            // we search common.lang.php in archive
346            if (basename($file['filename']) == 'common.lang.php'
347              and (!isset($main_filepath)
348              or strlen($file['filename']) < strlen($main_filepath)))
349            {
350              $main_filepath = $file['filename'];
351            }
352          }
353          if (isset($main_filepath))
354          {
355            $root = basename(dirname($main_filepath)); // common.lang.php path in archive
356            if (preg_match('/^[a-z]{2}_[A-Z]{2}$/', $root))
357            {
358              if ($action == 'install')
359              {
360                $dest = $root;
361              }
362              $extract_path = PHPWG_ROOT_PATH.'language/'.$dest;
363              if (
364                $result = $zip->extract(
365                  PCLZIP_OPT_PATH, $extract_path,
366                  PCLZIP_OPT_REMOVE_PATH, $root,
367                  PCLZIP_OPT_REPLACE_NEWER
368                  )
369                )
370              {
371                foreach ($result as $file)
372                {
373                  if ($file['stored_filename'] == $main_filepath)
374                  {
375                    $status = $file['status'];
376                    break;
377                  }
378                }
379                if ($status == 'ok')
380                {
381                  $this->fs_languages = $this->get_fs_languages();
382                  $this->perform_action('activate', $dest);
383                }
384                if (file_exists($extract_path.'/obsolete.list')
385                  and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
386                  and !empty($old_files))
387                {
388                  array_push($old_files, 'obsolete.list');
389                  foreach($old_files as $old_file)
390                  {
391                    $path = $extract_path.'/'.$old_file;
392                    if (is_file($path))
393                    {
394                      @unlink($path);
395                    }
396                    elseif (is_dir($path))
397                    {
398                      if (!$this->deltree($path))
399                      {
400                        $this->send_to_trash($path);
401                      }
402                    }
403                  }
404                }
405              }
406              else $status = 'extract_error';
407            }
408            else $status = 'archive_error';
409          }
410          else $status = 'archive_error';
411        }
412        else $status = 'archive_error';
413      }
414      else $status = 'dl_archive_error';
415    }
416    else $status = 'temp_path_error';
417
418    @unlink($archive);
419    return $status;
420  }
421
422  /**
423   * delete $path directory
424   * @param string - path
425   */
426  function deltree($path)
427  {
428    if (is_dir($path))
429    {
430      $fh = opendir($path);
431      while ($file = readdir($fh))
432      {
433        if ($file != '.' and $file != '..')
434        {
435          $pathfile = $path . '/' . $file;
436          if (is_dir($pathfile))
437          {
438            $this->deltree($pathfile);
439          }
440          else
441          {
442            @unlink($pathfile);
443          }
444        }
445      }
446      closedir($fh);
447      return @rmdir($path);
448    }
449  }
450
451  /**
452   * send $path to trash directory
453   * @param string - path
454   */
455  function send_to_trash($path)
456  {
457    $trash_path = PHPWG_ROOT_PATH . 'language/trash';
458    if (!is_dir($trash_path))
459    {
460      @mkdir($trash_path);
461      $file = @fopen($trash_path . '/.htaccess', 'w');
462      @fwrite($file, 'deny from all');
463      @fclose($file);
464    }
465    while ($r = $trash_path . '/' . md5(uniqid(rand(), true)))
466    {
467      if (!is_dir($r))
468      {
469        @rename($path, $r);
470        break;
471      }
472    }
473  }
474}
475?>
Note: See TracBrowser for help on using the repository browser.