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

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

feature:2210
Update language from piwigo.org extension repository

  • Property svn:eol-style set to LF
File size: 14.2 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->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_update', l10n('Check for updates'), $link.'languages_update');
51    $tabsheet->add('languages_new', l10n('Add New Language'), $link.'languages_new');
52    $tabsheet->select($selected);
53    $tabsheet->assign();
54  }
55
56  /**
57   * Perform requested actions
58   * @param string - action
59   * @param string - language id
60   * @param array - errors
61   */
62  function perform_action($action, $language_id)
63  {
64    global $conf;
65
66    if (isset($this->db_languages[$language_id]))
67    {
68      $crt_db_language = $this->db_languages[$language_id];
69    }
70
71    $errors = array();
72
73    switch ($action)
74    {
75      case 'activate':
76        if (isset($crt_db_language))
77        {
78          array_push($errors, 'CANNOT ACTIVATE - LANGUAGE IS ALREADY ACTIVATED');
79          break;
80        }
81
82        $query = '
83INSERT INTO '.LANGUAGES_TABLE.'
84  (id, version, name)
85  VALUES(\''.$language_id.'\',
86         \''.$this->fs_languages[$language_id]['version'].'\',
87         \''.$this->fs_languages[$language_id]['name'].'\')
88;';
89        pwg_query($query);
90        break;
91
92      case 'deactivate':
93        if (!isset($crt_db_language))
94        {
95          array_push($errors, 'CANNOT DEACTIVATE - LANGUAGE IS ALREADY DEACTIVATED');
96          break;
97        }
98
99        if ($language_id == get_default_language())
100        {
101          array_push($errors, 'CANNOT DEACTIVATE - LANGUAGE IS DEFAULT LANGUAGE');
102          break;
103        }
104
105        $query = '
106DELETE
107  FROM '.LANGUAGES_TABLE.'
108  WHERE id= \''.$language_id.'\'
109;';
110        pwg_query($query);
111        break;
112
113      case 'delete':
114        if (!empty($crt_db_language))
115        {
116          array_push($errors, 'CANNOT DELETE - LANGUAGE IS ACTIVATED');
117          break;
118        }
119        if (!isset($this->fs_languages[$language_id]))
120        {
121          array_push($errors, 'CANNOT DELETE - LANGUAGE DOES NOT EXIST');
122          break;
123        }
124
125        // Set default language to user who are using this language
126        $query = '
127UPDATE '.USER_INFOS_TABLE.'
128  SET language = \''.get_default_language().'\'
129  WHERE language = \''.$language_id.'\'
130;';
131        pwg_query($query);
132
133        if (!$this->deltree(PHPWG_ROOT_PATH.'language/'.$language_id))
134        {
135          $this->send_to_trash(PHPWG_ROOT_PATH.'language/'.$language_id);
136        }
137        break;
138
139      case 'set_default':
140        $query = '
141UPDATE '.USER_INFOS_TABLE.'
142  SET language = \''.$language_id.'\'
143  WHERE user_id = '.$conf['default_user_id'].'
144;';
145        pwg_query($query);
146        break;
147    }
148    return $errors;
149  }
150
151  /**
152  *  Get languages defined in the language directory
153  */
154  function get_fs_languages($target_charset = null)
155  {
156    if ( empty($target_charset) )
157    {
158      $target_charset = get_pwg_charset();
159    }
160    $target_charset = strtolower($target_charset);
161
162    $dir = opendir(PHPWG_ROOT_PATH.'language');
163    while ($file = readdir($dir))
164    {
165      if ($file!='.' and $file!='..')
166      {
167        $path = PHPWG_ROOT_PATH.'language/'.$file;
168        if (is_dir($path) and !is_link($path)
169            and preg_match('/^[a-zA-Z0-9-_]+$/', $file )
170            and file_exists($path.'/common.lang.php')
171            )
172        {
173          $language = array(
174              'name'=>$file,
175              'code'=>$file,
176              'version'=>'0',
177              'uri'=>'',
178              'author'=>'',
179            );
180          $plg_data = implode( '', file($path.'/common.lang.php') );
181
182          if ( preg_match("|Language Name: (.*)|", $plg_data, $val) )
183          {
184            $language['name'] = trim( $val[1] );
185            $language['name'] = convert_charset($language['name'], 'utf-8', $target_charset);
186          }
187          if (preg_match("|Version: (.*)|", $plg_data, $val))
188          {
189            $language['version'] = trim($val[1]);
190          }
191          if ( preg_match("|Language URI: (.*)|", $plg_data, $val) )
192          {
193            $language['uri'] = trim($val[1]);
194          }
195          if ( preg_match("|Author: (.*)|", $plg_data, $val) )
196          {
197            $language['author'] = trim($val[1]);
198          }
199          if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
200          {
201            $language['author uri'] = trim($val[1]);
202          }
203          if (!empty($language['uri']) and strpos($language['uri'] , 'extension_view.php?eid='))
204          {
205            list( , $extension) = explode('extension_view.php?eid=', $language['uri']);
206            if (is_numeric($extension)) $language['extension'] = $extension;
207          }
208          // IMPORTANT SECURITY !
209          $language = array_map('htmlspecialchars', $language);
210          $this->fs_languages[$file] = $language;
211        }
212      }
213    }
214    closedir($dir);
215    @uasort($this->fs_languages, 'name_compare');
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      'get_nb_downloads' => 'true',
286      )
287    );
288    if (!empty($languages_to_check))
289    {
290      if ($new)
291      {
292        $get_data['extension_exclude'] = implode(',', $languages_to_check);
293      }
294      else
295      {
296        $get_data['extension_include'] = implode(',', $languages_to_check);
297      }
298    }
299
300    if (fetchRemote($url, $result, $get_data))
301    {
302      $pem_languages = @unserialize($result);
303      if (!is_array($pem_languages))
304      {
305        return false;
306      }
307      foreach ($pem_languages as $language)
308      {
309        if (preg_match('/^.*? \[[A-Z]{2}\]$/', $language['extension_name']))
310        {
311          $this->server_languages[$language['extension_id']] = $language;
312        }
313      }
314      @uasort($this->server_languages, array($this, 'extension_name_compare'));
315      return true;
316    }
317    return false;
318  }
319
320  /**
321   * Extract language files from archive
322   *
323   * @param string - install or upgrade
324   * @param string - remote revision identifier (numeric)
325   * @param string - language id or extension id
326   */
327  function extract_language_files($action, $revision, $dest='')
328  {
329    if ($archive = tempnam( PHPWG_ROOT_PATH.'language', 'zip'))
330    {
331      $url = PEM_URL . '/download.php';
332      $get_data = array(
333        'rid' => $revision,
334        'origin' => 'piwigo_'.$action,
335      );
336
337      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
338      {
339        fclose($handle);
340        include(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
341        $zip = new PclZip($archive);
342        if ($list = $zip->listContent())
343        {
344          foreach ($list as $file)
345          {
346            // we search common.lang.php in archive
347            if (basename($file['filename']) == 'common.lang.php'
348              and (!isset($main_filepath)
349              or strlen($file['filename']) < strlen($main_filepath)))
350            {
351              $main_filepath = $file['filename'];
352            }
353          }
354          if (isset($main_filepath))
355          {
356            $root = basename(dirname($main_filepath)); // common.lang.php path in archive
357            if (preg_match('/^[a-z]{2}_[A-Z]{2}$/', $root))
358            {
359              if ($action == 'install')
360              {
361                $dest = $root;
362              }
363              $extract_path = PHPWG_ROOT_PATH.'language/'.$dest;
364              if (
365                $result = $zip->extract(
366                  PCLZIP_OPT_PATH, $extract_path,
367                  PCLZIP_OPT_REMOVE_PATH, $root,
368                  PCLZIP_OPT_REPLACE_NEWER
369                  )
370                )
371              {
372                foreach ($result as $file)
373                {
374                  if ($file['stored_filename'] == $main_filepath)
375                  {
376                    $status = $file['status'];
377                    break;
378                  }
379                }
380                if ($status == 'ok')
381                {
382                  $this->get_fs_languages();
383                  if ($action == 'install')
384                  {
385                    $this->perform_action('activate', $dest);
386                  }
387                }
388                if (file_exists($extract_path.'/obsolete.list')
389                  and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
390                  and !empty($old_files))
391                {
392                  array_push($old_files, 'obsolete.list');
393                  foreach($old_files as $old_file)
394                  {
395                    $path = $extract_path.'/'.$old_file;
396                    if (is_file($path))
397                    {
398                      @unlink($path);
399                    }
400                    elseif (is_dir($path))
401                    {
402                      if (!$this->deltree($path))
403                      {
404                        $this->send_to_trash($path);
405                      }
406                    }
407                  }
408                }
409              }
410              else $status = 'extract_error';
411            }
412            else $status = 'archive_error';
413          }
414          else $status = 'archive_error';
415        }
416        else $status = 'archive_error';
417      }
418      else $status = 'dl_archive_error';
419    }
420    else $status = 'temp_path_error';
421
422    @unlink($archive);
423    return $status;
424  }
425
426  /**
427   * delete $path directory
428   * @param string - path
429   */
430  function deltree($path)
431  {
432    if (is_dir($path))
433    {
434      $fh = opendir($path);
435      while ($file = readdir($fh))
436      {
437        if ($file != '.' and $file != '..')
438        {
439          $pathfile = $path . '/' . $file;
440          if (is_dir($pathfile))
441          {
442            $this->deltree($pathfile);
443          }
444          else
445          {
446            @unlink($pathfile);
447          }
448        }
449      }
450      closedir($fh);
451      return @rmdir($path);
452    }
453  }
454
455  /**
456   * send $path to trash directory
457   * @param string - path
458   */
459  function send_to_trash($path)
460  {
461    $trash_path = PHPWG_ROOT_PATH . 'language/trash';
462    if (!is_dir($trash_path))
463    {
464      @mkdir($trash_path);
465      $file = @fopen($trash_path . '/.htaccess', 'w');
466      @fwrite($file, 'deny from all');
467      @fclose($file);
468    }
469    while ($r = $trash_path . '/' . md5(uniqid(rand(), true)))
470    {
471      if (!is_dir($r))
472      {
473        @rename($path, $r);
474        break;
475      }
476    }
477  }
478
479  /**
480   * Sort functions
481   */
482  function language_version_compare($a, $b)
483  {
484    $pattern = array('/([a-z])/ei', '/\.+/', '/\.\Z|\A\./');
485    $replacement = array( "'.'.intval('\\1', 36).'.'", '.', '');
486
487    $array = preg_replace($pattern, $replacement, array($a, $b));
488
489    return version_compare($array[0], $array[1], '>=');
490  }
491
492  function extension_name_compare($a, $b)
493  {
494    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
495  }
496}
497?>
Note: See TracBrowser for help on using the repository browser.