PageRenderTime 1074ms CodeModel.GetById 631ms app.highlight 175ms RepoModel.GetById 127ms app.codeStats 1ms

/utils/reinstall.php

http://litepublisher.googlecode.com/
PHP | 933 lines | 640 code | 146 blank | 147 comment | 112 complexity | 719c2a48b6d0816ff718bbc54b5a737d MD5 | raw file
  1<?php
  2require('db.php');
  3//lib/include/tar.class.php
  4
  5/* special changes and bug fixes by Vladimir Yushko
  6http://litepublisher.com/
  7*/
  8
  9/*
 10=======================================================================
 11Name:
 12    tar Class
 13
 14Author:
 15    Josh Barger <joshb@npt.com>
 16
 17Description:
 18    This class reads and writes Tape-Archive (TAR) Files and Gzip
 19    compressed TAR files, which are mainly used on UNIX systems.
 20    This class works on both windows AND unix systems, and does
 21    NOT rely on external applications!! Woohoo!
 22
 23Usage:
 24    Copyright (C) 2002  Josh Barger
 25
 26    This library is free software; you can redistribute it and/or
 27    modify it under the terms of the GNU Lesser General Public
 28    License as published by the Free Software Foundation; either
 29    version 2.1 of the License, or (at your option) any later version.
 30
 31    This library is distributed in the hope that it will be useful,
 32    but WITHOUT ANY WARRANTY; without even the implied warranty of
 33    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 34    Lesser General Public License for more details at:
 35        http://www.gnu.org/copyleft/lesser.html
 36
 37    If you use this script in your application/website, please
 38    send me an e-mail letting me know about it :)
 39
 40Bugs:
 41    Please report any bugs you might find to my e-mail address
 42    at joshb@npt.com.  If you have already created a fix/patch
 43    for the bug, please do send it to me so I can incorporate it into my release.
 44
 45Version History:
 46    1.0 04/10/2002  - InitialRelease
 47
 48    2.0 04/11/2002  - Merged both tarReader and tarWriter
 49                  classes into one
 50                - Added support for gzipped tar files
 51                  Remember to name for .tar.gz or .tgz
 52                  if you use gzip compression!
 53                  :: THIS REQUIRES ZLIB EXTENSION ::
 54                - Added additional comments to
 55                  functions to help users
 56                - Added ability to remove files and
 57                  directories from archive
 58    2.1 04/12/2002  - Fixed serious bug in generating tar
 59                - Created another example file
 60                - Added check to make sure ZLIB is
 61                  installed before running GZIP
 62                  compression on TAR
 63    2.2 05/07/2002  - Added automatic detection of Gzipped
 64                  tar files (Thanks go to J?gen Falch
 65                  for the idea)
 66                - Changed "private" functions to have
 67                  special function names beginning with
 68                  two underscores
 69=======================================================================
 70*/
 71
 72class tar {
 73    // Unprocessed Archive Information
 74    var $filename;
 75    var $isGzipped;
 76    var $tar_file;
 77
 78    // Processed Archive Information
 79    var $files;
 80    var $directories;
 81    var $numFiles;
 82    var $numDirectories;
 83
 84
 85    // Class Constructor -- Does nothing...
 86    function tar() {
 87        return true;
 88    }
 89
 90
 91    // Computes the unsigned Checksum of a file's header
 92    // to try to ensure valid file
 93    // PRIVATE ACCESS FUNCTION
 94    function __computeUnsignedChecksum($bytestring) {
 95$unsigned_chksum = 0;
 96        for($i=0; $i<512; $i++)
 97            $unsigned_chksum += ord($bytestring[$i]);
 98        for($i=0; $i<8; $i++)
 99            $unsigned_chksum -= ord($bytestring[148 + $i]);
100        $unsigned_chksum += ord(" ") * 8;
101
102        return $unsigned_chksum;
103    }
104
105
106    // Converts a NULL padded string to a non-NULL padded string
107    // PRIVATE ACCESS FUNCTION
108    function __parseNullPaddedString($string) {
109        $position = strpos($string,chr(0));
110        return substr($string,0,$position);
111    }
112
113
114    // This function parses the current TAR file
115    // PRIVATE ACCESS FUNCTION
116    function __parseTar() {
117        // Read Files from archive
118        $tar_length = strlen($this->tar_file);
119        $main_offset = 0;
120        while($main_offset < $tar_length) {
121            // If we read a block of 512 nulls, we are at the end of the archive
122            if(substr($this->tar_file,$main_offset,512) == str_repeat(chr(0),512))
123                break;
124
125            // Parse file name
126            $file_name      = $this->__parseNullPaddedString(substr($this->tar_file,$main_offset,100));
127
128            // Parse the file mode
129            $file_mode      = substr($this->tar_file,$main_offset + 100,8);
130
131            // Parse the file user ID
132            $file_uid       = octdec(substr($this->tar_file,$main_offset + 108,8));
133
134            // Parse the file group ID
135            $file_gid       = octdec(substr($this->tar_file,$main_offset + 116,8));
136
137            // Parse the file size
138            $file_size      = octdec(substr($this->tar_file,$main_offset + 124,12));
139
140            // Parse the file update time - unix timestamp format
141            $file_time      = octdec(substr($this->tar_file,$main_offset + 136,12));
142
143            // Parse Checksum
144            $file_chksum        = octdec(substr($this->tar_file,$main_offset + 148,6));
145
146            // Parse user name
147            $file_uname     = $this->__parseNullPaddedString(substr($this->tar_file,$main_offset + 265,32));
148
149            // Parse Group name
150            $file_gname     = $this->__parseNullPaddedString(substr($this->tar_file,$main_offset + 297,32));
151
152            // Make sure our file is valid
153            if($this->__computeUnsignedChecksum(substr($this->tar_file,$main_offset,512)) != $file_chksum)
154                return false;
155
156            // Parse File Contents
157            $file_contents      = substr($this->tar_file,$main_offset + 512,$file_size);
158
159            /*  ### Unused Header Information ###
160                $activeFile["typeflag"]     = substr($this->tar_file,$main_offset + 156,1);
161                $activeFile["linkname"]     = substr($this->tar_file,$main_offset + 157,100);
162                $activeFile["magic"]        = substr($this->tar_file,$main_offset + 257,6);
163                $activeFile["version"]      = substr($this->tar_file,$main_offset + 263,2);
164                $activeFile["devmajor"]     = substr($this->tar_file,$main_offset + 329,8);
165                $activeFile["devminor"]     = substr($this->tar_file,$main_offset + 337,8);
166                $activeFile["prefix"]       = substr($this->tar_file,$main_offset + 345,155);
167                $activeFile["endheader"]    = substr($this->tar_file,$main_offset + 500,12);
168            */
169
170            if($file_size > 0) {
171                // Increment number of files
172                $this->numFiles++;
173
174                // Create us a new file in our array
175                $activeFile = &$this->files[];
176
177                // Asign Values
178                $activeFile["name"]     = $file_name;
179                $activeFile["mode"]     = $file_mode;
180                $activeFile["size"]     = $file_size;
181                $activeFile["time"]     = $file_time;
182                $activeFile["user_id"]      = $file_uid;
183                $activeFile["group_id"]     = $file_gid;
184                $activeFile["user_name"]    = $file_uname;
185                $activeFile["group_name"]   = $file_gname;
186                $activeFile["checksum"]     = $file_chksum;
187                $activeFile["file"]     = $file_contents;
188
189            } else {
190                // Increment number of directories
191                $this->numDirectories++;
192
193                // Create a new directory in our array
194                $activeDir = &$this->directories[];
195
196                // Assign values
197                $activeDir["name"]      = $file_name;
198                $activeDir["mode"]      = $file_mode;
199                $activeDir["time"]      = $file_time;
200                $activeDir["user_id"]       = $file_uid;
201                $activeDir["group_id"]      = $file_gid;
202                $activeDir["user_name"]     = $file_uname;
203                $activeDir["group_name"]    = $file_gname;
204                $activeDir["checksum"]      = $file_chksum;
205            }
206
207            // Move our offset the number of blocks we have processed
208            $main_offset += 512 + (ceil($file_size / 512) * 512);
209        }
210
211        return true;
212    }
213
214
215    public function loadfromstring($s) {
216        // Clear any values from previous tar archives
217        unset($this->filename);
218        unset($this->isGzipped);
219        unset($this->tar_file);
220        unset($this->files);
221        unset($this->directories);
222        unset($this->numFiles);
223        unset($this->numDirectories);
224
225        $this->tar_file = $s;
226        if($this->tar_file[0] == chr(31) && $this->tar_file[1] == chr(139) && $this->tar_file[2] == chr(8)) {
227            $this->isGzipped = TRUE;
228            $this->tar_file = gzinflate(substr($this->tar_file,10,-4));
229        }
230        // Parse the TAR file
231        $this->__parseTar();
232        return true;
233    }
234
235    // Generates a TAR file from the processed data
236    // PRIVATE ACCESS FUNCTION
237    function __generateTAR() {
238        // Clear any data currently in $this->tar_file
239        unset($this->tar_file);
240
241        // Generate Records for each directory, if we have directories
242        if($this->numDirectories > 0) {
243            foreach($this->directories as $key => $information) {
244                //unset($header);
245
246                // Generate tar header for this directory
247                // Filename, Permissions, UID, GID, size, Time, checksum, typeflag, linkname, magic, version, user name, group name, devmajor, devminor, prefix, end
248                $header = str_pad($information["name"],100,chr(0));
249                $header .= str_pad(decoct($information["mode"]),7,"0",STR_PAD_LEFT) . chr(0);
250                $header .= str_pad(decoct($information["user_id"]),7,"0",STR_PAD_LEFT) . chr(0);
251                $header .= str_pad(decoct($information["group_id"]),7,"0",STR_PAD_LEFT) . chr(0);
252                $header .= str_pad(decoct(0),11,"0",STR_PAD_LEFT) . chr(0);
253                $header .= str_pad(decoct($information["time"]),11,"0",STR_PAD_LEFT) . chr(0);
254                $header .= str_repeat(" ",8);
255                $header .= "5";
256                $header .= str_repeat(chr(0),100);
257                $header .= str_pad("ustar",6,chr(32));
258                $header .= chr(32) . chr(0);
259                $header .= str_pad("",32,chr(0));
260                $header .= str_pad("",32,chr(0));
261                $header .= str_repeat(chr(0),8);
262                $header .= str_repeat(chr(0),8);
263                $header .= str_repeat(chr(0),155);
264                $header .= str_repeat(chr(0),12);
265
266                // Compute header checksum
267                $checksum = str_pad(decoct($this->__computeUnsignedChecksum($header)),6,"0",STR_PAD_LEFT);
268                for($i=0; $i<6; $i++) {
269                    $header[(148 + $i)] = substr($checksum,$i,1);
270                }
271                $header[154] = chr(0);
272                $header[155] = chr(32);
273
274                // Add new tar formatted data to tar file contents
275                $this->tar_file .= $header;
276            }
277        }
278
279        // Generate Records for each file, if we have files (We should...)
280        if($this->numFiles > 0) {
281            foreach($this->files as $key => $information) {
282                //unset($header);
283
284                // Generate the TAR header for this file
285                // Filename, Permissions, UID, GID, size, Time, checksum, typeflag, linkname, magic, version, user name, group name, devmajor, devminor, prefix, end
286                $header = str_pad($information["name"],100,chr(0));
287                $header .= str_pad(decoct($information["mode"]),7,"0",STR_PAD_LEFT) . chr(0);
288                $header .= str_pad(decoct($information["user_id"]),7,"0",STR_PAD_LEFT) . chr(0);
289                $header .= str_pad(decoct($information["group_id"]),7,"0",STR_PAD_LEFT) . chr(0);
290                $header .= str_pad(decoct($information["size"]),11,"0",STR_PAD_LEFT) . chr(0);
291                $header .= str_pad(decoct($information["time"]),11,"0",STR_PAD_LEFT) . chr(0);
292                $header .= str_repeat(" ",8);
293                $header .= "0";
294                $header .= str_repeat(chr(0),100);
295                $header .= str_pad("ustar",6,chr(32));
296                $header .= chr(32) . chr(0);
297                $header .= str_pad($information["user_name"],32,chr(0));    // How do I get a file's user name from PHP?
298                $header .= str_pad($information["group_name"],32,chr(0));   // How do I get a file's group name from PHP?
299                $header .= str_repeat(chr(0),8);
300                $header .= str_repeat(chr(0),8);
301                $header .= str_repeat(chr(0),155);
302                $header .= str_repeat(chr(0),12);
303
304                // Compute header checksum
305                $checksum = str_pad(decoct($this->__computeUnsignedChecksum($header)),6,"0",STR_PAD_LEFT);
306                for($i=0; $i<6; $i++) {
307                    $header[(148 + $i)] = substr($checksum,$i,1);
308                }
309                $header[154] = chr(0);
310                $header[155] = chr(32);
311
312                // Pad file contents to byte count divisible by 512
313                $file_contents = str_pad($information["file"],(ceil($information["size"] / 512) * 512),chr(0));
314
315                // Add new tar formatted data to tar file contents
316                $this->tar_file .= $header . $file_contents;
317            }
318        }
319
320        // Add 512 bytes of NULLs to designate EOF
321        $this->tar_file .= str_repeat(chr(0),512);
322
323        return true;
324    }
325
326
327public function loadfromfile($filename) {
328        if(!file_exists($filename)) return false;
329        $this->filename = $filename;
330        return $this->loadfromstring(file_get_contents($filename));
331    }
332
333    // Appends a tar file to the end of the currently opened tar file
334    function appendTar($filename) {
335        // If the tar file doesn't exist...
336        if(!file_exists($filename))
337            return false;
338
339        $this->__readTar($filename);
340
341        return true;
342    }
343
344
345    // Retrieves information about a file in the current tar archive
346    function getFile($filename) {
347        if($this->numFiles > 0) {
348            foreach($this->files as $key => $information) {
349                if($information["name"] == $filename)
350                    return $information;
351            }
352        }
353
354        return false;
355    }
356
357
358    // Retrieves information about a directory in the current tar archive
359    function getDirectory($dirname) {
360        if($this->numDirectories > 0) {
361            foreach($this->directories as $key => $information) {
362                if($information["name"] == $dirname)
363                    return $information;
364            }
365        }
366
367        return false;
368    }
369
370
371    // Check if this tar archive contains a specific file
372    function containsFile($filename) {
373        if($this->numFiles > 0) {
374            foreach($this->files as $key => $information) {
375                if($information["name"] == $filename)
376                    return true;
377            }
378        }
379
380        return false;
381    }
382
383
384    // Check if this tar archive contains a specific directory
385    function containsDirectory($dirname) {
386        if($this->numDirectories > 0) {
387            foreach($this->directories as $key => $information) {
388                if($information["name"] == $dirname)
389                    return true;
390            }
391        }
392
393        return false;
394    }
395
396
397    // Add a directory to this tar archive
398    function adddir($dirname, $perm = 0777) {
399        $this->numDirectories++;
400        $activeDir      = &$this->directories[];
401        $activeDir["name"]  = $dirname;
402        $activeDir["mode"]  = $perm;
403        $activeDir["time"]  = time();
404        $activeDir["user_id"]   = 0;
405        $activeDir["group_id"]  = 0;
406        $activeDir["user_name"]    = "";
407        $activeDir["group_name"]   = "";
408        $activeDir["checksum"]  = 0;
409        return true;
410    }
411
412    // Add a file to the tar archive
413    public function add($realfile, $filename, $perm = 0666) {
414        if($this->containsFile($filename)) return false;
415        $file_information = stat($realfile);
416if (($perm == 0) && (DIRECTORY_SEPARATOR == '/')) $perm = $file_information["mode"] == 0 ? $perm : $file_information["mode"];
417        // Read in the file's contents
418        $file_contents = file_get_contents($realfile);
419        // Add file to processed data
420$checksum = 0;
421        $this->numFiles++;
422        $activeFile         = &$this->files[];
423        $activeFile["name"]     = $filename;
424        $activeFile["mode"]     = $perm;
425        $activeFile["user_id"]      = $file_information["uid"]; // == 0 ? 33 : $file_information["uid"];
426        $activeFile["group_id"]     = $file_information["gid"]; // == 0 ? 33 : $file_information["gid"];
427        $activeFile["user_name"]    = "";
428        $activeFile["group_name"]   = "";
429
430        $activeFile["size"]     = strlen($file_contents);
431        $activeFile["time"]     = $file_information["mtime"];
432        $activeFile["checksum"]     = 0;
433        $activeFile["file"]     = $file_contents;
434        return true;
435    }
436
437    public function addstring($s, $filename, $perm = 0666) {
438        if($this->containsFile($filename)) return false;
439        // Add file to processed data
440        $this->numFiles++;
441        $activeFile         = &$this->files[];
442        $activeFile["name"]     = $filename;
443        $activeFile["mode"]     = $perm;
444        $activeFile["user_id"]      = 0;
445        $activeFile["group_id"]     = 0;
446        $activeFile["size"]     = strlen($s);
447        $activeFile["time"]     = time();
448        $activeFile["checksum"]     = 0;
449        $activeFile["user_name"]    = "";
450        $activeFile["group_name"]   = "";
451        $activeFile["file"]     = $s;
452        return true;
453    }
454
455    // Remove a file from the tar archive
456    function removeFile($filename) {
457        if($this->numFiles > 0) {
458            foreach($this->files as $key => $information) {
459                if($information["name"] == $filename) {
460                    $this->numFiles--;
461                    unset($this->files[$key]);
462                    return true;
463                }
464            }
465        }
466
467        return false;
468    }
469
470
471    // Remove a directory from the tar archive
472    function removeDirectory($dirname) {
473        if($this->numDirectories > 0) {
474            foreach($this->directories as $key => $information) {
475                if($information["name"] == $dirname) {
476                    $this->numDirectories--;
477                    unset($this->directories[$key]);
478                    return true;
479                }
480            }
481        }
482
483        return false;
484    }
485
486
487    // Write the currently loaded tar archive to disk
488    function saveTar() {
489        if(!$this->filename)
490            return false;
491
492        // Write tar to current file using specified gzip compression
493        $this->toTar($this->filename,$this->isGzipped);
494
495        return true;
496    }
497
498    // Saves tar archive to a different file than the current file
499    function savetofile($filename,$useGzip) {
500return file_put_contents($filename, $this->savetostring($useGzip));
501}
502
503function savetostring($useGzip) {
504        $this->__generateTar();
505return$useGzip ? gzencode($this->tar_file) : $this->tar_file;
506}
507
508}
509
510// lib/http.class.php
511class http {
512  public static function get($url) {
513    $timeout = 5;
514    $parsed = @parse_url($url);
515    if ( !$parsed || !is_array($parsed) ) return false;
516    if ( !isset($parsed['scheme']) || !in_array($parsed['scheme'], array('http','https')) ) {
517      $url = 'http://' . $url;
518    }
519    
520    if ( ini_get('allow_url_fopen') ) {
521      if($fp = @fopen( $url, 'r' )) {
522        @stream_set_timeout($fp, $timeout);
523        $result = '';
524        while( $remote_read = fread($fp, 4096) )  $result .= $remote_read;
525        fclose($fp);
526        return $result;
527      }
528      return false;
529    } elseif ( function_exists('curl_init') ) {
530      $handle = curl_init();
531      curl_setopt ($handle, CURLOPT_URL, $url);
532      curl_setopt ($handle, CURLOPT_CONNECTTIMEOUT, 1);
533      curl_setopt ($handle, CURLOPT_RETURNTRANSFER, 1);
534      curl_setopt ($handle, CURLOPT_TIMEOUT, $timeout);
535      $result= curl_exec($handle);
536      curl_close($handle);
537      return $result;
538    } else {
539      return false;
540    }
541  }
542  
543}//class
544
545// part of lib/updater.class.php
546
547class download {
548
549  public static function getlatest() {
550    if (($s = http::get('http://litepublisher.com/service/version.txt'))  ||
551    ($s = http::get('http://litepublisher.googlecode.com/files/version.txt') )) {
552      return $s;
553    }
554    return false;
555  }
556  
557  public static function install() {
558$dir = dirname(__file__) . DIRECTORY_SEPARATOR;
559    //test write
560    if (!file_put_contents($dir. 'test.php', ' ')) die('Error write to test.php');
561chmod($dir. 'test.php', 0666);
562unlink($dir . 'test.php');
563
564if ($version = self::getlatest()) {
565    if (($s = http::get("http://litepublisher.googlecode.com/files/litepublisher.$version.tar.gz")) ||
566    ($s = http::get("http://litepublisher.com/download/litepublisher.$version.tar.gz") )) {
567    $tar = new tar();
568    $tar->loadfromstring($s);
569    foreach ($tar->files as $file) {
570      $filename = $dir . str_replace('/', DIRECTORY_SEPARATOR, $file['name']);
571        if (!self::forcedir(dirname($filename))) die("error create folder " . dirname($filename));
572        if (false === @file_put_contents($filename, $file['file']))  die(sprintf('Error write file %s', $filename));
573        @chmod($filename, 0666);
574    }
575return true;
576}
577}
578die('Error download last release');
579  }
580
581  public static function forcedir($dir) {
582    $dir = rtrim($dir, DIRECTORY_SEPARATOR);
583    if (is_dir($dir)) return true;
584    $up = rtrim(dirname($dir), DIRECTORY_SEPARATOR);
585    if (($up != '') || ($up != '.'))  self::forcedir($up);
586    if (!is_dir($dir)) mkdir($dir, 0777);
587    chmod($dir, 0777);
588    return is_dir($dir);
589  }
590
591}//class
592
593//lib/data.class.php
594class tdata {
595  public static $savedisabled;
596  public $basename;
597  public $cache;
598  public $coclasses;
599  public $coinstances;
600  public $data;
601  public $lockcount;
602  public $table;
603  
604  public function __construct() {
605    $this->lockcount = 0;
606    $this->cache= true;
607    $this->data= array();
608    $this->coinstances = array();
609    $this->coclasses = array();
610    $this->basename = substr(get_class($this), 1);
611    $this->create();
612  }
613  
614  protected function create() {
615  }
616  
617  public function __get($name) {
618    if (method_exists($this, $get = "get$name"))  {
619      return $this->$get();
620    } elseif (array_key_exists($name, $this->data)) {
621      return $this->data[$name];
622    } else {
623      foreach ($this->coinstances as $coinstance) {
624        if (isset($coinstance->$name)) return $coinstance->$name;
625      }
626      return    $this->error("The requested property $name not found in class ". get_class($this));
627    }
628  }
629  
630  public function __set($name, $value) {
631    if (method_exists($this, $set = "set$name")) {
632      $this->$set($value);
633      return true;
634    }
635    
636    if (key_exists($name, $this->data)) {
637      $this->data[$name] = $value;
638      return true;
639    }
640    
641    foreach ($this->coinstances as $coinstance) {
642      if (isset($coinstance->$name)) {
643        $coinstance->$name = $value;
644        return true;
645      }
646    }
647    
648    return false;
649  }
650  
651  public  function __call($name, $params) {
652    if (method_exists($this, strtolower($name))) {
653      return call_user_func_array(array($this, strtolower($name)), $params);
654    }
655    
656    foreach ($this->coinstances as $coinstance) {
657      if (method_exists($coinstance, $name)) return call_user_func_array(array($coinstance, $name), $params);
658    }
659    $this->error("The requested method $name not found in class " . get_class($this));
660  }
661  
662  public function __isset($name) {
663    return array_key_exists($name, $this->data) || method_exists($this, "get$name") | method_exists($this, "Get$name");
664  }
665  
666  public function error($Msg) {
667    throw new Exception($Msg);
668  }
669  
670  public function getbasename() {
671    return $this->basename;
672  }
673  
674  public function install() {
675    $this->externalchain('Install');
676  }
677  
678  public function uninstall() {
679    $this->externalchain('Uninstall');
680  }
681  
682  public function validate($repair = false) {
683    $this->externalchain('Validate', $repair);
684  }
685  
686  protected function externalchain($func, $arg = null) {
687    $parents = class_parents($this);
688    array_splice($parents, 0, 0, get_class($this));
689    foreach ($parents as $key => $class) {
690      $this->externalfunc($class, $func, $arg);
691    }
692  }
693  
694  protected function externalfunc($class, $func, $arg) {
695    if ($filename = litepublisher::$classes->getclassfilename($class)) {
696      $externalname = basename($filename, '.php') . '.install.php';
697      $dir = dirname($filename) . DIRECTORY_SEPARATOR;
698      $file = $dir . 'install' . DIRECTORY_SEPARATOR . $externalname;
699      if (!file_exists($file)) {
700        $file =$dir .  $externalname;
701        if (!file_exists($file)) return;
702      }
703      
704      include_once($file);
705      $fnc = $class . $func;
706      if (function_exists($fnc)) $fnc($this, $arg);
707    }
708  }
709  
710  public function load() {
711    if ($this->dbversion == 'full') return $this->LoadFromDB();
712    $filename = litepublisher::$paths->data . $this->getbasename() .'.php';
713    if (file_exists($filename)) {
714      return $this->loadfromstring(self::uncomment_php(file_get_contents($filename)));
715    }
716  }
717  
718  public function save() {
719    if (self::$savedisabled || ($this->lockcount > 0)) return;
720    if ($this->dbversion) {
721      $this->SaveToDB();
722    } else {
723      self::savetofile(litepublisher::$paths->data .$this->getbasename(), self::comment_php($this->savetostring()));
724    }
725  }
726  
727  public function savetostring() {
728    return serialize($this->data);
729  }
730  
731  public function loadfromstring($s) {
732    try {
733      if (!empty($s)) $this->data = unserialize($s) + $this->data;
734      $this->afterload();
735      return true;
736    } catch (Exception $e) {
737      echo 'Caught exception: '.  $e->getMessage() ;
738      return false;
739    }
740  }
741  
742  public function afterload() {
743  }
744  
745  public function lock() {
746    $this->lockcount++;
747  }
748  
749  public function unlock() {
750    if (--$this->lockcount <= 0) $this->save();
751  }
752  
753  public function getlocked() {
754    return $this->lockcount  > 0;
755  }
756  
757  public function Getclass() {
758    return get_class($this);
759  }
760  
761  public function getdbversion() {
762    return false; // dbversion == 'full';
763  }
764  
765  public function getdb($table = '') {
766    $table =$table != '' ? $table : $this->table;
767    if ($table != '') litepublisher::$db->table = $table;
768    return litepublisher::$db;
769  }
770  
771  protected function SaveToDB() {
772    $this->db->add($this->getbasename(), $this->savetostring());
773  }
774  
775  protected function LoadFromDB() {
776    if ($r = $this->db->select('basename = '. $this->getbasename() . "'")) {
777      return $this->loadfromstring($r['data']);
778    }
779  }
780  
781  protected function getthistable() {
782    return litepublisher::$db->prefix . $this->table;
783  }
784  
785  public static function savetofile($base, $content) {
786    $tmp = $base .'.tmp.php';
787    if(false === file_put_contents($tmp, $content)) {
788      litepublisher::$options->trace("Error write to file $tmp");
789      return false;
790    }
791    chmod($tmp, 0666);
792    $filename = $base .'.php';
793    if (file_exists($filename)) {
794      $back = $base . '.bak.php';
795      if (file_exists($back)) unlink($back);
796      rename($filename, $back);
797    }
798    if (!rename($tmp, $filename)) {
799      litepublisher::$options->trace("Error rename file $tmp to $filename");
800      return false;
801    }
802    return true;
803  }
804  
805  public static function comment_php($s) {
806    return sprintf('<?php /* %s */ ?>', str_replace('*/', '**//*/', $s));
807  }
808  
809  public static function uncomment_php($s) {
810    return str_replace('**//*/', '*/', substr($s, 9, strlen($s) - 9 - 6));
811  }
812  
813}//class
814
815class tarray2prop {
816  public $array;
817public function __get($name) { return $this->array[$name]; }
818public function __set($name, $value) { $this->array[$name] = $value; }
819public function __tostring() { return $this->array[0]; }
820public function __isset($name) { return array_key_exists($name, $this->array); }
821}//class
822
823function sqldate($date = 0) {
824  if ($date == 0) $date = time();
825  return date('Y-m-d H:i:s', $date);
826}
827
828function dbquote($s) {
829  return litepublisher::$db->quote($s);
830}
831
832function md5uniq() {
833  return md5(mt_rand() . litepublisher::$secret. microtime());
834}
835
836function strbegin($s, $begin) {
837  return strncmp($s, $begin, strlen($begin)) == 0;
838}
839
840function strend($s, $end) {
841  return $end == substr($s, 0 - strlen($end));
842}
843
844function array_delete(array &$a, $i) {
845  array_splice($a, $i, 1);
846}
847
848function array_delete_value(array &$a, $value) {
849  $i = array_search($value, $a);
850  if ($i !== false)         array_splice($a, $i, 1);
851}
852
853function array_insert(array &$a, $item, $index) {
854  array_splice($a, $index, 0, array($item));
855}
856
857function array_move(array &$a, $oldindex, $newindex) {
858  //delete and insert
859  if (($oldindex == $newindex) || !isset($a[$oldindex])) return false;
860  $item = $a[$oldindex];
861  array_splice($a, $oldindex, 1);
862  array_splice($a, $newindex, 0, array($item));
863}
864
865function dumpstr($s) {
866  echo "<pre>\n" . htmlspecialchars($s) . "</pre>\n";
867}
868
869class tmigratedata extends tdata {
870public static $dir;
871
872public function loadfile($name) {
873$this->data = array();
874$filename = self::$dir . $name . '.php';
875    if (file_exists($filename)) {
876      return $this->loadfromstring(self::uncomment_php(file_get_contents($filename)));
877    }
878}
879
880}//class
881
882function movefolders() {
883$home = dirname(__file__) . DIRECTORY_SEPARATOR;
884$backup = $home . 'backup' . DIRECTORY_SEPARATOR . date('H-i-s.d.m.Y');
885mkdir($backup, 0777);
886chmod($backup, 0777);
887$backup .= DIRECTORY_SEPARATOR;
888
889foreach (array('lib', 'plugins', 'themes') as $name) {
890if (is_dir($home . $name)) rename($home . $name, $backup . $name);
891}
892
893$data = $home . 'data' . DIRECTORY_SEPARATOR . $_SERVER['HTTP_HOST'];
894$old = $home . 'data' . DIRECTORY_SEPARATOR . 'old';
895if (is_dir($data) && !is_dir($old))  rename($data, $old);
896tmigratedata::$dir =$old . DIRECTORY_SEPARATOR;
897}
898
899set_time_limit(120);
900date_default_timezone_set("Europe/Moscow");
901movefolders();
902
903$data = new tmigratedata();
904$data->loadfile('options');
905if (download::install()) {
906$params = sprintf('&lang=%s&name=%s&description=%s&email=%s', rawurlencode($data->language), rawurlencode($data->name), rawurlencode($data->description), rawurlencode($data->email));
907if (isset($dbversion) && $dbversion) {
908//test connect
909    $host= isset($dbhost) ? $dbhost : 'localhost';
910    if (isset($dbport))  $host .= ':' . $dbport;
911    $handle = mysql_connect($host, $dblogin, $dbpassword);
912    if (! $handle) {
913die('Error connect to database');
914    }
915    if (!        mysql_select_db($dbname, $handle)) {
916die('Error select database');
917    }
918    
919$params .= "&dbversion=1&dbname=$dbname&dblogin=$dblogin&dbpassword=$dbpassword&dbprefix=$dbprefix";
920if (!isset($dbhost)) {
921$params .= '&usehost=0';
922} else {
923$params .= "&usehost=1&dbhost=$dbhost&dbport=$dbport";
924}
925}
926if ($s = http::get('http://'. $_SERVER['HTTP_HOST'] . '/?mode=remote&lite=1&resulttype=serialized' . $params)) {
927$info = unserialize($s);
928header('Location: http://'. $_SERVER['HTTP_HOST'] . '/migrate.php');
929exit();
930}
931}
932echo "Not installed";
933?>