Additional error messages.
[fa-stable.git] / includes / packages.inc
1 <?php
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
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']);
17 //
18 // FrontAccounting package class
19 //
20 class package extends gzip_file {
21         function package($filename, $basedir=null)
22         {
23                 global $path_to_root;
24
25                 if (!$basedir) {
26                         $basedir = PKG_CACHE_PATH.'/'.substr(basename($filename), 0, -4);
27                         if (file_exists($basedir)) {
28 //                              flush_dir($basedir, true); 
29                         } else
30                         mkdir($basedir);
31                 }
32                 $this->archive($filename);
33                 $this->set_options(array('basedir'=> $basedir));
34                 $this->options['type'] = "pkg";
35         }
36         //
37         //      Used by archive class. Use create_archive() instead.
38         //      
39         function create_pkg() 
40         {
41                 return $this->create_gzip();
42         }
43         //
44         //      Install package and clean temp directory.
45         //
46         function install()
47         {
48                 global $path_to_root;
49                 
50                 $success = true;
51
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");
56
57                 $targetdir = $path_to_root.'/'.$ctrl['InstallPath'];
58
59                 if (!is_dir($targetdir))
60                         mkdir($targetdir);
61
62                 $dpackage = new package("$cachepath/_data", $targetdir);
63                 $dpackage->set_options(array('overwrite' => 1));
64
65                 $flist = $dpackage->extract_files(true);
66                 if (count($dpackage->error)) {
67                         $this->error = array_merge($this->error, $dpackage->error);
68                         return false;
69                 }
70                 copy_files($flist, $targetdir, "$cachepath/_back");
71         
72                 $dpackage->extract_files(); //install package in target directory
73
74                 $success &= $this->support('install');
75                 $success &= count($dpackage->error) == 0;
76                 $this->error = array_merge($this->error, $dpackage->error);
77                 return $success;
78         }
79         //
80         //      Removing package related sources
81         //
82         function uninstall()
83         {
84                 global $path_to_root;
85
86                 $success = true;
87
88                 $cachepath = $this->options['basedir'];
89                 $ctrl = get_control_file("$cachepath/_init/config");
90
91                 $targetdir = $path_to_root.'/'.$ctrl['InstallPath'];
92
93                 $dpackage = new package("$cachepath/_data", $targetdir);
94
95                 $flist = $dpackage->extract_files(true);
96
97                 $success &= copy_files($flist, "$cachepath/_back", $targetdir, true);
98
99                 $success &= $this->support('uninstall');
100
101                 return $success;
102         }
103         //
104         //      Purge all package related configuration and data.
105         //
106         function purge()
107         {
108                 return true;
109         }
110
111         //
112         //      Call special function defined in package install class
113         //
114         function support($name, $params = null)
115         {
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());
121
122                                 $ret = $installer->$name($params);
123                                 return $ret;
124                         }
125                 }
126                 return true;
127         }
128 }
129 //
130 // Changes field value read from control file (single, or multiline) into 
131 // arrays of subfields if needed.
132 //
133 function ufmt_property($key, $value)
134 {
135         // indexes used in output arrays
136         $sub_fields = array(
137                 'MenuTabs' => array('url', 'access', 'tab_id', 'title', 'section'),
138                 'MenuEntries' => array('url', 'access', 'tab_id', 'title'),
139         );
140         if (!isset($sub_fields[$key]))
141                 return $value==='' ? null : $value;
142
143         $prop = array();
144
145         if (!is_array($value))
146                 $value = array($value);
147         foreach($value as $line) {
148                 $indexes = $sub_fields[$key];
149                 $ret = array();
150                 preg_match_all('/(["])(?:\\\\?+.)*?\1|[^"\s][\S]*/', $line, $match);
151                 foreach($match[0] as $n => $subf) {
152                         if ($match[1][$n])
153                                 $val = strtr(substr($subf, 1, -1),
154                                         array('\\"'=>'"'));
155                 else
156                                 $val = $subf;
157                         if (count($indexes))
158                                 $ret[array_shift($indexes)] = $val;
159                         else
160                                 $ret[] = $val;
161                 }
162                 if (count($ret))
163                         $prop[] = $ret;
164         }
165         return $prop;
166 }
167 //=============================================================================
168 //
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
171 //
172 function get_control_file($file, $index = false) {
173
174         $list = gzopen($file, 'rb');
175         if (!$list) return null;
176
177         $repo = $pkg = array();
178         $key = false; $value = '';
179         $line = '';
180         do {
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);
187                                 continue;
188                         }
189                 }
190                 if ($key) { // save previous property if any
191                         $pkg[$key] = ufmt_property($key, $value);
192                 }
193                 if (!strlen($line)) { // end of section
194                         if (count($pkg)) {
195                                 if ($index !== true) {
196                                         if ($index === false) break;
197                                         if (!isset($pkg[$index])) {
198                                                 display_error(_("No key field '$index' in file '$file'"));
199                                                 return null;
200                                         }
201                                         $repo[$pkg[$index]] = $pkg;
202                                 } else
203                                         $repo[] = $pkg;
204                         }
205                         $pkg = array(); 
206                         $key = null; $value = '';
207                         continue;
208                 } elseif (preg_match('/([^:]*):\s*(.*)/', $line, $m)) {
209                         $key = $m[1]; $value = $m[2];
210                         if (!strlen($key)) {
211                                 display_error("Empty key in line $line");
212                                 return null;
213                         }
214                 } else {
215                         display_error("File parse error in line $line");
216                         return null;
217                 }
218                 
219         } while ((($line = fgets($list))!==false) || $key);
220         fclose($list);
221
222         return $index === false ? $pkg : $repo;
223 }
224 //
225 //      Save configuration data to control file.
226 //
227 function save_control_file($fname, $list, $zip=false) 
228 {
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)) {
239                                                                 $value[$i][$n] = 
240                                                                         '"'.strtr($subfield, array('"'=>'\\"')).'"';
241                                                         }
242                                                 // Subfields are separated by white space.
243                                                 $value[$i] = implode(' ', $value[$i]);
244                                         }
245                                 }
246                                 // array elements on subsequent lines starting with white space
247                                 $value = implode("\n ", $value);
248                         }
249                         $zip ? gzwrite($file, "$key: $value\n") : fwrite($file, "$key: $value\n");
250                 }
251                 $zip ? gzwrite($file, "\n"): fwrite($file, "\n");
252         }
253         $zip ? gzclose($file) : fclose($file);
254 }
255 //
256 //      Retrieve text field in localized version or default one 
257 //      when the localized is not avaialable.
258 //
259 function pkg_prop($pkg, $property, $lang=false) 
260 {
261         
262         if ($lang && isset($pkg[$property.'-'.user_language()]))
263                 $prop = @$pkg[$pname];
264         else
265                 $prop = @$pkg[$property];
266
267         return is_array($prop) ? implode("\n ",$prop): $prop;
268 }
269 //
270 //      Retrieve list of packages from repository and return as table ($pkgname==null),
271 //      or find $pkgname package in repository and optionaly download
272 //
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.
277 //
278 function get_pkg_or_list($type = null, $pkgname = null, $filter=array(), $outkey=null, $download=true) {
279
280         global $path_to_root, $repo_auth;
281
282         // first download local copy of repo release file
283         // and check remote signature with local copy of public key
284         //
285         $loclist = PKG_CACHE_PATH.'/Release.gz';
286         
287         if (isset($type) && !is_array($type)) {
288                 $type = array($type);
289         }
290         $refresh = true;
291         do{
292                 if (!file_exists($loclist)) {
293                         copy(REPO_URL.'/Release.gz', $loclist);
294                         $refresh = false;
295                 }
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)) {
300                         if ($refresh)
301                                 @unlink($loclist);
302                         else {
303                                 display_error(_('Release file in repository is invalid, or public key is outdated.'));
304                                 return null;
305                         }
306                 } else
307                         $refresh = false;
308         } while($refresh);
309
310         $Release = get_control_file($loclist, 'Filename');
311         // download and check all indexes containing given package types
312         // then complete package list or seek for pkg
313         $Packages = array();
314         foreach($Release as $fname => $parms) {
315                 if ($type && !count(array_intersect(explode(' ', $parms['Type']), $type))) {
316                         unset($Release[$fname]); continue; // no packages of selected type in this index
317                 }
318                 if ($Release[$fname]['Version'] != $repo_auth['branch']) {
319                         display_warning(_('Repository version does not match application version.')); // ?
320                 }
321                 $remoteindex = REPO_URL.'/'.$fname;
322                 $locindex = PKG_CACHE_PATH.'/'.$fname;
323                 $refresh = true;
324                 do{
325                         if (!file_exists($locindex)) { 
326                                 copy($remoteindex, $locindex);
327                                 $refresh = false;
328                         }
329                         if ($parms['SHA1sum'] != sha1_file($locindex)) {        // check subdir index consistency
330                                 if ($refresh)
331                                         @unlink($locindex);
332                                 else {
333                                         display_error(sprintf( _("Security alert: broken index file in repository '%s'. Please inform repository administrator about this issue."),
334                                                 $fname));
335                                         return null;
336                                 }
337                         } else
338                                 $refresh = false;
339                 } while($refresh);
340                 
341                  // scan subdir list and select packages of given type
342                 $pkglist = get_control_file($locindex, 'Package');
343                 foreach($pkglist as $name => $pkg) {
344                         $pkgfullname = REPO_URL.'/'.$parms['Path']."/".$pkg['Filename'].'.pkg';
345                         if (!isset($type) || in_array($pkg['Type'], $type)) {
346                                 if (empty($filter))
347                                         $p = $pkg;
348                                 else {
349                                         foreach($filter as $field => $key) {
350                                                 if (is_numeric($field))
351                                                         $p[$field] = @$pkg[$field];
352                                                 else
353                                                         $p[$key] = @$pkg[$field];
354                                         }
355                                 }
356                                 if ($pkgname == null) {
357                                         $Packages[$outkey ? $outkey : $name] = $p;
358                                 } elseif ($pkgname == $pkg['Package']) {
359                                         //download package to temp directory
360                                         if ($download) {
361                                                 $locname = "$path_to_root/tmp/".$pkg['Filename'].'.pkg';
362                                                 copy($pkgfullname, $locname);
363                                                  // checking sha1 hash is expensive proces, so chekc the package
364                                                  // consistency just before downloading
365                                                 if ($pkg['SHA1sum'] != sha1_file($locname)) {
366                                                         display_error(sprintf( _("Security alert: broken package '%s' in repository. Please inform repository administrator about this issue."),
367                                                                 $pkgfullname));
368                                                         return null;
369                                                 }
370                                         }
371                                         return $p;
372                                 }
373                         }
374                 }
375         }
376
377         return $Packages;
378 }
379
380 function get_package($pkgname, $type = null)
381 {
382         return get_pkg_or_list($type, $pkgname);
383 }
384 /*
385         Returns full name of installed package, or null if package is not installed.
386 */
387 function installed_package($package)
388 {
389         $cache = opendir(PKG_CACHE_PATH);
390
391         while ($file = @readdir($cache)) {
392                 if (!is_dir(PKG_CACHE_PATH.'/'.$file))
393                         continue;
394                 if (strpos($file, $package.'-') === 0)
395                         return $file;
396         }
397         @closedir($cache);
398
399         return null;
400 }
401 /*
402         Remove package from system
403 */
404 function uninstall_package($name)
405 {
406         $name = installed_package($name);
407         if (!$name) return true; // not installed
408         $pkg = new package($name.'.pkg');
409         $pkg->uninstall();
410         if($name) {
411                 flush_dir(PKG_CACHE_PATH.'/'.$name, true);
412                 rmdir(PKG_CACHE_PATH.'/'.$name);
413         }
414         return count($pkg->error)==0;
415 }
416
417 //---------------------------------------------------------------------------------------
418 //
419 //      Return merged list of available and installed languages in inform of local 
420 // configuration array supplemented with installed versions information.
421 //
422 function get_languages_list()
423 {
424         global $installed_languages;
425         
426         $pkgs = get_pkg_or_list('language', null, array(
427                                 'Package' => 'package',
428                                 'Version' => 'available',
429                                 'Name' => 'name',
430                                 'Language' => 'code',
431                                 'Encoding' => 'encoding',
432                                 'RTLDir' => 'rtl',
433                                 'Description' => 'Descr',
434                                 'InstallPath' => 'path'
435                         ));
436
437         // add/update languages already installed
438         // 
439         foreach($installed_languages as $id => $l) {
440                 $list = array_search_keys($l['code'], $pkgs, 'code');   // get all packages with this code
441                 foreach ($list as $name) {
442                         if ($l['encoding'] == $pkgs[$name]['encoding']) {       // if the same encoding
443                                 $pkgs[$name]['version'] = @$l['version'];               // set installed version
444                                 $pkgs[$name]['local_id'] = $id;         // index in installed_languages
445                                 continue 2;
446                         }
447                 }
448                 $l['local_id'] = $id;
449                 if (!isset($l['package']) || $l['package'] == '' || !isset($pkgs[$l['package']]))
450                         $pkgs[] = $l;
451                 else
452                         $pkgs[$l['package']] = array_merge($pkgs[$l['package']], $l);
453         }
454         ksort($pkgs);
455         return $pkgs;
456 }
457 //---------------------------------------------------------------------------------------
458 //
459 //      Return merged list of available and installed extensions as a local 
460 // configuration array supplemented with installed versions information.
461 //
462 function get_extensions_list($type = null)
463 {
464
465         if (isset($type) && !is_array($type)) {
466                 $type = array($type);
467         }
468         
469         $pkgs = get_pkg_or_list($type, null, array(
470                                 'Package' => 'package',
471                                 'Version' => 'available',
472                                 'Name' => 'name',
473                                 'Description' => 'Descr',
474                                 'Type' => 'type',
475                                 'DefaultStatus'=> 'active',
476                                 'MenuTabs' => 'tabs',
477                                 'MenuEntries' => 'entries',
478                                 'Encoding' => 'encoding',
479                                 'AccessExtensions' => 'acc_file',
480                                 'InstallPath' => 'path'
481                         ));
482
483         // add/update extensions already installed
484         // 
485         $local = get_company_extensions();
486         foreach($local as $extno => $ext) {
487                 if (!in_array($ext['type'], $type)) continue;
488                 $ext['local_id'] = $extno;
489                 if (!isset($pkgs[$ext['package']]) || $ext['package'] == '')
490                         $pkgs[] = $ext;
491                 else
492                         $pkgs[$ext['package']] = array_merge($pkgs[$ext['package']], $ext);
493         }
494         ksort($pkgs);
495         return $pkgs;
496 }
497 //
498 // Return merged list of available and installed extensions as a local
499 // configuration array supplemented with installed versions information.
500 //
501 function get_themes_list()
502 {
503         $pkgs = get_pkg_or_list('theme', null, array(
504                                 'Package' => 'package',
505                                 'Version' => 'available',
506                                 'Name' => 'name',
507                                 'Description' => 'Descr'
508                         ));
509
510         // add/update extensions already installed
511         // 
512         $local = get_company_extensions();
513         
514         foreach($local as $extno => $ext) {
515                 if (isset($pkgs[@$ext['package']])) {
516                         $ext['local_id'] = $extno;
517                         $pkgs[$ext['package']] = array_merge($pkgs[$ext['package']], $ext);
518                 }
519         }
520         // TODO: Add other themes from themes directory
521         
522         ksort($pkgs);
523         return $pkgs;
524 }
525 //---------------------------------------------------------------------------------------
526 //
527 //      Return merged list of available and installed COAs as a local 
528 // configuration array supplemented with installed versions information.
529 //
530 function get_charts_list()
531 {
532         $pkgs = get_pkg_or_list('chart', null, array(
533                                 'Package' => 'package',
534                                 'Version' => 'available',
535                                 'Name' => 'name',
536                                 'Description' => 'Descr',
537                                 'Type' => 'type',
538                                 'InstallPath' => 'path',
539                                 'Encoding' => 'encoding',
540                                 'SqlScript' => 'sql'
541                         ));
542
543         // add/update default charts
544         // 
545         $local = get_company_extensions();
546
547         foreach($local as $extno => $ext) {
548                 if ($ext['type'] != 'chart') continue;
549                 $ext['local_id'] = $extno;
550                 if (!isset($pkgs[$ext['package']]) || $ext['package'] == '')
551                         $pkgs[] = $ext;
552                 else
553                         $pkgs[$ext['package']] = array_merge($pkgs[$ext['package']], $ext);
554         }
555         ksort($pkgs);
556         return $pkgs;
557 }
558 //---------------------------------------------------------------------------------------------
559 //      Install/update package from repository
560 //
561 function install_language($pkg_name)
562 {
563         global $path_to_root, $installed_languages, $Ajax;
564         
565         $pkg = get_pkg_or_list('language', $pkg_name);
566
567         if ($pkg) {
568                 $i = array_search_key($pkg['Language'], $installed_languages, 'code');
569                 if ($i === null)
570                         $i = count($installed_languages);
571                 else {  // remove another already installed package for this language 
572                         $old_pkg = @$installed_languages[$i]['package'];
573                         if ($old_pkg && ($pkg['Package'] != $old_pkg))
574                                 uninstall_package($old_pkg);
575                 }
576
577                 $package = new package("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
578                 if ($package->install()) {
579                         $lang = array(
580                                 'name' => $pkg['Name'],
581                                 'package' => $pkg['Package'],
582                                 'code' => $pkg['Language'],
583                                 'encoding' => $pkg['Encoding'],
584                                 'version' => $pkg['Version'],
585                                 'path' => $pkg['InstallPath']
586                         );
587                         if ($pkg['RTLDir']=='yes')
588                                 $lang['rtl'] = true;
589                         $installed_languages[$i] = $lang;
590                         write_lang($installed_languages);
591                         unlink("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
592                         $Ajax->activate('lang_tbl');
593                 } else {
594                         display_error(implode('<br>', $package->error));
595                         return false;
596                 }
597         } else {
598                 display_error(sprintf(_("Package '%s' not found."), $pkg_name));
599                 return false;
600         }
601         return true;
602 }
603 //---------------------------------------------------------------------------------------------
604 //      Install/update extension or theme package from repository
605 //
606 function install_extension($pkg_name)
607 {
608         global $path_to_root, $next_extension_id, $Ajax;
609         
610         $pkg = get_pkg_or_list(array('extension', 'theme', 'chart'), $pkg_name);
611         if ($pkg) {
612                 $package = new package("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
613                 $local_exts = get_company_extensions();
614                 if ($package->install()) {
615                         $ext_id = array_search_key($pkg['Package'], $local_exts, 'package');
616                         if ($ext_id === null)
617                                 $ext_id = $next_extension_id++;
618                         $ext = array(
619                                 'name' => $pkg['Name'],
620                                 'package' => $pkg['Package'],
621                                 'version' => $pkg['Version'],
622                                 'type' => $pkg['Type'],
623                                 'active' => true,
624                                 'path' => $pkg['InstallPath'],
625                         );
626                         if (isset($pkg['MenuTabs']))
627                                 $ext['tabs'] = $pkg['MenuTabs'];
628                         if (isset($pkg['MenuEntries']))
629                                 $ext['entries'] = $pkg['MenuEntries'];
630                         if (isset($pkg['AccessExtensions']))
631                                 $ext['acc_file'] = $pkg['AccessExtensions'];
632                         if (isset($pkg['SqlScript']))
633                                 $ext['sql'] = $pkg['SqlScript'];
634                         $local_exts[$ext_id] = $ext;
635                         $ret = update_extensions($local_exts);
636                         unlink("$path_to_root/tmp/".$pkg['Filename'].'.pkg');
637                         $Ajax->activate('ext_tbl');
638                         return $ret;
639                 } else {
640                         display_error(implode('<br>', $package->error));
641                         return false;
642                 }
643         } else {
644                 display_error(sprintf(_("Package '%s' not found."), $pkg_name));
645                 return false;
646         }
647         return true;
648 }
649 /*
650         Returns true if newer package version is available
651 */
652 function check_pkg_upgrade($current, $available)
653 {
654         preg_match_all('/[\d]+/', $available, $aver);
655         if (!count($aver[0]))
656                 return false;
657         preg_match_all('/[\d]+/', $current, $cver);
658         if (!count($cver[0]))
659                 return true;
660         foreach($aver[0] as $n => $ver)
661                 if ($ver>@$cver[0][$n]) 
662                         return true;
663         return false;
664 }
665
666 //
667 //      Returns package info from index file
668 //
669 function get_package_info($pkg, $type=null, $filter=array(), $outkey=null, $download=true) {
670         return get_pkg_or_list($type, $pkg, $filter, null, false);
671 }
672
673 ?>