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");
13 include_once($path_to_root. "/includes/remote_url.inc");
14 include_once($path_to_root. "/includes/hooks.inc");
16 define('PKG_CACHE_PATH', $path_to_root.'/modules/_cache');
17 define('PUBKEY_PATH', $path_to_root);
18 define('REPO_URL', 'http://'.$repo_auth['login'].':'.$repo_auth['pass'].'@'.$repo_auth['host'].'/'.$repo_auth['branch']);
20 // FrontAccounting package class
22 class package extends gzip_file {
23 function package($filename, $basedir=null)
28 $basedir = PKG_CACHE_PATH.'/'.substr(basename($filename), 0, -4);
29 if (file_exists($basedir)) {
30 // flush_dir($basedir, true);
34 $this->archive($filename);
35 $this->set_options(array('basedir'=> $basedir));
36 $this->options['type'] = "pkg";
39 // Used by archive class. Use create_archive() instead.
43 return $this->create_gzip();
46 // Install package and clean temp directory.
54 $this->set_options(array('overwrite' => 1));
55 $this->extract_files(); // extract package in cache directory
56 $cachepath = $this->options['basedir'];
57 $ctrl = get_control_file("$cachepath/_init/config");
59 $targetdir = $path_to_root.'/'.$ctrl['InstallPath'];
61 if (!is_dir($targetdir))
64 $dpackage = new package("$cachepath/_data", $targetdir);
65 $dpackage->set_options(array('overwrite' => 1));
67 $flist = $dpackage->extract_files(true);
68 if (count($dpackage->error)) {
69 $this->error = array_merge($this->error, $dpackage->error);
72 copy_files($flist, $targetdir, "$cachepath/_back");
74 $dpackage->extract_files(); //install package in target directory
76 $install = hook_invoke($ctrl['Package'], 'install_extension', $dummy);
77 $success &= $install===null || $install;
78 $success &= count($dpackage->error) == 0;
79 $this->error = array_merge($this->error, $dpackage->error);
83 // Removing package related sources
91 $cachepath = $this->options['basedir'];
92 $ctrl = get_control_file("$cachepath/_init/config");
94 $targetdir = $path_to_root.'/'.$ctrl['InstallPath'];
96 $dpackage = new package("$cachepath/_data", $targetdir);
98 $flist = $dpackage->extract_files(true);
100 $success &= copy_files($flist, "$cachepath/_back", $targetdir, true);
102 if (strpos($ctrl['InstallPath'], 'modules/') === 0) { // flush module directory
103 flush_dir($targetdir, true);
107 $uninstall = hook_invoke($ctrl['Package'], 'uninstall_extension', $dummy);
108 $success &= $uninstall===null || $uninstall;
113 // Purge all package related configuration and data.
122 // Changes field value read from control file (single, or multiline) into
123 // arrays of subfields if needed.
125 function ufmt_property($key, $value)
127 // indexes used in output arrays
129 // 'MenuTabs' => array('url', 'access', 'tab_id', 'title', 'section'),
130 // 'MenuEntries' => array('url', 'access', 'tab_id', 'title'),
132 if (!isset($sub_fields[$key]))
133 return $value==='' ? null : $value;
137 if (!is_array($value))
138 $value = array($value);
139 foreach($value as $line) {
140 $indexes = $sub_fields[$key];
142 preg_match_all('/(["])(?:\\\\?+.)*?\1|[^"\s][\S]*/', $line, $match);
143 foreach($match[0] as $n => $subf) {
145 $val = strtr(substr($subf, 1, -1),
150 $ret[array_shift($indexes)] = $val;
159 //=============================================================================
161 // Retrieve control file and return as associative array
162 // $index is name of field used as key in result array, or null for numeric keys
164 function get_control_file($file, $index = false) {
166 $list = gzopen($file, 'rb');
167 if (!$list) return null;
169 $repo = $pkg = array();
170 $key = false; $value = '';
173 $line = rtrim($line);
174 if ($line && ctype_space($line[0])) { // continuation of multiline property
175 if (strlen(ltrim($line))) {
176 if ($value !== '' && !is_array($value))
177 $value = array($value);
178 $value[] = ltrim($line);
182 if ($key) { // save previous property if any
183 $pkg[$key] = ufmt_property($key, $value);
185 if (!strlen($line)) { // end of section
187 if ($index !== true) {
188 if ($index === false) break;
189 if (!isset($pkg[$index])) {
190 display_error(_("No key field '$index' in file '$file'"));
193 $repo[$pkg[$index]] = $pkg;
198 $key = null; $value = '';
200 } elseif (preg_match('/([^:]*):\s*(.*)/', $line, $m)) {
201 $key = $m[1]; $value = $m[2];
203 display_error("Empty key in line $line");
207 display_error("File parse error in line $line");
211 } while ((($line = fgets($list))!==false) || $key);
214 return $index === false ? $pkg : $repo;
217 // Save configuration data to control file.
219 function save_control_file($fname, $list, $zip=false)
221 $file = $zip ? gzopen($fname, 'wb') : fopen($fname, 'wb');
222 foreach($list as $section) {
223 foreach($section as $key => $value) {
224 if (is_array($value)) { // multiline value
225 if (is_array(reset($value))) { // lines have subfields
226 foreach($value as $i => $line) {
227 // Subfields containing white spaces or double quotes are doublequoted
228 // with " escaped with backslash.
229 foreach($line as $n => $subfield)
230 if (preg_match('/[\s"]/', $subfield)) {
232 '"'.strtr($subfield, array('"'=>'\\"')).'"';
234 // Subfields are separated by white space.
235 $value[$i] = implode(' ', $value[$i]);
238 // array elements on subsequent lines starting with white space
239 $value = implode("\n ", $value);
241 $zip ? gzwrite($file, "$key: $value\n") : fwrite($file, "$key: $value\n");
243 $zip ? gzwrite($file, "\n"): fwrite($file, "\n");
245 $zip ? gzclose($file) : fclose($file);
248 // Retrieve text field in localized version or default one
249 // when the localized is not avaialable.
251 function pkg_prop($pkg, $property, $lang=false)
254 if ($lang && isset($pkg[$property.'-'.user_language()]))
255 $prop = @$pkg[$pname];
257 $prop = @$pkg[$property];
259 return is_array($prop) ? implode("\n ",$prop): $prop;
262 // Retrieve list of packages from repository and return as table ($pkgname==null),
263 // or find $pkgname package in repository and optionaly download
265 // $type is type/s of package
266 // $filter is optional field selection array in form field=>newkey
267 // or (0=>field1, 1=>field2...)
268 // $outkey - field used as a key in package list. If null 'Package' field is used.
270 function get_pkg_or_list($type = null, $pkgname = null, $filter=array(), $outkey=null, $download=true) {
272 global $path_to_root, $repo_auth;
274 // first download local copy of repo release file
275 // and check remote signature with local copy of public key
277 $loclist = PKG_CACHE_PATH.'/Release.gz';
279 if (isset($type) && !is_array($type)) {
280 $type = array($type);
284 if (!file_exists($loclist)) {
285 url_copy(REPO_URL.'/Release.gz', $loclist);
288 $sig = url_get_contents(REPO_URL.'/Release.sig');
289 $data = file_get_contents($loclist);
290 $cert = file_get_contents(PUBKEY_PATH.'/FA.pem');
291 if (!openssl_verify($data, $sig, $cert)) {
295 display_error(_('Release file in repository is invalid, or public key is outdated.'));
302 $Release = get_control_file($loclist, 'Filename');
303 // download and check all indexes containing given package types
304 // then complete package list or seek for pkg
306 foreach($Release as $fname => $parms) {
307 if ($type && !count(array_intersect(explode(' ', $parms['Type']), $type))) {
308 unset($Release[$fname]); continue; // no packages of selected type in this index
310 if ($Release[$fname]['Version'] != $repo_auth['branch']) {
311 display_warning(_('Repository version does not match application version.')); // ?
313 $remoteindex = REPO_URL.'/'.$fname;
314 $locindex = PKG_CACHE_PATH.'/'.$fname;
317 if (!file_exists($locindex)) {
318 url_copy($remoteindex, $locindex);
321 if ($parms['SHA1sum'] != sha1_file($locindex)) { // check subdir index consistency
325 display_error(sprintf( _("Security alert: broken index file in repository '%s'. Please inform repository administrator about this issue."),
333 // scan subdir list and select packages of given type
334 $pkglist = get_control_file($locindex, 'Package');
335 foreach($pkglist as $name => $pkg) {
336 $pkgfullname = REPO_URL.'/'.$parms['Path']."/".$pkg['Filename'].'.pkg';
337 if (!isset($type) || in_array($pkg['Type'], $type)) {
341 foreach($filter as $field => $key) {
342 if (is_numeric($field))
343 $p[$field] = @$pkg[$field];
345 $p[$key] = @$pkg[$field];
348 if ($pkgname == null) {
349 $Packages[$outkey ? $outkey : $name] = $p;
350 } elseif ($pkgname == $pkg['Package']) {
351 //download package to temp directory
353 $locname = "$path_to_root/tmp/".$pkg['Filename'].'.pkg';
354 url_copy($pkgfullname, $locname);
355 // checking sha1 hash is expensive proces, so chekc the package
356 // consistency just before downloading
357 if ($pkg['SHA1sum'] != sha1_file($locname)) {
358 display_error(sprintf( _("Security alert: broken package '%s' in repository. Please inform repository administrator about this issue."),
372 function get_package($pkgname, $type = null)
374 return get_pkg_or_list($type, $pkgname);
377 Returns full name of installed package, or null if package is not installed.
379 function installed_package($package)
381 $cache = opendir(PKG_CACHE_PATH);
383 while ($file = @readdir($cache)) {
384 if (!is_dir(PKG_CACHE_PATH.'/'.$file))
386 if (strpos($file, $package.'-') === 0)
394 Remove package from system
396 function uninstall_package($name)
398 $name = installed_package($name);
399 if (!$name) return true; // not installed
400 $pkg = new package($name.'.pkg');
403 flush_dir(PKG_CACHE_PATH.'/'.$name, true);
404 rmdir(PKG_CACHE_PATH.'/'.$name);
406 return count($pkg->error)==0;
409 //---------------------------------------------------------------------------------------
411 // Return merged list of available and installed languages in inform of local
412 // configuration array supplemented with installed versions information.
414 function get_languages_list()
416 global $installed_languages;
418 $pkgs = get_pkg_or_list('language', null, array(
419 'Package' => 'package',
420 'Version' => 'available',
422 'Language' => 'code',
423 'Encoding' => 'encoding',
425 'Description' => 'Descr',
426 'InstallPath' => 'path'
429 // add/update languages already installed
431 foreach($installed_languages as $id => $l) {
432 $list = array_search_keys($l['code'], $pkgs, 'code'); // get all packages with this code
433 foreach ($list as $name) {
434 if ($l['encoding'] == $pkgs[$name]['encoding']) { // if the same encoding
435 $pkgs[$name]['version'] = @$l['version']; // set installed version
436 $pkgs[$name]['local_id'] = $id; // index in installed_languages
440 $l['local_id'] = $id;
441 if (!isset($l['package']) || $l['package'] == '' || !isset($pkgs[$l['package']]))
444 $pkgs[$l['package']] = array_merge($pkgs[$l['package']], $l);
449 //---------------------------------------------------------------------------------------
451 // Return merged list of available and installed extensions as a local
452 // configuration array supplemented with installed versions information.
454 function get_extensions_list($type = null)
456 global $path_to_root;
458 if (isset($type) || !is_array($type)) {
459 $type = array($type);
462 $pkgs = get_pkg_or_list($type, null, array(
463 'Package' => 'package',
464 'Version' => 'available',
466 'Description' => 'Descr',
468 'DefaultStatus'=> 'active',
469 // 'MenuTabs' => 'tabs',
470 // 'MenuEntries' => 'entries',
471 'Encoding' => 'encoding',
472 // 'AccessExtensions' => 'acc_file',
473 'InstallPath' => 'path'
476 // lookup for local extensions
477 $path = $path_to_root.'/modules/';
479 $moddir = opendir($path);
481 while(false != ($fname = readdir($moddir)))
483 if(!in_array($fname, array('.','..','CVS','_cache')) && is_dir($path.$fname))
485 if (!isset($pkgs[$fname]))
486 $pkgs[$fname] = array(
491 'type' => 'extension',
492 'path' => 'modules/'.$fname,
498 // add/update extensions already installed
500 $installed = get_company_extensions();
501 foreach($installed as $extno => $ext) {
502 if (!in_array($ext['type'], $type)) continue;
503 $ext['local_id'] = $extno;
504 // if (!isset($pkgs[$ext['package']]) || $ext['package'] == '')
507 $pkgs[$ext['package']] = array_merge($pkgs[$ext['package']], $ext);
513 // Return merged list of available and installed extensions as a local
514 // configuration array supplemented with installed versions information.
516 function get_themes_list()
518 $pkgs = get_pkg_or_list('theme', null, array(
519 'Package' => 'package',
520 'Version' => 'available',
522 'Description' => 'Descr'
525 // add/update extensions already installed
527 $local = get_company_extensions();
529 foreach($local as $extno => $ext) {
530 if (isset($pkgs[@$ext['package']])) {
531 $ext['local_id'] = $extno;
532 $pkgs[$ext['package']] = array_merge($pkgs[$ext['package']], $ext);
535 // TODO: Add other themes from themes directory
540 //---------------------------------------------------------------------------------------
542 // Return merged list of available and installed COAs as a local
543 // configuration array supplemented with installed versions information.
545 function get_charts_list()
547 $pkgs = get_pkg_or_list('chart', null, array(
548 'Package' => 'package',
549 'Version' => 'available',
551 'Description' => 'Descr',
553 'InstallPath' => 'path',
554 'Encoding' => 'encoding',
558 // add/update default charts
560 $local = get_company_extensions();
562 foreach($local as $extno => $ext) {
563 if ($ext['type'] != 'chart') continue;
564 $ext['local_id'] = $extno;
565 if (!isset($pkgs[$ext['package']]) || $ext['package'] == '')
568 $pkgs[$ext['package']] = array_merge($pkgs[$ext['package']], $ext);
573 //---------------------------------------------------------------------------------------------
574 // Install/update package from repository
576 function install_language($pkg_name)
578 global $path_to_root, $installed_languages, $Ajax;
580 $pkg = get_pkg_or_list('language', $pkg_name);
583 $i = array_search_key($pkg['Language'], $installed_languages, 'code');
585 $i = count($installed_languages);
586 else { // remove another already installed package for this language
587 $old_pkg = @$installed_languages[$i]['package'];
588 if ($old_pkg && ($pkg['Package'] != $old_pkg))
589 uninstall_package($old_pkg);
592 $package = new package("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
593 if ($package->install()) {
595 'name' => $pkg['Name'],
596 'package' => $pkg['Package'],
597 'code' => $pkg['Language'],
598 'encoding' => $pkg['Encoding'],
599 'version' => $pkg['Version'],
600 'path' => $pkg['InstallPath']
602 if ($pkg['RTLDir']=='yes')
604 $installed_languages[$i] = $lang;
605 write_lang($installed_languages);
606 unlink("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
607 $Ajax->activate('lang_tbl');
609 display_error(implode('<br>', $package->error));
613 display_error(sprintf(_("Package '%s' not found."), $pkg_name));
618 //---------------------------------------------------------------------------------------------
619 // Install/update extension or theme package from repository
621 function install_extension($pkg_name)
623 global $path_to_root, $installed_extensions, $next_extension_id, $Ajax;
625 $pkg = get_pkg_or_list(array('extension', 'theme', 'chart'), $pkg_name);
627 $package = new package("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
628 $local_exts = get_company_extensions();
629 if ($package->install()) {
630 $ext_id = array_search_key($pkg['Package'], $local_exts, 'package');
631 if ($ext_id === null)
632 $ext_id = $next_extension_id++;
633 else { // remove another already installed package for this language
634 $old_pkg = $installed_extensions[$ext_id]['package'];
636 uninstall_package($old_pkg);
639 'name' => $pkg['Name'],
640 'package' => $pkg['Package'],
641 'version' => $pkg['Version'],
642 'type' => $pkg['Type'],
644 'path' => $pkg['InstallPath'],
646 // if (isset($pkg['MenuTabs']))
647 // $ext['tabs'] = $pkg['MenuTabs'];
648 // if (isset($pkg['MenuEntries']))
649 // $ext['entries'] = $pkg['MenuEntries'];
650 // if (isset($pkg['AccessExtensions']))
651 // $ext['acc_file'] = $pkg['AccessExtensions'];
652 if (isset($pkg['SqlScript']))
653 $ext['sql'] = $pkg['SqlScript'];
654 $local_exts[$ext_id] = $ext;
655 $ret = update_extensions($local_exts);
656 unlink("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
657 $Ajax->activate('ext_tbl');
660 display_error(implode('<br>', $package->error));
664 display_error(sprintf(_("Package '%s' not found."), $pkg_name));
670 Returns true if newer package version is available
672 function check_pkg_upgrade($current, $available)
674 preg_match_all('/[\d]+/', $available, $aver);
675 if (!count($aver[0]))
677 preg_match_all('/[\d]+/', $current, $cver);
678 if (!count($cver[0]))
680 foreach($aver[0] as $n => $ver)
681 if ($ver>@$cver[0][$n])
687 // Returns package info from index file
689 function get_package_info($pkg, $type=null, $filter=array(), $outkey=null, $download=true) {
690 return get_pkg_or_list($type, $pkg, $filter, null, false);