2 /**********************************************************************
3 Copyright (C) FrontAccounting, LLC.
4 Released under the terms of the GNU General Public License, GPL,
5 as published by the Free Software Foundation, either version 3
6 of the License, or (at your option) any later version.
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 include_once($path_to_root. "/includes/archive.inc");
14 define('PKG_CACHE_PATH', $path_to_root.'/modules/_cache');
15 define('PUBKEY_PATH', $path_to_root);
16 define('REPO_URL', 'http://'.$repo_auth['login'].':'.$repo_auth['pass'].'@'.$repo_auth['host'].'/'.$repo_auth['branch']);
18 // FrontAccounting package class
20 class package extends gzip_file {
21 function package($filename, $basedir=null)
26 $basedir = PKG_CACHE_PATH.'/'.substr(basename($filename), 0, -4);
27 if (file_exists($basedir)) {
28 // flush_dir($basedir, true);
32 $this->archive($filename);
33 $this->set_options(array('basedir'=> $basedir));
34 $this->options['type'] = "pkg";
37 // Used by archive class. Use create_archive() instead.
41 return $this->create_gzip();
44 // Install package and clean temp directory.
52 $this->set_options(array('overwrite' => 1));
53 $this->extract_files(); // extract package in cache directory
54 $cachepath = $this->options['basedir'];
55 $ctrl = get_control_file("$cachepath/_init/config");
57 $targetdir = $path_to_root.'/'.$ctrl['InstallPath'];
59 if (!is_dir($targetdir))
62 $dpackage = new package("$cachepath/_data", $targetdir);
63 $dpackage->set_options(array('overwrite' => 1));
65 $flist = $dpackage->extract_files(true);
66 if (count($dpackage->error)) {
67 $this->error = array_merge($this->error, $dpackage->error);
70 copy_files($flist, $targetdir, "$cachepath/_back");
72 $dpackage->extract_files(); //install package in target directory
74 $success &= $this->support('install');
75 $success &= count($dpackage->error) == 0;
76 $this->error = array_merge($this->error, $dpackage->error);
80 // Removing package related sources
88 $cachepath = $this->options['basedir'];
89 $ctrl = get_control_file("$cachepath/_init/config");
91 $targetdir = $path_to_root.'/'.$ctrl['InstallPath'];
93 $dpackage = new package("$cachepath/_data", $targetdir);
95 $flist = $dpackage->extract_files(true);
97 $success &= copy_files($flist, "$cachepath/_back", $targetdir, true);
99 $success &= $this->support('uninstall');
104 // Purge all package related configuration and data.
112 // Call special function defined in package install class
114 function support($name, $params = null)
116 $cachepath = $this->options['basedir'];
117 if (file_exists("$cachepath/_init/init.php")) {
118 include("$cachepath/_init/init.php");
119 if (method_exists($installer, $name)) {
120 set_include_path("$cachepath/_init".PATH_SEPARATOR.get_include_path());
122 $ret = $installer->$name($params);
130 // Changes field value read from control file (single, or multiline) into
131 // arrays of subfields if needed.
133 function ufmt_property($key, $value)
135 // indexes used in output arrays
137 'MenuTabs' => array('url', 'access', 'tab_id', 'title', 'section'),
138 'MenuEntries' => array('url', 'access', 'tab_id', 'title'),
140 if (!isset($sub_fields[$key]))
141 return $value==='' ? null : $value;
145 if (!is_array($value))
146 $value = array($value);
147 foreach($value as $line) {
148 $indexes = $sub_fields[$key];
150 preg_match_all('/(["])(?:\\\\?+.)*?\1|[^"\s][\S]*/', $line, $match);
151 foreach($match[0] as $n => $subf) {
153 $val = strtr(substr($subf, 1, -1),
158 $ret[array_shift($indexes)] = $val;
167 //=============================================================================
169 // Retrieve control file and return as associative array
170 // $index is name of field used as key in result array, or null for numeric keys
172 function get_control_file($file, $index = false) {
174 $list = gzopen($file, 'rb');
175 if (!$list) return null;
177 $repo = $pkg = array();
178 $key = false; $value = '';
181 $line = rtrim($line);
182 if ($line && ctype_space($line[0])) { // continuation of multiline property
183 if (strlen(ltrim($line))) {
184 if ($value !== '' && !is_array($value))
185 $value = array($value);
186 $value[] = ltrim($line);
190 if ($key) { // save previous property if any
191 $pkg[$key] = ufmt_property($key, $value);
193 if (!strlen($line)) { // end of section
195 if ($index !== true) {
196 if ($index === false) break;
197 if (!isset($pkg[$index])) {
198 display_error(_("No key field '$index' in file '$file'"));
201 $repo[$pkg[$index]] = $pkg;
206 $key = null; $value = '';
208 } elseif (preg_match('/([^:]*):\s*(.*)/', $line, $m)) {
209 $key = $m[1]; $value = $m[2];
211 display_error("Empty key in line $line");
215 display_error("File parse error in line $line");
219 } while ((($line = fgets($list))!==false) || $key);
222 return $index === false ? $pkg : $repo;
225 // Save configuration data to control file.
227 function save_control_file($fname, $list, $zip=false)
229 $file = $zip ? gzopen($fname, 'wb') : fopen($fname, 'wb');
230 foreach($list as $section) {
231 foreach($section as $key => $value) {
232 if (is_array($value)) { // multiline value
233 if (is_array(reset($value))) { // lines have subfields
234 foreach($value as $i => $line) {
235 // Subfields containing white spaces or double quotes are doublequoted
236 // with " escaped with backslash.
237 foreach($line as $n => $subfield)
238 if (preg_match('/[\s"]/', $subfield)) {
240 '"'.strtr($subfield, array('"'=>'\\"')).'"';
242 // Subfields are separated by white space.
243 $value[$i] = implode(' ', $value[$i]);
246 // array elements on subsequent lines starting with white space
247 $value = implode("\n ", $value);
249 $zip ? gzwrite($file, "$key: $value\n") : fwrite($file, "$key: $value\n");
251 $zip ? gzwrite($file, "\n"): fwrite($file, "\n");
253 $zip ? gzclose($file) : fclose($file);
256 // Retrieve text field in localized version or default one
257 // when the localized is not avaialable.
259 function pkg_prop($pkg, $property, $lang=false)
262 if ($lang && isset($pkg[$property.'-'.user_language()]))
263 $prop = @$pkg[$pname];
265 $prop = @$pkg[$property];
267 return is_array($prop) ? implode("\n ",$prop): $prop;
270 // Retrieve list of packages from repository and return as table ($pkgname==null),
271 // or find $pkgname package in repository and optionaly download
273 // $type is type/s of package
274 // $filter is optional field selection array in form field=>newkey
275 // or (0=>field1, 1=>field2...)
276 // $outkey - field used as a key in package list. If null 'Package' field is used.
278 function get_pkg_or_list($type = null, $pkgname = null, $filter=array(), $outkey=null, $download=true) {
280 global $path_to_root, $repo_auth;
282 // first download local copy of repo release file
283 // and check remote signature with local copy of public key
285 $loclist = PKG_CACHE_PATH.'/Release.gz';
287 if ($type!=null && !is_array($type)) {
288 $type = array($type);
292 if (!file_exists($loclist)) {
293 copy(REPO_URL.'/Release.gz', $loclist);
296 $sig = file_get_contents(REPO_URL.'/Release.sig', 'rb');
297 $data = file_get_contents($loclist);
298 $cert = file_get_contents(PUBKEY_PATH.'/FA.pem');
299 if (!openssl_verify($data, $sig, $cert)) {
303 display_error(_('Release file in repository is invalid, or public key is outdated.'));
310 $Release = get_control_file($loclist, 'Filename');
312 // download and check all indexes containing given package types
313 // then complete package list or seek for pkg
315 foreach($Release as $fname => $parms) {
316 if ($type && !count(array_intersect(explode(' ', $parms['Type']), $type))) {
317 unset($Release[$fname]); continue; // no packages of selected type in this index
319 if ($Release[$fname]['Version'] != $repo_auth['branch']) {
320 display_warning(_('Repository version does not match application version.')); // ?
322 $remoteindex = REPO_URL.'/'.$fname;
323 $locindex = PKG_CACHE_PATH.'/'.$fname;
326 if (!file_exists($locindex)) {
327 copy($remoteindex, $locindex);
330 if ($parms['SHA1sum'] != sha1_file($locindex)) { // check subdir index consistency
334 display_error(sprintf( _("Security alert: broken index file in repository '%s'. Please inform repository administrator about this issue."),
342 // scan subdir list and select packages of given type
343 $pkglist = get_control_file($locindex, 'Package');
344 foreach($pkglist as $name => $pkg) {
345 $pkgfullname = REPO_URL.'/'.$parms['Path']."/".$pkg['Filename'].'.pkg';
346 if ($type==null || in_array($pkg['Type'], $type)) {
350 foreach($filter as $field => $key) {
351 if (is_numeric($field))
352 $p[$field] = @$pkg[$field];
354 $p[$key] = @$pkg[$field];
357 if ($pkgname == null) {
358 $Packages[$outkey ? $outkey : $name] = $p;
359 } elseif ($pkgname == $pkg['Package']) {
360 //download package to temp directory
362 $locname = "$path_to_root/tmp/".$pkg['Filename'].'.pkg';
363 copy($pkgfullname, $locname);
364 // checking sha1 hash is expensive proces, so chekc the package
365 // consistency just before downloading
366 if ($pkg['SHA1sum'] != sha1_file($locname)) {
367 display_error(sprintf( _("Security alert: broken package '%s' in repository. Please inform repository administrator about this issue."),
381 function get_package($pkgname, $type = null)
383 return get_pkg_or_list($type, $pkgname);
386 Returns full name of installed package, or null if package is not installed.
388 function installed_package($package)
390 $cache = opendir(PKG_CACHE_PATH);
392 while ($file = @readdir($cache)) {
393 if (!is_dir(PKG_CACHE_PATH.'/'.$file))
395 if (strpos($file, $package.'-') === 0)
403 Remove package from system
405 function uninstall_package($name)
407 $name = installed_package($name);
408 if (!$name) return true; // not installed
409 $pkg = new package($name.'.pkg');
412 flush_dir(PKG_CACHE_PATH.'/'.$name, true);
413 rmdir(PKG_CACHE_PATH.'/'.$name);
415 return count($pkg->error)==0;
418 //---------------------------------------------------------------------------------------
420 // Return merged list of available and installed languages in inform of local
421 // configuration array supplemented with installed versions information.
423 function get_languages_list()
425 global $installed_languages;
427 $pkgs = get_pkg_or_list('language', null, array(
428 'Package' => 'package',
429 'Version' => 'available',
431 'Language' => 'code',
432 'Encoding' => 'encoding',
434 'Description' => 'Descr',
435 'InstallPath' => 'path'
438 // add/update languages already installed
440 foreach($installed_languages as $id => $l) {
441 $list = array_search_keys($l['code'], $pkgs, 'code'); // get all packages with this code
442 foreach ($list as $name) {
443 if ($l['encoding'] == $pkgs[$name]['encoding']) { // if the same encoding
444 $pkgs[$name]['version'] = @$l['version']; // set installed version
445 $pkgs[$name]['local_id'] = $id; // index in installed_languages
449 $l['local_id'] = $id;
450 if (!isset($l['package']) || $l['package'] == '' || !isset($pkgs[$l['package']]))
453 $pkgs[$l['package']] = array_merge($pkgs[$l['package']], $l);
458 //---------------------------------------------------------------------------------------
460 // Return merged list of available and installed extensions as a local
461 // configuration array supplemented with installed versions information.
463 function get_extensions_list()
465 $pkgs = get_pkg_or_list('extension', null, array(
466 'Package' => 'package',
467 'Version' => 'available',
469 'Description' => 'Descr',
471 'DefaultStatus'=> 'active',
472 'MenuTabs' => 'tabs',
473 'MenuEntries' => 'entries',
474 'AccessExtensions' => 'acc_file',
475 'InstallPath' => 'path'
478 // add/update extensions already installed
480 $local = get_company_extensions();
481 foreach($local as $extno => $ext) {
482 if ($ext['type'] != 'extension') continue;
483 $ext['local_id'] = $extno;
484 if (!isset($pkgs[$ext['package']]) || $ext['package'] == '')
487 $pkgs[$ext['package']] = array_merge($pkgs[$ext['package']], $ext);
493 // Return merged list of available and installed extensions as a local
494 // configuration array supplemented with installed versions information.
496 function get_themes_list()
498 $pkgs = get_pkg_or_list('theme', null, array(
499 'Package' => 'package',
500 'Version' => 'available',
502 'Description' => 'Descr'
505 // add/update extensions already installed
507 $local = get_company_extensions();
509 foreach($local as $extno => $ext) {
510 if (isset($pkgs[@$ext['package']])) {
511 $ext['local_id'] = $extno;
512 $pkgs[$ext['package']] = array_merge($pkgs[$ext['package']], $ext);
515 // TODO: Add other themes from themes directory
520 //---------------------------------------------------------------------------------------
522 // Return merged list of available and installed COAs as a local
523 // configuration array supplemented with installed versions information.
525 function get_charts_list()
527 $pkgs = get_pkg_or_list('chart', null, array(
528 'Package' => 'package',
529 'Version' => 'available',
531 'Description' => 'Descr',
533 'InstallPath' => 'path',
537 // add/update default charts
539 $local = get_company_extensions();
541 foreach($local as $extno => $ext) {
542 if ($ext['type'] != 'chart') continue;
543 $ext['local_id'] = $extno;
544 if (!isset($pkgs[$ext['package']]) || $ext['package'] == '')
547 $pkgs[$ext['package']] = array_merge($pkgs[$ext['package']], $ext);
552 //---------------------------------------------------------------------------------------------
553 // Install/update package from repository
555 function install_language($pkg_name)
557 global $path_to_root, $installed_languages, $Ajax;
559 $pkg = get_pkg_or_list('language', $pkg_name);
562 $i = array_search_key($pkg['Language'], $installed_languages, 'code');
564 $i = count($installed_languages);
565 else { // remove another already installed package for this language
566 $old_pkg = @$installed_languages[$i]['package'];
567 if ($old_pkg && ($pkg['Package'] != $old_pkg))
568 uninstall_package($old_pkg);
571 $package = new package("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
572 if ($package->install()) {
574 'name' => $pkg['Name'],
575 'package' => $pkg['Package'],
576 'code' => $pkg['Language'],
577 'encoding' => $pkg['Encoding'],
578 'version' => $pkg['Version'],
579 'path' => $pkg['InstallPath']
581 if ($pkg['RTLDir']=='yes')
583 $installed_languages[$i] = $lang;
584 write_lang($installed_languages);
585 unlink("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
586 $Ajax->activate('lang_tbl');
592 //---------------------------------------------------------------------------------------------
593 // Install/update extension or theme package from repository
595 function install_extension($pkg_name)
597 global $path_to_root, $next_extension_id, $Ajax;
599 $pkg = get_pkg_or_list(array('extension', 'theme', 'chart'), $pkg_name);
601 $package = new package("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
602 $local_exts = get_company_extensions();
603 if ($package->install()) {
604 $ext_id = array_search_key($pkg['Package'], $local_exts, 'package');
605 if ($ext_id === null)
606 $ext_id = $next_extension_id++;
608 'name' => $pkg['Name'],
609 'package' => $pkg['Package'],
610 'version' => $pkg['Version'],
611 'type' => $pkg['Type'],
613 'path' => $pkg['InstallPath'],
615 if (isset($pkg['MenuTabs']))
616 $ext['tabs'] = $pkg['MenuTabs'];
617 if (isset($pkg['MenuEntries']))
618 $ext['entries'] = $pkg['MenuEntries'];
619 if (isset($pkg['AccessExtensions']))
620 $ext['acc_file'] = $pkg['AccessExtensions'];
621 if (isset($pkg['SqlScript']))
622 $ext['sql'] = $pkg['SqlScript'];
623 $local_exts[$ext_id] = $ext;
624 $ret = update_extensions($local_exts);
625 unlink("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
626 $Ajax->activate('ext_tbl');
629 display_error(implode('<br>', $package->error));
636 Returns true if newer package version is available
638 function check_pkg_upgrade($current, $available)
640 preg_match_all('/[\d]+/', $available, $aver);
641 if (!count($aver[0]))
643 preg_match_all('/[\d]+/', $current, $cver);
644 if (!count($cver[0]))
646 foreach($aver[0] as $n => $ver)
647 if ($ver>@$cver[0][$n])
653 // Returns package info from index file
655 function get_package_info($pkg, $type=null, $filter=array(), $outkey=null, $download=true) {
656 return get_pkg_or_list($type, $pkg, $filter, null, false);