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

Last change on this file since 28969 was 28969, checked in by mistic100, 10 years ago

improves regexes parsing plugins metadata

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