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