Changeset 8 for trunk


Ignore:
Timestamp:
Jun 1, 2023, 12:18:18 AM (18 months ago)
Author:
chronos
Message:
  • Modified: Updated Common package.
  • Modified: Form types made as separate FormManager package.
  • Fixed: PHP 8.1 support.
Location:
trunk
Files:
59 added
4 deleted
19 edited
1 copied
4 moved

Legend:

Unmodified
Added
Removed
  • trunk/Application/BaseView.php

    r7 r8  
    2626    $Output .= $Content;
    2727    $Output .= '<br/><div style="text-align: center; font-size: small;">Verze: '.$Revision.' ('.HumanDate($ReleaseTime).')'.
    28       ' &nbsp; <a href="http://svn.zdechov.net/trac/open2ride/browser/trunk">Zdrojový kód</a> &nbsp; '.
    29       '<a href="http://svn.zdechov.net/trac/open2ride/log/trunk?verbose=on">Historie změn</a></div>';
     28      ' &nbsp; <a href="https://svn.zdechov.net/trac/open2ride/browser/trunk">Zdrojový kód</a> &nbsp; '.
     29      '<a href="https://svn.zdechov.net/trac/open2ride/log/trunk?verbose=on">Historie změn</a></div>';
    3030    $Output .= '</body></html>';
    3131    echo($Output);
  • trunk/Application/Core.php

    r7 r8  
    44if (file_exists($ConfigFileName)) include_once($ConfigFileName);
    55
    6 include_once(dirname(__FILE__).'/../Packages/Common/Common.php');
     6include_once(dirname(__FILE__).'/../Packages/Common/PackageCommon.php');
     7include_once(dirname(__FILE__).'/../Packages/FormManager/PackageFormManager.php');
    78include_once(dirname(__FILE__).'/Version.php');
    8 include_once(dirname(__FILE__).'/View.php');
     9include_once(dirname(__FILE__).'/BaseView.php');
     10include_once(dirname(__FILE__).'/PageMissing.php');
    911include_once(dirname(__FILE__).'/UpdateTrace.php');
    1012include_once(dirname(__FILE__).'/DefaultConfig.php');
    1113include_once(dirname(__FILE__).'/../Global.php');
    1214
    13 class Core extends Application
     15class Core extends System
    1416{
    15   var $Pages;
    16   var $ShowPage;
    17   var $BaseURL;
    18   var $Config;
    19   var $HeadItems;
    20   var $Bars;
    21   /** @var FormManager */
    22   var $FormManager;
     17  public bool $ShowPage;
     18  public string $BaseURL;
     19  public array $Config;
     20  public array $HeadItems;
     21  public array $Bars;
     22  public array $PathItems;
     23  public FormManager $FormManager;
     24  public BaseView $BaseView;
    2325
    2426  function __construct()
     
    6567    $this->RegisterPageBar('TopLeft');
    6668
    67     // Register and start existing modules
    68     $this->Setup = new Setup($this);
    69     $this->Setup->Start();
    70     if ($this->Setup->CheckState())
     69    $this->StartModules();
     70  }
     71
     72  function StartModules(): void
     73  {
     74    $ModuleSetup = $this->ModuleManager->LoadModule(dirname(__FILE__).'/../Packages/Common/Modules/ModuleSetup.php');
     75    $ModuleSetup->Install();
     76    $ModuleSetup->Start();
     77    $this->ModuleManager->LoadModules();
     78    $this->ModuleManager->LoadModule(dirname(__FILE__).'/../Packages/Common/Modules/ModuleAdmin.php');
     79    if (file_exists($this->ModuleManager->FileName)) $this->ModuleManager->LoadState();
     80    if (ModuleSetup::Cast($ModuleSetup)->CheckState())
    7181    {
    72       $this->ModuleManager->Start();
     82      $this->ModuleManager->StartAll(array(ModuleCondition::Enabled));
    7383    }
    7484  }
    7585
    76   function Run()
     86  function Run(): void
    7787  {
    7888    $this->RunCommon();
     
    98108    echo($this->BaseView->GetOutput($Page));
    99109  }
    100 
    101   function RegisterPage($Path, $Handler)
    102   {
    103     if (is_array($Path))
    104     {
    105       $Page = &$this->Pages;
    106       $LastKey = array_pop($Path);
    107       foreach ($Path as $PathItem)
    108       {
    109         $Page = &$Page[$PathItem];
    110       }
    111       if (!is_array($Page)) $Page = array('' => $Page);
    112       $Page[$LastKey] = $Handler;
    113     } else $this->Pages[$Path] = $Handler;
    114   }
    115 
    116   function UnregisterPage($Path)
    117   {
    118     unset($this->Pages[$Path]);
    119   }
    120 
     110 
    121111  function RegisterPageBar($Name)
    122112  {
     
    148138  }
    149139
    150   function Link($Target)
     140  function Link($Target): string
    151141  {
    152142    return $this->BaseURL.$Target;
    153143  }
    154 }
    155144
    156 class PageMissing extends Page
    157 {
    158   function __construct($System)
     145  static function Cast(System $System): Core
    159146  {
    160     parent::__construct($System);
    161     $this->ParentClass = '';
    162     $this->Title = T('Page not found');
    163   }
    164 
    165   function Show()
    166   {
    167     Header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
    168     return '<h3 align="center">'.T('Required page not found').'</h3>';
     147    if ($System instanceof Core)
     148    {
     149      return $System;
     150    }
     151    throw new Exception('Expected Core type but '.gettype($System));
    169152  }
    170153}
  • trunk/Application/Version.php

    r6 r8  
    66// and system will need database update.
    77
    8 $Revision = 6;
    9 $DatabaseRevision = 6;
    10 $ReleaseTime = strtotime('2020-04-14');
     8$Revision = 8;
     9$DatabaseRevision = 8;
     10$ReleaseTime = strtotime('2023-06-01');
  • trunk/Modules/Map/Map.php

    r7 r8  
    11<?php
    2 
    3 class ModuleMap extends AppModule
    4 {
    5   function __construct($System)
    6   {
    7     parent::__construct($System);
    8     $this->Name = 'Map';
    9     $this->Version = '1.0';
    10     $this->Creator = 'Chronos';
    11     $this->License = 'GNU/GPL';
    12     $this->Description = 'Map';
    13     $this->Dependencies = array();
    14   }
    15 
    16   function DoStart()
    17   {
    18   }
    19 
    20   function DoInstall()
    21   {
    22   }
    23 
    24   function DoUninstall()
    25   {
    26   }
    27 
    28   function DoUpgrade()
    29   {
    30 
    31   }
    32 }
    332
    343class Map extends Model
     
    4110  var $Key;
    4211
    43   function __construct(Application $System)
     12  function __construct(Core $System)
    4413  {
    4514    parent::__construct($System);
     
    7039}
    7140
    72 class MapSeznam extends Map
    73 {
    74   function Geolocate($Text)
    75   {
    76     //new SMap.Geocoder(query, odpoved);
    77   }
    7841
    79   function Show()
    80   {
    81     $Output .= '<div id="m" style="height:380px"></div>';
    82     $Output .= '<script type="text/javascript">
    83             var centerMap = SMap.Coords.fromWGS84(14.40, 50.08);
    84 var m = new SMap(JAK.gel("m"), centerMap, 16);
    85 var l = m.addDefaultLayer(SMap.DEF_BASE).enable();
    86 m.addDefaultControls();
    87 
    88 
    89 var nalezeno = function(route) {
    90     var vrstva = new SMap.Layer.Geometry();
    91     m.addLayer(vrstva).enable();
    92 
    93     var coords = route.getResults().geometry;
    94     var cz = m.computeCenterZoom(coords);
    95     m.setCenterZoom(cz[0], cz[1]);
    96     var g = new SMap.Geometry(SMap.GEOMETRY_POLYLINE, null, coords);
    97     vrstva.addGeometry(g);
    98 }
    99 
    100 var coords = [
    101     SMap.Coords.fromWGS84(14.434, 50.084),
    102     SMap.Coords.fromWGS84(16.600, 49.195)
    103 ];
    104 var route = new SMap.Route(coords, nalezeno);
    105             </script>';
    106     $this->System->HeadItems[] = '<script src="//api.mapy.cz/loader.js"></script>
    107         <script>Loader.load()</script>';
    108 
    109     return $Output;
    110   }
    111 }
    112 
    113 class MapGoogle extends Map
    114 {
    115   function Route()
    116   {
    117     $Origins = array();
    118     $Destinations = array();
    119     foreach ($this->Path as $Index => $PathItem)
    120     if ($Index > 0)
    121     {
    122        if ($Index == 1) $Origins[] = $this->Path[$Index - 1];
    123        $Destinations[] = $this->Path[$Index];
    124     }
    125     $URL = 'https://maps.googleapis.com/maps/api/distancematrix/json'.
    126       '?origins='.implode('|', $Origins).'&destinations='.implode('|', $Destinations).'&key='.$this->Key;
    127     $Result = file_get_contents($URL);
    128     $Points = array(array('Destination' => $this->Path[0], 'Distance' => 0, 'Duration' => 0));
    129     $I = 1;
    130     while (strpos($Result, '"distance"') !== false) {
    131       $Distance = trim($this->Parse($Result, '"value" :', '}'));
    132       $Duration = trim($this->Parse($Result, '"value" :', '}'));
    133       $Points[] = array('Destination' => $this->Path[$I], 'Distance' => $Distance, 'Duration' => $Duration);
    134       $I++;
    135     }
    136     return $Points;
    137   }
    138 
    139   function Show()
    140   {
    141     $WayPoints = $this->Path;
    142     array_shift($WayPoints);
    143     array_pop($WayPoints);
    144     if (count($WayPoints) > 0)
    145       $WaypointsQuery = '&waypoints='.implode('|', $WayPoints);
    146       else $WaypointsQuery = '';
    147 
    148     $Output = '<iframe width="'.$this->Width.'" height="'.$this->Height.'" frameborder="0" scrolling="no" '.
    149       'marginheight="0" marginwidth="0" src="'.'https://www.google.com/maps/embed/v1/directions'.
    150       '?key='.$this->Key.'&origin='.$this->Path[0].$WaypointsQuery.
    151       '&destination='.$this->Path[count($this->Path) - 1].''.
    152       '" style="border: 1px solid black"></iframe>';
    153     return $Output;
    154   }
    155 }
    156 
    157 class MapOSM extends Map
    158 {
    159   function Geolocate($Text)
    160   {
    161     // http://wiki.openstreetmap.org/wiki/Nominatim
    162     $URL = 'http://nominatim.openstreetmap.org/search.php?q='.urlencode($Text).'&viewbox=&format=xml&limit=1';
    163     $Result = file_get_contents($URL);
    164     $Result = substr($Result, strpos($Result, 'boundingbox="') + 13);
    165     $BoundingBox = substr($Result, 0, strpos($Result, '"') - 1);
    166     $Parts = explode(',', $BoundingBox);
    167     $Zoom = 1 / ($Parts[1] - $Parts[0]) * 2;
    168     $Result = substr($Result, strpos($Result, 'lat=\'') + 5);
    169     $Latitude = substr($Result, 0, strpos($Result, '\'') - 1);
    170     $Result = substr($Result, strpos($Result, 'lon=\'') + 5);
    171     $Longitude = substr($Result, 0, strpos($Result, '\'') - 1);
    172     return array('Latitude' => $Latitude, 'Longitude' => $Longitude, 'BoundingBox' => $BoundingBox, 'Zoom' => $Zoom);
    173   }
    174 
    175   function Route($TextPathItems)
    176   {
    177     $this->Points = array();
    178     foreach ($TextPathItems as $TextPathItem)
    179     {
    180       $Result = $this->Geolocate($TextPathItem);
    181       $this->Points[] = array('Longitude' => $Result['Longitude'],
    182         'Latitude' => $Result['Latitude']);
    183     }
    184 
    185     $WayPoints = array();
    186     foreach ($this->Points as $Point)
    187     {
    188       $WayPoints[] = $Point['Longitude'];
    189       $WayPoints[] = $Point['Latitude'];
    190     }
    191 
    192     // http://wiki.openstreetmap.org/wiki/OpenRouteService#OpenRouteService_API
    193     $this->Key = 'ee0b8233adff52ce9fd6afc2a2859a28';
    194     $URL = 'http://openls.geog.uni-heidelberg.de/route?api_key='.
    195       $this->Key.'&start='.implode(',', $this->Points[0]).'&end='.implode(',', $this->Points[count($this->Points) - 1]).
    196       '&via='.implode(',', $WayPoints).'&lang=en&distunit=M&routepref=Car&weighting=Fastest&avoidAreas='.
    197       '&useTMC=false&noMotorways=false&noTollways=false&noUnpavedroads=false&noSteps=false'.
    198       '&noFerries=false&elevation=false&surface=false&instructions=false';
    199     $Result = file_get_contents($URL);
    200     echo($Result);
    201     $Separator = '<xls:TotalDistance uom="M" value="';
    202     $Result = substr($Result, strpos($Result, $Separator) + strlen($Separator));
    203     $TotalDistance = substr($Result, 0, strpos($Result, '"/>') - 1);
    204     $Separator = '<xls:TotalTime>PT2H3M48S';
    205     $Result = substr($Result, strpos($Result, $Separator) + strlen($Separator));
    206     $TotalTime = substr($Result, 0, strpos($Result, '"/>') - 1);
    207 
    208     $Points = array();
    209     $Separator = '<gml:pos>';
    210     while (strpos($Result, $Separator) !== false)
    211     {
    212       $Result = substr($Result, strpos($Result, $Separator) + strlen($Separator));
    213       $Pos = substr($Result, 0, strpos($Result, '</gml:pos>') - 1);
    214       $PosParts = explode(' ', $Pos);
    215       $Points[] = array('Longitude' => $PosParts[0], 'Latitude' => $PosParts[1]);
    216     }
    217     return array('TotalDistance' => $TotalDistance, 'TotalTime' => $TotalTime,
    218       'Points' => $Points);
    219   }
    220 
    221   function Show()
    222   {
    223     $WayPoints = array();
    224     foreach ($this->Points as $Point)
    225     {
    226       $WayPoints[] = $Point['Longitude'];
    227       $WayPoints[] = $Point['Latitude'];
    228     }
    229 
    230     $Output = '<iframe width="'.$this->Width.'" height="'.$this->Height.'" frameborder="0" scrolling="no" '.
    231       'marginheight="0" marginwidth="0" src="'.
    232       'http://www.openrouteservice.org/?pos=8.925670599999979,52.28150333376007&zoom='.
    233       $this->Zoom.'&layer=0B00&routeOpt=Car&wp='.implode(',', $WayPoints).
    234       '&lang=en&routeLang=en&distUnit=m&routeWeight=Fastest'.
    235       'style="border: 1px solid black"></iframe>';
    236 /*    $Latitude = $this->Pos['Latitude'];
    237     $Longitude = $this->Pos['Longitude'];
    238     $Zoom = $this->Zoom;
    239     $BoundingBox = array($Longitude - 1 / $Zoom, $Latitude - 1 / $Zoom, $Longitude + 1 / $Zoom, $Latitude + 1 / $Zoom);
    240     $Output = '<iframe width="'.$this->Width.'" height="'.$this->Height.'" frameborder="0" scrolling="no" '.
    241       'marginheight="0" marginwidth="0" src="http://www.openstreetmap.org/export/embed.html'.
    242       '?bbox='.implode(',', $BoundingBox).'&amp;layer=mapnik&amp;marker='.$Latitude.','.$Longitude.'" '.
    243       'style="border: 1px solid black"></iframe>'.
    244       '<p><small><a href="http://www.openstreetmap.org/'.
    245       '?lat='.$Latitude.'&amp;lon='.$Longitude.';zoom='.$Zoom.'&amp;layers=M&amp;mlat='.$Latitude.'&amp;mlon='.$Longitude.'">View Larger Map</a></small></p>';
    246       */
    247     return $Output;
    248   }
    249 }
  • trunk/Modules/Ride/Ride.php

    r7 r8  
    11<?php
    22
    3 include_once(dirname(__FILE__).'/RideModel.php');
     3class Ride extends Model
     4{
     5  function Add($Track, $SeatCount, $Car, $Details)
     6  {
     7    $this->Database->insert('Ride', array('SeatCount' => $SeatCount, 'Details' => $Details,
     8      'Car' => $Car, 'Driver' => $this->System->ModuleManager->Modules['User']->User['Id']));
     9    $RideId = $this->Database->insert_id;
    410
    5 class ModuleRide extends AppModule
    6 {
    7   function __construct($System)
    8   {
    9     parent::__construct($System);
    10     $this->Name = 'Ride';
    11     $this->Version = '1.0';
    12     $this->Creator = 'Chronos';
    13     $this->License = 'GNU/GPL';
    14     $this->Description = 'Ride management';
    15     $this->Dependencies = array('User', 'Map');
    16   }
    17 
    18   function DoStart()
    19   {
    20     $this->System->RegisterPage('', 'PageMain');
    21     $this->System->RegisterPage('nova-jizda', 'PageNewRide');
    22     $this->System->RegisterPage('jizda', 'PageRideDetail');
    23     $this->System->RegisterPage('jizdy', 'PageRideList');
    24     $this->System->RegisterPageBarItem('TopLeft', 'Logo', array($this, 'ShowLogo'));
    25   }
    26 
    27   function DoInstall()
    28   {
    29     $this->Database->query('CREATE TABLE `CarManufacturer` (
    30   `Id` int(11) NOT NULL AUTO_INCREMENT,
    31   `Name` varchar(255) NOT NULL,
    32   PRIMARY KEY (`Id`)
    33 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;');
    34     $this->Database->query('CREATE TABLE `CarModel` (
    35   `Id` int(11) NOT NULL AUTO_INCREMENT,
    36   `Name` varchar(255) NOT NULL,
    37   `Manufacturer` int(11) NOT NULL,
    38   PRIMARY KEY (`Id`),
    39   KEY `Manufacturer` (`Manufacturer`)
    40 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;');
    41     $this->Database->query('ALTER TABLE `CarModel`
    42     ADD CONSTRAINT `CarModel_ibfk_1` FOREIGN KEY (`Manufacturer`) REFERENCES `CarManufacturer` (`Id`);');
    43     $this->Database->query('CREATE TABLE `Car` (
    44   `Id` int(11) NOT NULL AUTO_INCREMENT,
    45   `Owner` int(11) NOT NULL,
    46   `Photo` int(11) DEFAULT NULL,
    47   `Model` int(11) NOT NULL,
    48   PRIMARY KEY (`Id`),
    49   KEY `Owner` (`Owner`),
    50   KEY `Model` (`Model`)
    51 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;');
    52    $this->Database->query('ALTER TABLE `Car`
    53   ADD CONSTRAINT `Car_ibfk_1` FOREIGN KEY (`Owner`) REFERENCES `User` (`Id`),
    54   ADD CONSTRAINT `Car_ibfk_2` FOREIGN KEY (`Model`) REFERENCES `CarModel` (`Id`);');
    55      $this->Database->query('CREATE TABLE `Ride` (
    56   `Id` int(11) NOT NULL AUTO_INCREMENT,
    57   `Driver` int(11) NOT NULL,
    58   `SeatCount` int(11) NOT NULL,
    59   `Car` int(11) NOT NULL,
    60   `Details` text NOT NULL,
    61   PRIMARY KEY (`Id`),
    62   KEY `Driver` (`Driver`),
    63   KEY `Car` (`Car`)
    64 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;');
    65     $this->Database->query('ALTER TABLE `Ride`
    66   ADD CONSTRAINT `Ride_ibfk_1` FOREIGN KEY (`Driver`) REFERENCES `User` (`Id`),
    67   ADD CONSTRAINT `Ride_ibfk_2` FOREIGN KEY (`Car`) REFERENCES `Car` (`Id`);');
    68     $this->Database->query('CREATE TABLE `RideStop` (
    69   `Id` int(11) NOT NULL AUTO_INCREMENT,
    70   `Ride` int(11) NOT NULL,
    71   `Time` datetime NOT NULL,
    72   `Place` varchar(255) NOT NULL,
    73   `Sequence` int(11) NOT NULL,
    74   `Price` int(11) NOT NULL,
    75   `PassengerCount` int(11) NOT NULL,
    76   PRIMARY KEY (`Id`),
    77   KEY `Ride` (`Ride`)
    78 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;');
    79     $this->Database->query('ALTER TABLE `RideStop`
    80   ADD CONSTRAINT `RideStop_ibfk_1` FOREIGN KEY (`Ride`) REFERENCES `Ride` (`Id`);');
    81    $this->Database->query('CREATE TABLE `Passenger` (
    82   `Id` int(11) NOT NULL AUTO_INCREMENT,
    83   `Ride` int(11) NOT NULL,
    84   `User` int(11) NOT NULL,
    85   `SeatCount` int(11) NOT NULL,
    86   `RideStopFrom` int(11) NOT NULL,
    87   `RideStopTo` int(11) NOT NULL,
    88   PRIMARY KEY (`Id`),
    89   KEY `User` (`User`),
    90   KEY `Ride` (`Ride`),
    91   KEY `RideStopFrom` (`RideStopFrom`),
    92   KEY `RideStopTo` (`RideStopTo`)
    93 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;');
    94    $this->Database->query('ALTER TABLE `Passenger`
    95   ADD CONSTRAINT `Passenger_ibfk_1` FOREIGN KEY (`Ride`) REFERENCES `Ride` (`Id`),
    96   ADD CONSTRAINT `Passenger_ibfk_2` FOREIGN KEY (`User`) REFERENCES `User` (`Id`),
    97   ADD CONSTRAINT `Passenger_ibfk_3` FOREIGN KEY (`RideStopFrom`) REFERENCES `RideStop` (`Id`),
    98   ADD CONSTRAINT `Passenger_ibfk_4` FOREIGN KEY (`RideStopTo`) REFERENCES `RideStop` (`Id`);');
    99     $this->InsertData();
    100   }
    101 
    102   function InsertData()
    103   {
    104     $this->Database->query('INSERT INTO `CarManufacturer` (`Id`, `Name`) VALUES '.
    105       '(NULL, "Škoda"), (NULL, "Nissan"), (NULL, "Mitsubishi"), (NULL, "Fiat"), '.
    106       '(NULL, "Dacia"), (NULL, "KIA"), (NULL, "Hyundai"), (NULL, "Ford"), '.
    107       '(NULL, "Opel"), (NULL, "Volkswagen"), (NULL, "Citroen"), (NULL, "Peugeot"), '.
    108       '(NULL, "Tesla"), (NULL, "Audi"), (NULL, "BMW"), (NULL, "Chevrolet"), '.
    109       '(NULL, "Suzuki"), (NULL, "Toyota"), (NULL, "Mercedes-benz"), (NULL, "Seat"),'.
    110       '(NULL, "Volvo"), (NULL, "Renault"), (NULL, "Mazda");');
    111     $this->Database->query('INSERT INTO `CarModel` (`Id`, `Name`, `Manufacturer`) VALUES '.
    112       '(NULL, "Rapid", 1), (NULL, "Octavia", 1), (NULL, "Fabia", 1), (NULL, "Felicia", 1), '.
    113       '(NULL, "Superb", 1);');
    114   }
    115 
    116   function DoUninstall()
    117   {
    118     $this->Database->query('DROP TABLE IF EXISTS `Passenger`');
    119     $this->Database->query('DROP TABLE IF EXISTS `RideStop`');
    120     $this->Database->query('DROP TABLE IF EXISTS `Ride`');
    121     $this->Database->query('DROP TABLE IF EXISTS `Car`');
    122     $this->Database->query('DROP TABLE IF EXISTS `CarModel`');
    123     $this->Database->query('DROP TABLE IF EXISTS `CarManufacturer`');
    124   }
    125 
    126   function DoUpgrade()
    127   {
    128 
    129   }
    130 
    131   function InsertSampleData()
    132   {
    133     $Cities = array('Praha', 'Brno', 'Ostrava', 'Olomouc', 'Liberec', 'Plzeň',
    134       'Humpolec', 'Zlín', 'Přerov', 'České Budějovice', 'Jihlava', 'Ústí nad Labem',
    135       'Hradec Králové', 'Pardubice', 'Mohelnice', 'Břeclav', 'Znojmo', 'Semily',
    136       'Tábor', 'Opava', 'Karviná', 'Pelhřimov', 'Osoblaha', 'Broumov', 'Jirkov',
    137       'Aš', 'Kutná Hora', 'Kolín', 'Strakonice', 'Tachov', 'Domažlice', 'Beroun',
    138       'Most', 'Chomutov', 'Mělník', 'Mladá Boleslav', 'Svitavy', 'Šumperk',
    139       'Litomyšl', 'Chrudim', 'Blansko', 'Hodonín', 'Rosice', 'Uherský Brod',
    140       'Vsetín', 'Nový Jičín', 'Prostějov', 'Vyškov', 'Mohelnice', 'Ústí nad Orlicí');
    141 
    142     for ($I = 0; $I < 100; $I++)
     11    foreach($_SESSION['Track'] as $Index => $TrackItem)
    14312    {
    144       $Stops = array_fill(0, random(5), '');
    145       for ($J = 0; $J < count($Stops); $J++)
    146         $Stops[$J] = $Cities[random(count($Cities))];
    147 
    148       $Ride = new Ride();
    149       $StartTime = time() - random(60*60*24*365);
    150       $StopCount = random(5);
    151       $Ride->Add($Stops, $StartTime, $SeatCount);
     13      $this->Database->insert('RideStop', array(
     14        'Ride' => $RideId,
     15        'Place' => $TrackItem['Destination'],
     16        'Time' => TimeToMysqlDateTime($TrackItem['Time']),
     17        'Price' => $TrackItem['Price'],
     18        'Sequence' => $Index,
     19        'PassengerCount' => 0,
     20      ));
    15221    }
    15322  }
    15423
    155   function ShowLogo()
     24  function GetTrack()
    15625  {
    157     $Output = '<img src="" width="200" height="50" alt="Logo"/> '.
    158       '<a href="'.$this->System->Link('/jizdy/').'">Hledat jízdu</a> nebo '.
    159       '<a href="'.$this->System->Link('/nova-jizda/').'">Nabídnout jízdu</a>';
    160     return $Output;
     26    return($Track);
    16127  }
    16228
    163   function UpdatePassengerCount($RideId)
     29  function Remove($Id)
    16430  {
    165     $DbResult = $this->System->Database->select('RideStop', 'COUNT(*) AS RideStopCount', 'Ride='.$RideId);
    166     $DbRow = $DbResult->fetch_assoc();
    167 
    168     $Stops = array_fill(0, $DbRow['RideStopCount'], 0);
    169     $this->System->Database->update('RideStop', 'Ride='.$RideId, array('PassengerCount' => 0));
    170     $DbResult = $this->System->Database->query('SELECT PassengerRideStopFrom.Sequence AS SequenceFrom, '.
    171         'PassengerRideStopTo.Sequence AS SequenceTo, Passenger.SeatCount FROM Passenger '.
    172         'LEFT JOIN RideStop AS PassengerRideStopFrom ON PassengerRideStopFrom.Id=Passenger.RideStopFrom '.
    173         'LEFT JOIN RideStop AS PassengerRideStopTo ON PassengerRideStopTo.Id=Passenger.RideStopTo '.
    174         'WHERE Passenger.Ride='.$RideId);
    175     while ($DbRow = $DbResult->fetch_assoc())
    176     {
    177       for ($I = $DbRow['SequenceFrom'] + 1; $I <= $DbRow['SequenceTo']; $I++)
    178       {
    179         $Stops[$I] = $Stops[$I] + $DbRow['SeatCount'];
    180       }
    181     }
    182     foreach ($Stops as $Index => $Stop)
    183     {
    184       $this->System->Database->update('RideStop', 'Ride='.$RideId.' AND Sequence='.$Index, array('PassengerCount' => $Stop));
    185     }
     31    $this->Database->delete('Passenger', 'Ride='.$Id);
     32    $this->Database->delete('RideStop', 'Ride='.$Id);
     33    $this->Database->delete('Ride', 'Id='.$Id);
    18634  }
    18735}
    188 
    189 class PageRideDetail extends Page
    190 {
    191   function ShowDetail()
    192   {
    193     $RideId = $_GET['id'];
    194     $DbResult = $this->Database->query('SELECT Ride.Details, Ride.Id, Ride.SeatCount, '.
    195       'RideStopFrom.Id AS RideStopFromId, RideStopTo.Id AS RideStopToId, '.
    196       '(SELECT Name FROM User WHERE User.Id=Ride.Driver) AS DriverName, '.
    197       'CONCAT(CarManufacturer.Name, " ", CarModel.Name) AS CarName FROM Ride '.
    198       'JOIN RideStop AS RideStopFrom ON (RideStopFrom.Ride = Ride.Id) AND (RideStopFrom.Place LIKE "%'.$_GET['from'].'%") '.
    199       'JOIN RideStop AS RideStopTo ON (RideStopTo.Ride = Ride.Id) AND (RideStopTo.Place LIKE "%'.$_GET['to'].'%") '.
    200         'LEFT JOIN Car ON Car.Id = Ride.Car '.
    201       'LEFT JOIN CarModel ON CarModel.Id = Car.Model '.
    202       'LEFT JOIN CarManufacturer ON CarManufacturer.Id = CarModel.Manufacturer '.
    203       'WHERE Ride.Id='.$RideId);
    204     $DbRow = $DbResult->fetch_assoc();
    205     $Track = array();
    206     $Stops = array();
    207     $DbResult2 = $this->Database->query('SELECT * FROM RideStop WHERE Ride='.$DbRow['Id'].' ORDER BY Sequence');
    208     while ($DbRow2 = $DbResult2->fetch_assoc())
    209     {
    210       $Track[] = $DbRow2;
    211       $Stops[] = $DbRow2['Place'];
    212     }
    213 
    214     $Output = '<h3>Detail jízdy</h3><table>'.
    215       '<tr><td>Trasa:</td><td>'.implode(' → ', $Stops).'</td></tr>'.
    216       '<tr><td>Odjezd z:</td><td>'.$Track[0]['Place'].'</td></tr>'.
    217       '<tr><td>Příjezd do:</td><td>'.$Track[count($Track) - 1]['Place'].'</td></tr>'.
    218       '<tr><td>Čas odjezdu:</td><td>'.$Track[0]['Time'].'</td></tr>'.
    219       '<tr><td>Podrobnosti:</td><td>'.$DbRow['Details'].'</td></tr>';
    220     $Output .= '</table>';
    221     $Output .= '<form action="?step=2" method="post">'.
    222       'Počet míst: <input type="text" name="seats" value="1"/>'.
    223       '<input type="hidden" name="id" value="'.$RideId.'"/>'.
    224       '<input type="hidden" name="fromid" value="'.$DbRow['RideStopFromId'].'"/>'.
    225       '<input type="hidden" name="toid" value="'.$DbRow['RideStopToId'].'"/>'.
    226       '<input type="submit" value="Rezervovat"/>'.
    227       '</form>';
    228 
    229     $Output .= '<h3>Cestující</h3>'.
    230       '<table class="WideTable">';
    231 
    232     // Load passengers table
    233     $Table = array_fill(0, count($Track), array_fill(0, $DbRow['SeatCount'], NULL));
    234     $Passengers = array();
    235     $DbResult = $this->System->Database->query('SELECT User.Name AS UserName, PassengerRideStopFrom.Sequence AS SequenceFrom, '.
    236       'PassengerRideStopTo.Sequence AS SequenceTo FROM Passenger '.
    237       'LEFT JOIN RideStop AS PassengerRideStopFrom ON PassengerRideStopFrom.Id=Passenger.RideStopFrom '.
    238       'LEFT JOIN RideStop AS PassengerRideStopTo ON PassengerRideStopTo.Id=Passenger.RideStopTo '.
    239       'LEFT JOIN User ON User.Id=Passenger.User '.
    240       'WHERE Passenger.Ride='.$RideId);
    241     while ($Passenger = $DbResult->fetch_assoc())
    242     {
    243       $Passengers[] = $Passenger;
    244       $Seat = 0;
    245       do {
    246         $Check = true;
    247         for ($I = $Passenger['SequenceFrom']; $I < $Passenger['SequenceTo']; $I++)
    248         {
    249           if ($Table[$I][$Seat] != 0) $Check = false;
    250         }
    251         if (!$Check) $Seat++;
    252       } while (!$Check);
    253       for ($I = $Passenger['SequenceFrom']; $I < $Passenger['SequenceTo']; $I++)
    254         $Table[$I][$Seat] = count($Passengers) - 1;
    255     }
    256 
    257     $Output .= '<tr><th>Zastávka / Čas</th><th style="width: 80px">Řidič</th>';
    258     for ($I = 0; $I < $DbRow['SeatCount']; $I++)
    259       $Output .= '<th style="width: 80px">Cestující</th>';
    260     $Output .= '</tr>';
    261     foreach ($Track as $Index => $TrackItem)
    262     {
    263       $Output .= '<tr><td style="height: 100px">'.$TrackItem['Place'].'<br/>'.$TrackItem['Time'].'</td>';
    264       if ($Index == 0) $Output .= '<td rowspan="'.count($Track).'">Řidič</td>';
    265       for ($I = 0; $I < $DbRow['SeatCount']; $I++)
    266       {
    267         if (!is_null($Table[$Index][$I])) {
    268           $Passenger = $Passengers[$Table[$Index][$I]];
    269           if ($Index == $Passenger['SequenceFrom'])
    270           $Output .= '<td rowspan="'.($Passenger['SequenceTo'] - $Passenger['SequenceFrom']).'">'.$Passenger['UserName'].'</td>';
    271         } else {
    272           // Show unused space
    273           if (($Index == 0) or ((($Index - 1) >= 0) and (!is_null($Table[$Index - 1][$I]))))
    274           {
    275             $J = 1;
    276             while ((($Index + $J) < count($Table)) and is_null($Table[$Index + $J][$I])) $J++;
    277             $Output .= '<td rowspan="'.$J.'">&nbsp;</td>';
    278           }
    279         }
    280       }
    281       $Output .= '</tr>';
    282     }
    283     $Output .= '</table>';
    284 
    285 
    286     return $Output;
    287   }
    288 
    289   function Show()
    290   {
    291     if (!array_key_exists('step', $_GET)) $Output = $this->ShowDetail();
    292     else {
    293       if ($_GET['step'] == 2) {
    294         $this->System->Database->insert('Passenger', array(
    295           'Ride' => $_POST['id'],
    296           'User' => $this->System->User->User['Id'],
    297           'SeatCount' => $_POST['seats'],
    298           'RideStopFrom' => $_POST['fromid'],
    299           'RideStopTo' => $_POST['toid'],
    300         ));
    301         $this->System->ModuleManager->Modules['Ride']->UpdatePassengerCount($_POST['id']);
    302         $Output = 'Rezervace dokončena';
    303       }
    304     }
    305     return $Output;
    306   }
    307 }
    308 
    309 class PageMain extends Page
    310 {
    311   function Show()
    312   {
    313     if (array_key_exists('from', $_GET)) $PlaceFrom = $_GET['from'];
    314       else $PlaceFrom = '';
    315     if (array_key_exists('to', $_GET)) $PlaceTo = $_GET['to'];
    316       else $PlaceTo = '';
    317     if (array_key_exists('time', $_GET)) $Time = $_GET['time'];
    318       else $Time = '';
    319     $Output = '<table style="width: 100%; margin-top: 100px; margin-bottom: 100px;"><tr><td style="text-align: center">'.
    320       '<div><h3>Vyhledat jízdu</h3>'.
    321       '<form style="display: inline;" method="get" action="'.$this->System->Link('/jizdy/').'">'.
    322       'Odkud: <input type="text" name="from" value="'.$PlaceFrom.'"/> '.
    323       'Kam: <input type="text" name="to" value="'.$PlaceTo.'"/> '.
    324       'Čas: <input type="text" name="time" value="'.$Time.'"/> '.
    325       '<input type="submit" value="Hledat"/>'.
    326       '</form></div></td></tr></table>';
    327     return $Output;
    328   }
    329 }
    330 
    331 class PageRideList extends Page
    332 {
    333   function Show()
    334   {
    335     if (array_key_exists('from', $_GET)) $PlaceFrom = $_GET['from'];
    336       else $PlaceFrom = '';
    337     if (array_key_exists('to', $_GET)) $PlaceTo = $_GET['to'];
    338       else $PlaceTo = '';
    339     if (array_key_exists('time', $_GET)) $Time = $_GET['time'];
    340       else $Time = '';
    341     $Output = '<table style="width: 100%"><tr><td style="text-align: center;">'.
    342       '<form style="display: inline;" method="get" action="'.$this->System->Link('/').'">'.
    343       'Odkud: <input type="text" name="from" value="'.$PlaceFrom.'"/> '.
    344       'Kam: <input type="text" name="to" value="'.$PlaceTo.'"/> '.
    345       'Čas: <input type="text" name="time" value="'.$Time.'"/> '.
    346       '<input type="submit" value="Hledat"/>'.
    347       '</form></td></tr></table>';
    348     if (array_key_exists('from', $_GET) and array_key_exists('to', $_GET)) {
    349       $Output .= $this->ShowRides($_GET['from'], $_GET['to']);
    350     } else $Output .= $this->ShowRides('', '');
    351     return $Output;
    352   }
    353 
    354   function ShowRides($PlaceFrom, $PlaceTo)
    355   {
    356     $Output = '<h3>Jízdy:</h3>';
    357     $Output .= '<table>';
    358     $Query = 'SELECT Ride.Id, Ride.SeatCount, User.Name AS DriverName, User.BirthDate, '.
    359       'CONCAT(CarManufacturer.Name, " ", CarModel.Name) AS CarName ';
    360     if ((trim($PlaceFrom) != '') and (trim($PlaceTo != '')))
    361       $Query .= ', (SELECT COALESCE(MAX(RideStop.PassengerCount), 0) FROM RideStop '.
    362       'WHERE (RideStop.Ride=Ride.Id) AND (RideStop.Sequence > RideStopFrom.Sequence) AND '.
    363       '(RideStop.Sequence <= RideStopTo.Sequence)) AS PassengerCount ';
    364     else
    365       $Query .= ', (SELECT COALESCE(MAX(RideStop.PassengerCount), 0) FROM RideStop '.
    366        'WHERE (RideStop.Ride=Ride.Id)) AS PassengerCount ';
    367 
    368     $Query .= 'FROM Ride '.
    369       'LEFT JOIN Car ON Car.Id = Ride.Car '.
    370       'LEFT JOIN CarModel ON CarModel.Id = Car.Model '.
    371       'LEFT JOIN CarManufacturer ON CarManufacturer.Id = CarModel.Manufacturer '.
    372       'LEFT JOIN User ON User.Id=Ride.Driver ';
    373     if ((trim($PlaceFrom) != '') and (trim($PlaceTo != '')))
    374       $Query .= 'JOIN RideStop AS RideStopFrom ON (RideStopFrom.Ride = Ride.Id) AND (RideStopFrom.Place LIKE "%'.$PlaceFrom.'%") '.
    375         'JOIN RideStop AS RideStopTo ON (RideStopTo.Ride = Ride.Id) AND (RideStopTo.Place LIKE "%'.$PlaceTo.'%") '.
    376         'WHERE (RideStopFrom.Sequence < RideStopTo.Sequence)';
    377     $Query .= 'LIMIT 10';
    378     $DbResult = $this->Database->query($Query);
    379     while ($DbRow = $DbResult->fetch_assoc())
    380     {
    381       $Stops = array();
    382       $Price = 0;
    383       $DbResult2 = $this->Database->query('SELECT * FROM RideStop WHERE Ride='.$DbRow['Id'].' ORDER BY Sequence');
    384       while ($DbRow2 = $DbResult2->fetch_assoc())
    385       {
    386         $Stops[] = $DbRow2['Place'];
    387         $Price += $DbRow2['Price'];
    388       }
    389 
    390       if ($DbRow['BirthDate'] != '') $Age = ' ('.round((time() - MysqlDateToTime($DbRow['BirthDate'])) / (3600*24*364.25)).' let)';
    391         else $Age = '';
    392       $Output .= '<tr><td>Řidič:</td><td>'.$DbRow['DriverName'].$Age.'</td>'.
    393         '<td colspan="4"><a href="'.$this->System->Link('/jizda/?id='.$DbRow['Id'].'&from='.$PlaceFrom.'&to='.$PlaceTo).'">Ukázat</a></td></tr>'.
    394         '<tr><td>Trasa:</td><td>'.implode(' → ', $Stops).'</td></tr>'.
    395         '<tr><td>Cena:</td><td>'.$Price.' Kč</td></tr>'.
    396         '<tr><td>Volných míst:</td><td>'.($DbRow['SeatCount'] - $DbRow['PassengerCount']).'</td></tr>'.
    397         '<tr><td>Auto:</td><td>'.$DbRow['CarName'].'</td></tr>'.
    398         '<tr><td>&nbsp;</td></tr>';
    399     }
    400     $Output .= '</table>';
    401 
    402     return $Output;
    403   }
    404 }
    405 
    406 function time_elapsed($secs)
    407 {
    408   $bit = array(
    409     'y' => $secs / 31556926 % 12,
    410     'w' => $secs / 604800 % 52,
    411     'd' => $secs / 86400 % 7,
    412     'h' => $secs / 3600 % 24,
    413     'm' => $secs / 60 % 60,
    414     's' => $secs % 60
    415   );
    416 
    417   $ret = array();
    418   foreach ($bit as $k => $v)
    419     if ($v > 0)$ret[] = $v . $k;
    420 
    421   return join(' ', $ret);
    422 }
    423 
    424 class PageNewRide extends Page
    425 {
    426   function Show()
    427   {
    428     if (!array_key_exists('step', $_GET))
    429     {
    430       $Output = '<script>
    431 function insertAfter(referenceNode, newNode)
    432 {
    433     referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    434 }
    435 
    436 function add_before(name)
    437 {
    438     var objTo = document.getElementById(name)
    439     var divtest = document.createElement("div");
    440     divtest.innerHTML = \'<tr><td>Zastávka:</td><td><input type="text" name="ridestop1"/></td></tr>\';
    441 
    442     objTo.parentNode.insertBefore(divtest, objTo.childNodes[0])
    443 }
    444 
    445 function add_after(name)
    446 {
    447     var objTo = document.getElementById(name)
    448     var divtest = document.createElement("div");
    449     divtest.innerHTML = \'<tr><td>Zastávka:</td><td><input type="text" name="ridestop1"/></td></tr>\';
    450 
    451     insertAfter(objTo, divtest)
    452 }
    453           </script>'.
    454         '<form method="get" action="'.$this->System->Link('/nova-jizda/').'">'.
    455         '<table>'.
    456         '<tr><td colspan="2"><strong>Trasa:</strong></td></tr>'.
    457 
    458         '<tr><td>Počátek:</td><td><input type="text" name="from"/></td></tr>'.
    459         '<tr><td>Zastávka:</td><td><input type="text" name="middle"/></td></tr>'.
    460         '<tr><td>Konec:</td><td><input type="text" name="to"/></td></tr>'.
    461 
    462         '<tr><td colspan="2"><br><strong>Parametry jízdy:</strong></td></tr>'.
    463         '<tr><td>Čas odjezdu:</td><td><input type="text" name="time-from"/></td></tr>'.
    464         '<tr><td>Počet míst pro cestující:</td><td><input type="text" name="seats"/></td></tr>'.
    465         '</table>'.
    466         '<input type="hidden" name="step" value="2"/><br/>'.
    467         '<input type="submit" value="Pokračovat"/>'.
    468         '</form>';
    469     } else {
    470       if ($_GET['step'] == '2') {
    471         $TimeFrom = strtotime($_GET['time-from']);
    472         $Output = '<table style="width: 100%"><tr><td>';
    473         $Output .= '<form method="post" action="'.$this->System->Link('/nova-jizda/?step=3').'">'.
    474         '<input type="hidden" name="from" value="'.$_GET['from'].'"/><br/>'.
    475         '<input type="hidden" name="to" value="'.$_GET['to'].'"/><br/>'.
    476         '<input type="hidden" name="time-from" value="'.$_GET['time-from'].'"/><br/>'.
    477         '<input type="hidden" name="seats" value="'.$_GET['seats'].'"/><br/>'.
    478         '<input type="hidden" name="step" value="3"/><br/>'.
    479         'Popis:<br/><textarea name="desc"></textarea><br/>'.
    480         'Auto: <select name="car">';
    481         $DbResult = $this->Database->query('SELECT Car.Id, CONCAT(CarManufacturer.Name, " ", CarModel.Name) AS ModelName FROM Car '.
    482           'LEFT JOIN CarModel ON CarModel.Id=Car.Model '.
    483           'LEFT JOIN CarManufacturer ON CarManufacturer.Id = CarModel.Manufacturer '.
    484           'WHERE Car.Owner='.$this->System->User->User['Id']);
    485         while ($DbRow = $DbResult->fetch_assoc())
    486         {
    487           $Output .= '<option value="'.$DbRow['Id'].'"/>'.$DbRow['ModelName'].'</option>';
    488         }
    489         $Output .= '</select>'.
    490           '<input type="submit" value="Vytvořit"/>'.
    491           '</form>';
    492         $Map = new MapGoogle($this->System);
    493         $Map->Key = 'AIzaSyDQ-tOjP9mO8ZpSEuBc5_oCRg30rpQZiBI';
    494         $Map->Width = 400;
    495         $Map->Height = 300;
    496         $Map->Path = array($_GET['from'], $_GET['to']);
    497         //$Map->Path = array('Praha', 'Brno', 'Zlín', 'Vsetín');
    498         $Track = $Map->Route();
    499         $Output .= '<h3>Trasa</h3>';
    500         $PricePerKm = 0.8;
    501         $Output .= '<table class="WideTable"><tr><th>Úsek</th><th>Odjezd</th><th>Trvání</th><th>Vzdálenost [km]</th><th>Cena [Kč]</th></tr>';
    502         foreach ($Track as $Index => $TrackItem)
    503         {
    504           if ($Index > 0)
    505           {
    506             $Track[$Index]['Time'] = $TimeFrom + $Track[$Index - 1]['Duration'];
    507             $RelDistance = $TrackItem['Distance'] - $Track[$Index - 1]['Distance'];
    508             $RelDuration = $TrackItem['Duration'] - $Track[$Index - 1]['Duration'];
    509             $Track[$Index]['Price'] = round($PricePerKm * $RelDistance / 1000);
    510             $Output .= '<tr><td>'.$Map->Path[$Index - 1].' → '.$TrackItem['Destination'].'</td>'.
    511               '<td>'.TimeToMysqlDateTime($Track[$Index]['Time']).'</td>'.
    512               '<td>'.time_elapsed($RelDuration).'</td>'.
    513               '<td>'.round($RelDistance / 1000).'</td>'.
    514               '<td>'.$Track[$Index]['Price'].'</td></tr>';
    515 
    516           } else {
    517             $Track[$Index]['Time'] = $TimeFrom;
    518             $Track[$Index]['Price'] = 0;
    519           }
    520         }
    521         $Output .= '<tr><td>'.$Map->Path[0].' → '.$Map->Path[count($Map->Path) - 1].'</td>'.
    522           '<td>'.TimeToMysqlDateTime($Track[0]['Time']).'</td>'.
    523           '<td>'.time_elapsed($Track[count($Track) - 1]['Duration']).'</td>'.
    524           '<td>'.round($Track[count($Track) - 1]['Distance'] / 1000).'</td>'.
    525           '<td>'.round($PricePerKm * $Track[count($Track) - 1]['Distance'] / 1000).'</td></tr>';
    526         $Output .= '</table><br/>';
    527         $Output .= 'Vzdálenost: '.round($Track[count($Track) - 1]['Distance'] / 1000, 1).' km<br/>';
    528         $Output .= 'Délka jízdy: '.time_elapsed($Track[count($Track) - 1]['Duration']).'<br/>';
    529         $Output .= '</td><td>';
    530         $Map->Key = 'AIzaSyDwKYuEdkXAl9Y2RyDLf5m03n-ItHaqdKs';
    531         $Output .= $Map->Show();
    532         $Output .= '</td></tr></table>';
    533         $_SESSION['Track'] = $Track;
    534         $_SESSION['SeatCount'] = $_GET['seats'];
    535       } else
    536       if ($_GET['step'] == '3') {
    537         $this->Database->insert('Ride', array(
    538           'Driver' => $this->System->User->User['Id'],
    539           'SeatCount' => $_POST['seats'],
    540           'Car' => $_POST['car'],
    541           'Details' => $_POST['desc'],
    542         ));
    543         $RideId = $this->Database->insert_id;
    544         foreach ($_SESSION['Track'] as $Index => $TrackItem)
    545         {
    546           $this->Database->insert('RideStop', array(
    547             'Ride' => $RideId,
    548             'Place' => $TrackItem['Destination'],
    549             'Time' => TimeToMysqlDateTime($TrackItem['Time']),
    550             'Price' => $TrackItem['Price'],
    551             'Sequence' => $Index,
    552             'PassengerCount' => 0,
    553           ));
    554         }
    555         $Output = 'Nová jízda přidána.';
    556       }
    557     }
    558     return $Output;
    559   }
    560 }
    561 
  • trunk/Modules/User/ModuleUser.php

    r7 r8  
    11<?php
    22
    3 include_once(dirname(__FILE__).'/UserModel.php');
    4 include_once(dirname(__FILE__).'/UserList.php');
    5 include_once(dirname(__FILE__).'/UserPage.php');
    6 
    7 class ModuleUser extends AppModule
     3include_once(dirname(__FILE__).'/User.php');
     4include_once(dirname(__FILE__).'/PageUserList.php');
     5include_once(dirname(__FILE__).'/PageUser.php');
     6
     7class ModuleUser extends Module
    88{
    99  var $UserPanel;
     
    2121  }
    2222
    23   function DoInstall()
     23  function DoInstall(): void
    2424  {
    2525    $this->Database->query('CREATE TABLE IF NOT EXISTS `User` ('.
     
    107107  }
    108108
    109   function DoUninstall()
     109  function DoUninstall(): void
    110110  {
    111111    $this->Database->query('DROP TABLE `PermissionUserAssignment`');
     
    117117  }
    118118
    119   function DoUpgrade()
     119  function DoUpgrade(): string
    120120  {
    121121    /*
     
    126126    }
    127127    */
    128   }
    129 
    130   function DoStart()
     128    return '';
     129  }
     130
     131  function DoStart(): void
    131132  {
    132133    $this->System->User = new User($this->System);
     
    281282  }
    282283
    283   function DoStop()
     284  function DoStop(): void
    284285  {
    285286  }
  • trunk/Modules/User/PageUser.php

    r7 r8  
    33class PageUser extends Page
    44{
    5   var $FullTitle = 'Uživatel';
    6   var $ShortTitle = 'Uživatel';
    7   var $ParentClass = 'PagePortal';
     5  function __construct(System $System)
     6  {
     7    parent::__construct($System);
     8    $this->Title = 'Uživatel';
     9    $this->Description = 'Uživatel';
     10    $this->ParentClass = 'PagePortal';
     11  }
    812
    913  function Panel($Title, $Content, $Menu = array())
     
    8892  }
    8993
    90   function Show()
     94  function Show(): string
    9195  {
    9296    $Output = '';
  • trunk/Modules/User/PageUserList.php

    r7 r8  
    33class PageUserList extends Page
    44{
    5   var $FullTitle = 'Seznam registrovaných uživatelů';
    6   var $ShortTitle = 'Seznam uživatelů';
    7   var $ParentClass = 'PagePortal';
     5  function __construct(System $System)
     6  {
     7    parent::__construct($System);
     8    $this->Title = 'Seznam uživatelů';
     9    $this->Description = 'Seznam registrovaných uživatelů';
     10    $this->ParentClass = 'PagePortal';
     11  }
    812
    9   function Show()
     13  function Show(): string
    1014  {
    1115    if (!$this->System->User->CheckPermission('User', 'ShowList'))
  • trunk/Modules/User/User.php

    r7 r8  
    11<?php
     2
     3include_once(dirname(__FILE__).'/PasswordHash.php');
    24
    35define('LOGIN_USED', 'Přihlašovací jméno již použito.');
     
    2830define('DEFAULT_GROUP', 1);
    2931
    30 class PasswordHash
    31 {
    32   function Hash($Password, $Salt)
    33   {
    34     return sha1(sha1($Password).$Salt);
    35   }
    36 
    37   function Verify($Password, $Salt, $StoredHash)
    38   {
    39     return $this->Hash($Password, $Salt) == $StoredHash;
    40   }
    41 
    42   function GetSalt()
    43   {
    44     mt_srand(microtime(true) * 100000 + memory_get_usage(true));
    45     return sha1(uniqid(mt_rand(), true));
    46   }
    47 }
    48 
    4932// TODO: Make User class more general without dependencies to System, Mail, Log
    5033
  • trunk/Packages/Common/Base.php

    r1 r8  
    11<?php
    2 
    3 class System
    4 {
    5   /* @var Database */
    6   var $Database;
    7 
    8   function __construct()
    9   {
    10     $this->Database = new Database();
    11   }
    12 }
    132
    143class Base
    154{
    16   /** @var Application */
    17   var $System;
    18   /* @var Database */
    19   var $Database;
     5  public System $System;
     6  public Database $Database;
    207
    21   function __construct(Application $System)
     8  function __construct(System $System)
    229  {
    2310    $this->System = &$System;
    2411    $this->Database = &$System->Database;
    2512  }
     13
     14  static function GetClassName()
     15  {
     16    return get_called_class();
     17  }
    2618}
    27 
    28 class Model extends Base
    29 {
    30 
    31 }
    32 
    33 class View extends Base
    34 {
    35 
    36 }
    37 
    38 class Controller extends Base
    39 {
    40 
    41 }
  • trunk/Packages/Common/Common.php

    r7 r8  
    1111include_once(dirname(__FILE__).'/Error.php');
    1212include_once(dirname(__FILE__).'/Base.php');
    13 include_once(dirname(__FILE__).'/Application.php');
    14 include_once(dirname(__FILE__).'/AppModule.php');
     13include_once(dirname(__FILE__).'/View.php');
     14include_once(dirname(__FILE__).'/Model.php');
     15include_once(dirname(__FILE__).'/ModelDesc.php');
     16include_once(dirname(__FILE__).'/Controller.php');
     17include_once(dirname(__FILE__).'/System.php');
     18include_once(dirname(__FILE__).'/Module.php');
     19include_once(dirname(__FILE__).'/ModuleManager.php');
     20include_once(dirname(__FILE__).'/ModelDef.php');
    1521include_once(dirname(__FILE__).'/Config.php');
    1622include_once(dirname(__FILE__).'/Page.php');
    1723include_once(dirname(__FILE__).'/Locale.php');
    1824include_once(dirname(__FILE__).'/Update.php');
    19 include_once(dirname(__FILE__).'/Setup.php');
    2025include_once(dirname(__FILE__).'/Table.php');
    21 include_once(dirname(__FILE__).'/Form/Form.php');
     26include_once(dirname(__FILE__).'/Process.php');
     27include_once(dirname(__FILE__).'/Generics.php');
     28include_once(dirname(__FILE__).'/BigInt.php');
     29include_once(dirname(__FILE__).'/Int128.php');
     30include_once(dirname(__FILE__).'/Pdf.php');
     31include_once(dirname(__FILE__).'/Paging.php');
     32include_once(dirname(__FILE__).'/Modules/Setup.php');
     33include_once(dirname(__FILE__).'/Modules/ModuleManager.php');
    2234
    2335class PackageCommon
    2436{
    25   var $Name;
    26   var $Version;
    27   var $ReleaseDate;
    28   var $License;
    29   var $Creator;
    30   var $Homepage;
     37  public string $Name;
     38  public string $Version;
     39  public int $ReleaseDate;
     40  public string $License;
     41  public string $Creator;
     42  public string $Homepage;
    3143
    3244  function __construct()
     
    3446    $this->Name = 'Common';
    3547    $this->Version = '1.2';
    36     $this->ReleaseDate = strtotime('2016-01-22');
     48    $this->ReleaseDate = strtotime('2023-05-31');
    3749    $this->Creator = 'Chronos';
    38     $this->License = 'GNU/GPL';
    39     $this->Homepage = 'http://svn.zdechov.net/svn/PHPlib/Common/';
     50    $this->License = 'GNU/GPLv3';
     51    $this->Homepage = 'https://svn.zdechov.net/PHPlib/Common/';
    4052  }
    4153}
    42 
    43 class Paging
    44 {
    45   var $TotalCount;
    46   var $ItemPerPage;
    47   var $Around;
    48   var $SQLLimit;
    49   var $Page;
    50 
    51   function __construct(Application $System)
    52   {
    53     $this->ItemPerPage = $System->Config['Web']['ItemsPerPage'];
    54     $this->Around = $System->Config['Web']['VisiblePagingItems'];
    55   }
    56 
    57   function Show()
    58   {
    59     $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
    60 
    61     $Result = '';
    62     if (array_key_exists('all', $QueryItems))
    63     {
    64       $PageCount = 1;
    65       $ItemPerPage = $this->TotalCount;
    66     } else
    67     {
    68       $ItemPerPage = $this->ItemPerPage;
    69       $Around = round($this->Around / 2);
    70       $PageCount = floor($this->TotalCount / $ItemPerPage) + 1;
    71     }
    72 
    73     if (!array_key_exists('Page', $_SESSION)) $_SESSION['Page'] = 0;
    74     if (array_key_exists('page', $_GET)) $_SESSION['Page'] = $_GET['page'] * 1;
    75     if ($_SESSION['Page'] < 0) $_SESSION['Page'] = 0;
    76     if ($_SESSION['Page'] >= $PageCount) $_SESSION['Page'] = $PageCount - 1;
    77     $CurrentPage = $_SESSION['Page'];
    78 
    79     $Result .= 'Počet položek: <strong>'.$this->TotalCount.'</strong> &nbsp; Stránky: ';
    80 
    81     $Result = '';
    82     if ($PageCount > 1)
    83     {
    84       if ($CurrentPage > 0)
    85       {
    86         $QueryItems['page'] = 0;
    87         $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;&lt;</a> ';
    88         $QueryItems['page'] = ($CurrentPage - 1);
    89         $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;</a> ';
    90       }
    91       $PagesMax = $PageCount - 1;
    92       $PagesMin = 0;
    93       if ($PagesMax > ($CurrentPage + $Around)) $PagesMax = $CurrentPage + $Around;
    94       if ($PagesMin < ($CurrentPage - $Around))
    95       {
    96         $Result.= ' ... ';
    97         $PagesMin = $CurrentPage - $Around;
    98       }
    99       for ($i = $PagesMin; $i <= $PagesMax; $i++)
    100       {
    101         if ($i == $CurrentPage) $Result.= '<strong>'.($i + 1).'</strong> ';
    102         else {
    103          $QueryItems['page'] = $i;
    104          $Result .= '<a href="?'.SetQueryStringArray($QueryItems).'">'.($i + 1).'</a> ';
    105         }
    106       }
    107       if ($PagesMax < ($PageCount - 1)) $Result .= ' ... ';
    108       if ($CurrentPage < ($PageCount - 1))
    109       {
    110         $QueryItems['page'] = ($CurrentPage + 1);
    111         $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;</a> ';
    112         $QueryItems['page'] = ($PageCount - 1);
    113         $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;&gt;</a>';
    114       }
    115     }
    116     $QueryItems['all'] = '1';
    117     if ($PageCount > 1) $Result.= ' <a href="?'.SetQueryStringArray($QueryItems).'">Vše</a>';
    118 
    119     $Result = '<div style="text-align: center">'.$Result.'</div>';
    120     $this->SQLLimit = ' LIMIT '.$CurrentPage * $ItemPerPage.', '.$ItemPerPage;
    121     $this->Page = $CurrentPage;
    122     return $Result;
    123   }
    124 }
  • trunk/Packages/Common/Config.php

    r7 r8  
    33class Config
    44{
    5   var $Data;
     5  public array $Data;
    66
    77  function __construct()
     
    1010  }
    1111
    12   function ReadValue($Name)
     12  function ReadValue(string $Name)
    1313  {
    1414    if (!is_array($Name)) $Name = explode('/', $Name);
     
    2222  }
    2323
    24   function WriteValue($Name, $Value)
     24  function WriteValue(string $Name, $Value)
    2525  {
    2626    if (!is_array($Name)) $Name = explode('/', $Name);
     
    3434  }
    3535
    36   function LoadFromFile($FileName)
     36  function LoadFromFile(string $FileName): void
    3737  {
    3838    $ConfigData = array();
     
    4040    foreach ($this->Data as $Index => $Item)
    4141    {
    42       if (array_key_exits($Index, $ConfigData))
     42      if (array_key_exists($Index, $ConfigData))
    4343        $this->Data[$Index] = $ConfigData[$Index];
    4444    }
    4545  }
    4646
    47   function SaveToFile($FileName)
     47  function SaveToFile(string $FileName): void
    4848  {
    4949    file_put_contents($FileName, "<?php \n\n\$ConfigData = ".var_export($this->Data, true).";\n");
    5050  }
    5151
    52   function GetAsArray()
     52  function GetAsArray(): array
    5353  {
    5454    return $this->Data;
  • trunk/Packages/Common/Database.php

    r7 r8  
    22
    33// Extended database class
    4 // Date: 2016-01-11
     4// Date: 2020-11-10
     5
     6function microtime_float()
     7{
     8  list($usec, $sec) = explode(" ", microtime());
     9  return (float)$usec + (float)$sec;
     10}
    511
    612class DatabaseResult
    713{
    8   var $PDOStatement;
    9   var $num_rows = 0;
     14  public PDOStatement $PDOStatement;
     15  public int $num_rows = 0;
    1016
    1117  function fetch_assoc()
     
    2733class Database
    2834{
    29   var $Prefix;
    30   var $Functions;
    31   var $Type;
    32   var $PDO;
    33   var $Error;
    34   var $insert_id;
    35   var $LastQuery;
    36   var $ShowSQLError;
    37   var $ShowSQLQuery;
    38   var $LogSQLQuery;
    39   var $LogFile;
     35  public string $Prefix;
     36  public array $Functions;
     37  public string $Type;
     38  public PDO $PDO;
     39  public string $Error;
     40  public string $insert_id;
     41  public string $LastQuery;
     42  public bool $ShowSQLError;
     43  public bool $ShowSQLQuery;
     44  public bool $LogSQLQuery;
     45  public string $LogFile;
     46  public string $Database;
    4047
    4148  function __construct()
    4249  {
    4350    $this->Prefix = '';
    44     $this->Functions = array('NOW()', 'CURDATE()', 'CURTIME()', 'UUID()');
     51    $this->Functions = array('NOW(', 'CURDATE(', 'CURTIME(', 'UUID(', 'SHA1(');
    4552    $this->Type = 'mysql';  // mysql, pgsql
    4653    $this->Error = '';
     
    5057    $this->LogSQLQuery = false;
    5158    $this->LogFile = dirname(__FILE__).'/../../Query.log';
    52   }
    53 
    54   function Connect($Host, $User, $Password, $Database)
     59    $this->Database = '';
     60  }
     61
     62  function Connect(string $Host, string $User, string $Password, string $Database): void
    5563  {
    5664    if ($this->Type == 'mysql') $ConnectionString = 'mysql:host='.$Host.';dbname='.$Database;
    5765      else if ($this->Type == 'pgsql') $ConnectionString = 'pgsql:dbname='.$Database.';host='.$Host;
    5866      else $ConnectionString = '';
     67    $this->Database = $Database;
    5968    try {
    6069      $this->PDO = new PDO($ConnectionString, $User, $Password);
    61 
    6270    } catch (Exception $E)
    6371    {
     
    6775  }
    6876
    69   function Disconnect()
     77  function Disconnect(): void
    7078  {
    7179    unset($this->PDO);
    7280  }
    7381
    74   function Connected()
     82  function Connected(): bool
    7583  {
    7684    return isset($this->PDO);
    7785  }
    7886
    79   function select_db($Database)
     87  function select_db(string $Database)
    8088  {
    8189    $this->query('USE `'.$Database.'`');
    8290  }
    8391
    84   function query($Query)
     92  function query($Query): DatabaseResult
    8593  {
    8694    if (!$this->Connected()) throw new Exception(T('Not connected to database'));
    87     if (($this->ShowSQLQuery == true) or ($this->LogSQLQuery == true)) $QueryStartTime = microtime();
     95    if (($this->ShowSQLQuery == true) or ($this->LogSQLQuery == true)) $QueryStartTime = microtime_float();
    8896    $this->LastQuery = $Query;
    8997    if (($this->ShowSQLQuery == true) or ($this->LogSQLQuery == true))
    90       $Duration = ' ; '.round(microtime() - $QueryStartTime, 4). ' s';
    91     if ($this->LogSQLQuery == true)
     98    {
     99      $Time = round(microtime_float() - $QueryStartTime, 4);
     100      $Duration = ' ; '.$Time. ' s';
     101    }
     102    if (($this->LogSQLQuery == true) and ($Time != 0))
    92103      file_put_contents($this->LogFile, $Query.$Duration."\n", FILE_APPEND);
    93104    if ($this->ShowSQLQuery == true)
     
    95106      'padding-bottom: 3px; padding-top: 3px; font-size: 12px; font-family: Arial;">'.$Query.$Duration.'</div>'."\n");
    96107    $Result = new DatabaseResult();
    97     $Result->PDOStatement = $this->PDO->query($Query);
    98     if ($Result->PDOStatement)
    99     {
    100       $Result->num_rows = $Result->PDOStatement->rowCount();
     108    $Statement = $this->PDO->query($Query);
     109    if ($Statement)
     110    {
     111      $Result->PDOStatement = $Statement;
     112      $Result->num_rows = $Statement->rowCount();
    101113      $this->insert_id = $this->PDO->lastInsertId();
    102114    } else
    103115    {
    104       $this->Error = $this->PDO->errorInfo();
    105       $this->Error = $this->Error[2];
     116      $Error = $this->PDO->errorInfo();
     117      $this->Error = $Error[2];
    106118      if (($this->Error != '') and ($this->ShowSQLError == true))
    107119        echo('<div><strong>SQL Error: </strong>'.$this->Error.'<br />'.$Query.'</div>');
     
    111123  }
    112124
    113   function select($Table, $What = '*', $Condition = 1)
     125  function select(string $Table, string $What = '*', string $Condition = '1'): DatabaseResult
    114126  {
    115127    return $this->query('SELECT '.$What.' FROM `'.$this->Prefix.$Table.'` WHERE '.$Condition);
    116128  }
    117129
    118   function delete($Table, $Condition)
     130  function delete(string $Table, string $Condition): void
    119131  {
    120132    $this->query('DELETE FROM `'.$this->Prefix.$Table.'` WHERE '.$Condition);
    121133  }
    122134
    123   function insert($Table, $Data)
     135  function insert(string $Table, array $Data): int
     136  {
     137    $this->query($this->GetInsert($Table, $Data));
     138    $this->insert_id = $this->PDO->lastInsertId();
     139    return $this->insert_id;
     140  }
     141
     142  function IsFunction(string $Text): bool
     143  {
     144    $Pos = strpos($Text, '(');
     145    return ($Pos !== false) && in_array(substr($Text, 0, $Pos + 1), $this->Functions);
     146  }
     147
     148  function GetInsert(string $Table, array $Data): string
    124149  {
    125150    $Name = '';
     
    128153    {
    129154      $Name .= ',`'.$Key.'`';
    130       if (!in_array($Value, $this->Functions))
     155      if (is_null($Value)) $Value = 'NULL';
     156      else if (!$this->IsFunction($Value))
    131157      {
    132         if (is_null($Value)) $Value = 'NULL';
    133         else $Value = $this->PDO->quote($Value);
     158        $Value = $this->PDO->quote($Value);
    134159      }
    135160      $Values .= ','.$Value;
     
    137162    $Name = substr($Name, 1);
    138163    $Values = substr($Values, 1);
    139     $this->query('INSERT INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES('.$Values.')');
    140     $this->insert_id = $this->PDO->lastInsertId();
    141   }
    142 
    143   function update($Table, $Condition, $Data)
     164    return 'INSERT INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES('.$Values.')';
     165  }
     166
     167  function update(string $Table, string $Condition, array $Data): void
     168  {
     169    $this->query($this->GetUpdate($Table, $Condition, $Data));
     170  }
     171
     172  function GetUpdate(string $Table, string $Condition, array $Data): string
    144173  {
    145174    $Values = '';
    146175    foreach ($Data as $Key => $Value)
    147176    {
    148       if (!in_array($Value, $this->Functions))
     177      if (is_null($Value)) $Value = 'NULL';
     178      else if (!$this->IsFunction($Value))
    149179      {
    150         if (is_null($Value)) $Value = 'NULL';
    151         else $Value = $this->PDO->quote($Value);
     180        $Value = $this->PDO->quote($Value);
    152181      }
    153182      $Values .= ', `'.$Key.'`='.$Value;
    154183    }
    155184    $Values = substr($Values, 2);
    156     $this->query('UPDATE `'.$this->Prefix.$Table.'` SET '.$Values.' WHERE ('.$Condition.')');
    157   }
    158 
    159   function replace($Table, $Data)
     185    return 'UPDATE `'.$this->Prefix.$Table.'` SET '.$Values.' WHERE ('.$Condition.')';
     186  }
     187
     188  function replace(string $Table, array $Data): void
    160189  {
    161190    $Name = '';
     
    163192    foreach ($Data as $Key => $Value)
    164193    {
    165       if (!in_array($Value, $this->Functions))
     194      if (is_null($Value)) $Value = 'NULL';
     195      else if (!$this->IsFunction($Value))
    166196      {
    167         if (is_null($Value)) $Value = 'NULL';
    168         else $Value = $this->PDO->quote($Value);
     197        $Value = $this->PDO->quote($Value);
    169198      }
    170199      $Name .= ',`'.$Key.'`';
     
    173202    $Name = substr($Name, 1);
    174203    $Values = substr($Values, 1);
    175     //echo('REPLACE INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES ('.$Values.')<br />');
    176204    $this->query('REPLACE INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES('.$Values.')');
    177     //echo($this->error().'<br>');
    178   }
    179 
    180   function charset($Charset)
     205  }
     206
     207  function charset(string $Charset): void
    181208  {
    182209    $this->query('SET NAMES "'.$Charset.'"');
    183210  }
    184211
    185   function real_escape_string($Text)
     212  function real_escape_string(string $Text): string
    186213  {
    187214    return addslashes($Text);
    188215  }
    189216
    190   function quote($Text)
     217  function quote(string $Text): string
    191218  {
    192219    return $this->PDO->quote($Text);
    193220  }
    194221
    195   public function __sleep()
     222  public function __sleep(): array
    196223  {
    197224    return array('LastQuery');
    198225  }
    199226
    200   public function __wakeup()
    201   {
     227  public function __wakeup(): void
     228  {
     229  }
     230
     231  public function Transaction(array $Queries): void
     232  {
     233    $this->PDO->beginTransaction();
     234    foreach ($Queries as $Query)
     235    {
     236      $Statement = $this->PDO->prepare($Query);
     237      $Statement->execute();
     238    }
     239    $this->PDO->commit();
     240  }
     241
     242  public function TableExists(string $Name): bool
     243  {
     244    $DbResult = $this->query('SELECT * FROM information_schema.tables  WHERE table_schema = "'.$this->Database.
     245    '" AND table_name = "'.$Name.'" LIMIT 1');
     246    return $DbResult->num_rows != 0;
    202247  }
    203248}
  • trunk/Packages/Common/Error.php

    r7 r8  
    33class ErrorHandler
    44{
    5   var $Encoding;
    6   var $ShowError;
    7   var $UserErrors;
    8   var $OnError;
     5  public string $Encoding;
     6  public bool $ShowError;
     7  public int $UserErrors;
     8  public $OnError;
    99
    1010  function __construct()
     
    1616  }
    1717
    18   function Start()
     18  function Start(): void
    1919  {
    2020    set_error_handler(array($this, 'ErrorHandler'));
     
    2222  }
    2323
    24   function Stop()
     24  function Stop(): void
    2525  {
    2626    restore_error_handler();
     
    2828  }
    2929
    30   function ErrorHandler($Number, $Message, $FileName, $LineNumber, $Variables)
     30  function ErrorHandler(int $Number, string $Message, string $FileName, int $LineNumber, array $Variables = array()): bool
    3131  {
    3232    $ErrorType = array
     
    6363  }
    6464
    65   function ExceptionHandler(Throwable $Exception)
     65  function ExceptionHandler(Throwable $Exception): void
    6666  {
    6767    $Backtrace = $Exception->getTrace();
     
    7575  }
    7676
    77   function ShowDefaultError($Message)
     77  function ShowDefaultError(string $Message): void
    7878  {
    7979    $Output = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>'."\n".
     
    8888  }
    8989
    90   function Report($Backtrace)
     90  function Report(array $Backtrace): void
    9191  {
    9292    $Date = date('Y-m-d H:i:s');
  • trunk/Packages/Common/Image.php

    r7 r8  
    99class Font
    1010{
    11   var $Size;
    12   var $FileName;
    13   var $Color;
     11  public int $Size;
     12  public string $FileName;
     13  public int $Color;
    1414
    1515  function __construct()
     
    2323class Pen
    2424{
    25   var $Color;
    26   var $X;
    27   var $Y;
     25  public int $Color;
     26  public int $X;
     27  public int $Y;
    2828
    2929  function __construct()
     
    3838class Brush
    3939{
    40   var $Color;
     40  public int $Color;
    4141
    4242  function __construct()
     
    4949class Image
    5050{
    51   var $Image;
    52   var $Type;
    53   var $Font;
    54   var $Pen;
     51  public $Image;
     52  public int $Type;
     53  public Font $Font;
     54  public Pen $Pen;
     55  public Brush $Brush;
    5556
    5657  function __construct()
     
    6364  }
    6465
    65   function SaveToFile($FileName)
     66  function SaveToFile(string $FileName): void
    6667  {
    6768    if ($this->Type == IMAGETYPE_JPEG)
     
    7980  }
    8081
    81   function LoadFromFile($FileName)
     82  function LoadFromFile(string $FileName): void
    8283  {
    8384    $ImageInfo = getimagesize($FileName);
     
    8990    if ($this->Type == IMAGETYPE_GIF)
    9091    {
    91       $this->Image = imagecreatefromgif($FileName);
     92      $this->Image = imagecreatefromgif ($FileName);
    9293    } else
    9394    if ( $this->Type == IMAGETYPE_PNG)
     
    9798  }
    9899
    99   function Output()
    100   {
    101     $this->SaveToFile(NULL);
    102   }
    103 
    104   function SetSize($Width, $Height)
     100  function SetSize(int $Width, int $Height): void
    105101  {
    106102    $NewImage = imagecreatetruecolor($Width, $Height);
     
    110106  }
    111107
    112   function GetWidth()
     108  function GetWidth(): int
    113109  {
    114110    return imagesx($this->Image);
    115111  }
    116112
    117   function GetHeight()
     113  function GetHeight(): int
    118114  {
    119115    return imagesy($this->Image);
    120116  }
    121117
    122   function TextOut($X, $Y, $Text)
     118  function TextOut(int $X, int $Y, string $Text): void
    123119  {
    124120    imagettftext($this->Image, $this->Font->Size, 0, $X, $Y, $this->ConvertColor($this->Font->Color), $this->Font->FileName, $Text);
    125121  }
    126122
    127   function ConvertColor($Color)
     123  function ConvertColor(int $Color): int
    128124  {
    129125    return imagecolorallocate($this->Image, ($Color >> 16) & 0xff, ($Color >> 8) & 0xff, $Color & 0xff);
    130126  }
    131127
    132   function FillRect($X1, $Y1, $X2, $Y2)
     128  function FillRect(int $X1, int $Y1, int $X2, int $Y2): void
    133129  {
    134130    imagefilledrectangle($this->Image, $X1, $Y1, $X2, $Y2, $this->ConvertColor($this->Brush->Color));
    135131  }
    136132
    137   function Line($X1, $Y1, $X2, $Y2)
     133  function Line(int $X1, int $Y1, int $X2, int $Y2): void
    138134  {
    139135    imageline($this->Image, $X1, $Y1, $X2, $Y2, $this->ConvertColor($this->Pen->Color));
  • trunk/Packages/Common/Locale.php

    r7 r8  
    33class LocaleText
    44{
    5   var $Data;
    6   var $Code;
    7   var $Title;
     5  public array $Data;
     6  public string $Code;
     7  public string $Title;
    88
    99  function __construct()
     
    1414  }
    1515
    16   function Load()
    17   {
    18   }
    19 
    20   function Translate($Text, $Group = '')
     16  function Load(): void
     17  {
     18  }
     19
     20  function Translate(string $Text, string $Group = ''): string
    2121  {
    2222    if (array_key_exists($Text, $this->Data[$Group]) and ($this->Data[$Group][$Text] != ''))
     
    2525  }
    2626
    27   function TranslateReverse($Text, $Group = '')
     27  function TranslateReverse(string $Text, string $Group = ''): string
    2828  {
    2929    $Key = array_search($Text, $this->Data[$Group]);
     
    3535class LocaleFile extends Model
    3636{
    37   var $Texts;
    38   var $Dir;
     37  public LocaleText $Texts;
     38  public string $Dir;
    3939
    4040  function __construct(System $System)
     
    4444  }
    4545
    46   function Load($Language)
     46  function Load(string $Language): void
    4747  {
    4848    $FileName = $this->Dir.'/'.$Language.'.php';
     
    5555  }
    5656
    57   function AnalyzeCode($Path)
     57  function AnalyzeCode(string $Path): void
    5858  {
    5959    // Search for php files
     
    7575            $Previous = strtolower(substr($Content, strpos($Content, 'T(') - 1, 1));
    7676            $Content = substr($Content, strpos($Content, 'T(') + 2);
    77             $Ord = ord($Previous);
    78             //echo($Ord.',');
     77            $Ord = ord($Previous);           
    7978            if (!(($Ord >= ord('a')) and ($Ord <= ord('z'))))
    8079            {
     
    9897  }
    9998
    100   function SaveToFile($FileName)
     99  function SaveToFile(string $FileName): void
    101100  {
    102101    $Content = '<?php'."\n".
     
    119118  }
    120119
    121   function LoadFromDatabase($Database, $LangCode)
     120  function LoadFromDatabase(Database $Database, string $LangCode): void
    122121  {
    123122    $DbResult = $Database->select('Language', '*', 'Code='.$Database->quote($LangCode));
     
    132131  }
    133132
    134   function SaveToDatabase(Database $Database, $LangCode)
    135   {
    136     $DbResult = $Database->select('Language', '*', 'Code='.$Database->quote($LangCode));
     133  function SaveToDatabase(string $LangCode): void
     134  {
     135    $DbResult = $this->Database->select('Language', '*', 'Code='.$this->Database->quote($LangCode));
    137136    if ($DbResult->num_rows > 0)
    138137    {
    139138      $Language = $DbResult->fetch_assoc();
    140       $Database->delete('Locale', '`Language`='.$Language['Id']);
     139      $this->Database->delete('Locale', '`Language`='.$Language['Id']);
    141140      foreach ($this->Texts->Data as $Index => $Item)
    142         $Database->query('INSERT INTO `Locale` (`Language`,`Original`,`Translated`) '.
    143         'VALUES('.$Language['Id'].','.$Database->quote($Index).','.$Database->quote($Item).')');
    144     }
    145   }
    146 
    147   function UpdateToDatabase(Database $Database, $LangCode)
    148   {
    149     $DbResult = $Database->select('Language', '*', '`Code`='.$Database->quote($LangCode));
     141        $this->Database->query('INSERT INTO `Locale` (`Language`,`Original`,`Translated`) '.
     142        'VALUES('.$Language['Id'].','.$this->Database->quote($Index).','.$this->Database->quote($Item).')');
     143    }
     144  }
     145
     146  function UpdateToDatabase(string $LangCode): void
     147  {
     148    $DbResult = $this->Database->select('Language', '*', '`Code`='.$this->Database->quote($LangCode));
    150149    if ($DbResult->num_rows > 0)
    151150    {
     
    153152      foreach ($this->Texts->Data as $Index => $Item)
    154153      {
    155         $DbResult = $Database->select('Locale', '*', '(`Original` ='.$Database->quote($Index).
     154        $DbResult = $this->Database->select('Locale', '*', '(`Original` ='.$this->Database->quote($Index).
    156155          ') AND (`Language`='.($Language['Id']).')');
    157156        if ($DbResult->num_rows > 0)
    158         $Database->update('Locale', '(`Language`='.($Language['Id']).') AND '.
    159           '(`Original` ='.$Database->quote($Index).')', array('Translated' => $Item));
    160         else $Database->insert('Locale', array('Language' => $Language['Id'],
     157        $this->Database->update('Locale', '(`Language`='.($Language['Id']).') AND '.
     158          '(`Original` ='.$this->Database->quote($Index).')', array('Translated' => $Item));
     159        else $this->Database->insert('Locale', array('Language' => $Language['Id'],
    161160         'Original' => $Index, 'Translated' => $Item));
    162161      }
     
    167166class LocaleManager extends Model
    168167{
    169   var $CurrentLocale;
    170   var $Codes;
    171   var $Dir;
    172   var $LangCode;
    173   var $DefaultLangCode;
    174   var $Available;
     168  public LocaleFile $CurrentLocale;
     169  public array $Codes;
     170  public string $Dir;
     171  public string $LangCode;
     172  public string $DefaultLangCode;
     173  public array $Available;
    175174
    176175  function __construct(System $System)
     
    182181    $this->DefaultLangCode = 'en';
    183182    $this->Available = array();
    184   }
    185 
    186   function LoadAvailable()
     183    $this->Dir = '';
     184  }
     185
     186  function LoadAvailable(): void
    187187  {
    188188    $this->Available = array();
     
    201201  }
    202202
    203   function UpdateAll($Directory)
     203  function UpdateAll(string $Directory): void
    204204  {
    205205    $Locale = new LocaleFile($this->System);
     
    222222          if (!array_key_exists($Index, $Locale->Texts->Data))
    223223            unset($FileLocale->Texts->Data[$Index]);
    224         $FileLocale->UpdateToDatabase($this->System->Database, $FileLocale->Texts->Code);
     224        $FileLocale->UpdateToDatabase($FileLocale->Texts->Code);
    225225        $FileName = $this->Dir.'/'.$FileLocale->Texts->Code.'.php';
    226226        $FileLocale->SaveToFile($FileName);
     
    230230  }
    231231
    232   function LoadLocale($Code)
     232  function LoadLocale(string $Code): void
    233233  {
    234234    if (array_key_exists($Code, $this->Available))
     
    241241
    242242// Short named global translation function
    243 function T($Text, $Group = '')
     243function T(string $Text, string $Group = ''): string
    244244{
    245245  global $GlobalLocaleManager;
  • trunk/Packages/Common/Mail.php

    r7 r8  
    99class Mail
    1010{
    11   var $Priorities;
    12   var $Subject;
    13   var $From;
    14   var $Recipients;
    15   var $Bodies;
    16   var $Attachments;
    17   var $AgentIdent;
    18   var $Organization;
    19   var $ReplyTo;
    20   var $Headers;
     11  public string $Subject;
     12  public string $From;
     13  public array $Recipients;
     14  public array $Bodies;
     15  public array $Attachments;
     16  public string $AgentIdent;
     17  public string $Organization;
     18  public string $ReplyTo;
     19  public array $Headers;
     20  private array $Priorities;
     21  private string $Boundary;
     22  public bool $TestMode;
     23  public string $SenderAddress;
     24  public string $SenderName;
    2125
    2226  function __construct()
     
    2529    $this->Boundary = md5(date('r', time()));
    2630    $this->AgentIdent = 'PHP/Mail';
     31    $this->TestMode = false;
    2732    $this->Clear();
    2833  }
    2934
    30   function Clear()
     35  function Clear(): void
    3136  {
    3237    $this->Bodies = array();
     
    4146  }
    4247
    43   function AddToCombined($Address)
     48  function AddToCombined(string $Address): void
    4449  {
    4550    $this->Recipients[] = array('Address' => $Address, 'Type' => 'SendCombined');
    4651  }
    4752
    48   function AddTo($Address, $Name)
     53  function AddTo(string $Address, string $Name): void
    4954  {
    5055    $this->Recipients[] = array('Address' => $Address, 'Name' => $Name, 'Type' => 'Send');
    5156  }
    5257
    53   function AddCc($Address, $Name)
     58  function AddCc(string $Address, string $Name): void
    5459  {
    5560    $this->Recipients[] = array('Address' => $Address, 'Name' => $Name, 'Type' => 'Copy');
    5661  }
    5762
    58   function AddBcc($Address, $Name)
     63  function AddBcc(string $Address, string $Name): void
    5964  {
    6065    $this->Recipients[] = array('Address' => $Address, 'Name' => $Name, 'Type' => 'HiddenCopy');
    6166  }
    6267
    63   function AddBody($Content, $MimeType = 'text/plain', $Charset = 'utf-8')
     68  function AddBody(string $Content, string $MimeType = 'text/plain', string $Charset = 'utf-8'): void
    6469  {
    6570    $this->Bodies[] = array('Content' => $Content, 'Type' => strtolower($MimeType),
     
    6772  }
    6873
    69   function Organization($org)
    70   {
    71     if (trim($org != '')) $this->xheaders['Organization'] = $org;
    72   }
    73 
    74   function Priority($Priority)
     74  function Organization(string $org): void
     75  {
     76    if (trim($org != '')) $this->Headers['Organization'] = $org;
     77  }
     78
     79  function Priority(int $Priority): bool
    7580  {
    7681    if (!intval($Priority)) return false;
    7782
    78     if (!isset($this->priorities[$Priority - 1])) return false;
    79 
    80     $this->xheaders['X-Priority'] = $this->priorities[$Priority - 1];
     83    if (!isset($this->Priorities[$Priority - 1])) return false;
     84
     85    $this->Headers['X-Priority'] = $this->Priorities[$Priority - 1];
    8186    return true;
    8287  }
    8388
    84   function AttachFile($FileName, $FileType, $Disposition = DISPOSITION_ATTACHMENT)
     89  function AttachFile($FileName, $FileType, $Disposition = DISPOSITION_ATTACHMENT): void
    8590  {
    8691    $this->Attachments[] = array('FileName' => $FileName, 'FileType' => $FileType,
     
    8893  }
    8994
    90   function AttachData($FileName, $FileType, $Data, $Disposition = DISPOSITION_ATTACHMENT)
     95  function AttachData($FileName, $FileType, $Data, $Disposition = DISPOSITION_ATTACHMENT): void
    9196  {
    9297    $this->Attachments[] = array('FileName' => $FileName, 'FileType' => $FileType,
     
    9499  }
    95100
    96   function Send()
     101  function Send(): bool
    97102  {
    98103    if (count($this->Bodies) == 0) throw new Exception(T('Mail message need at least one text body'));
     
    132137    if ($this->AgentIdent != '') $this->Headers['X-Mailer'] = $this->AgentIdent;
    133138    if ($this->ReplyTo != '') $this->Headers['Reply-To'] = $this->ReplyTo;
    134     if ($this->From != '') $this->Headers['From'] = $this->From;
     139    if ($this->From != '')
     140    {
     141      $IndexStart = strpos($this->From, '<');
     142      if ($IndexStart !== false)
     143      {
     144        $this->Headers['From'] = '=?utf-8?Q?'.quoted_printable_encode(trim(substr($this->From, 0, $IndexStart))).'?= '.substr($this->From, $IndexStart);
     145      } else
     146      {
     147        $this->Headers['From'] = $this->From;
     148      }
     149    }
    135150
    136151    $Headers = '';
     
    144159    if ($this->Subject == '') throw new Exception(T('Mail message missing Subject'));
    145160
    146 
    147     $res = mail($To, $this->Subject, $Body, $Headers);
     161    if ($this->TestMode)
     162    {
     163      echo('to: '.$To.', subject: '.$this->Subject.', body: '.$Body.', headers: '.$Headers);
     164      $res = true;
     165    } else
     166    {
     167      $res = mail($To, $this->Subject, $Body, $Headers);
     168    }
    148169    return $res;
    149170  }
    150171
    151   function ValidEmail($Address)
    152   {
    153     if (ereg(".*<(.+)>", $Address, $regs)) $Address = $regs[1];
    154     if (ereg("^[^@  ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|net|com|gov|mil|org|edu|int)\$", $Address))
     172  function ValidEmail(string $Address): bool
     173  {
     174    if (preg_match(".*<(.+)>", $Address, $regs)) $Address = $regs[1];
     175    if (preg_match("^[^@  ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|net|com|gov|mil|org|edu|int)\$", $Address))
    155176      return true;
    156177      else return false;
    157178  }
    158179
    159   function CheckAdresses($Addresses)
     180  function CheckAdresses(array $Addresses): void
    160181  {
    161182    foreach ($Addresses as $Address)
    162183    {
    163184      if (!$this->ValidEmail($Address))
    164   throw new Exception(sprintf(T('Mail message invalid address %s'), $Address));
    165     }
    166   }
    167 
    168   private function ContentEncoding($Charset)
     185      {
     186        throw new Exception(sprintf(T('Mail message invalid address %s'), $Address));
     187      }
     188    }
     189  }
     190
     191  private function ContentEncoding($Charset): string
    169192  {
    170193    if ($Charset != CHARSET_ASCII) return '8bit';
     
    172195  }
    173196
    174   private function BuildAttachment($Body)
     197  private function BuildAttachment($Body): string
    175198  {
    176199    if (count($this->Attachments) > 0)
     
    206229  }
    207230
    208   private function BuildBody()
     231  private function BuildBody(): string
    209232  {
    210233    $Result = '';
     
    219242      $this->Headers['Content-Transfer-Encoding'] = $this->ContentEncoding($this->Bodies[0]['Charset']);
    220243    }
    221 
    222244
    223245    foreach ($this->Bodies as $Body)
  • trunk/Packages/Common/NetworkAddress.php

    r7 r8  
    11<?php
     2
     3define('IPV4_BIT_WIDTH', 32);
    24
    35class NetworkAddressIPv4
    46{
    5   var $Address;
    6   var $Prefix;
     7  public int $Address;
     8  public int $Prefix;
    79
    810  function __construct()
     
    1214  }
    1315
    14   function GetNetMask()
     16  function GetNetMask(): int
    1517  {
    16     return 0xffffffff ^ ((1 << (32 - $this->Prefix)) - 1);
     18    return ((1 << IPV4_BIT_WIDTH) - 1) ^ ((1 << (IPV4_BIT_WIDTH - $this->Prefix)) - 1);
    1719  }
    1820
    19   function AddressToString()
     21  function AddressToString(): string
    2022  {
    2123    return implode('.', array(($this->Address >> 24) & 255, ($this->Address >> 16) & 255, ($this->Address >> 8) & 255, ($this->Address & 255)));
    2224  }
    2325
    24   function AddressFromString($Value)
     26  function AddressFromString(string $Value): void
    2527  {
    2628    $Parts = explode('.', $Value);
     
    2830  }
    2931
    30   function GetRange()
     32  function GetRange(): array
    3133  {
    3234    $From = new NetworkAddressIPv4();
    3335    $From->Address = $this->Address;
    34     $From->Prefix = 32;
     36    $From->Prefix = IPV4_BIT_WIDTH;
    3537    $HostMask = 0xffffffff ^ $this->GetNetMask();
    3638    $To = new NetworkAddressIPv4();
    3739    $To->Address = $From->Address + $HostMask;
    38     $To->Prefix = 32;
     40    $To->Prefix = IPV4_BIT_WIDTH;
    3941    return array('From' => $From, 'To' => $To);
    4042  }
    4143
    42   function ChangePrefix($NewPrefix)
     44  function ChangePrefix(int $NewPrefix): void
    4345  {
    4446    $this->Prefix = $NewPrefix;
    45     if ($this->Prefix > 32) $this->Prefix = 32;
     47    if ($this->Prefix > IPV4_BIT_WIDTH) $this->Prefix = IPV4_BIT_WIDTH;
    4648    if ($this->Prefix < 0) $this->Prefix = 0;
    4749    $this->Address = $this->Address & $this->GetNetMask();
    4850  }
    4951
    50   function Contain($Address)
     52  function Contain(NetworkAddressIPv4 $Address): bool
    5153  {
    5254    $UpperNetmask = $this->GetNetMask();
    5355    if (($this->Prefix < $Address->Prefix) and (($Address->Address & $UpperNetmask) == ($this->Address & $UpperNetmask))) $Result = true;
    5456      else $Result = false;
    55     //echo($Address->AddressToString().'/'.$Address->Prefix.' in '.$this->AddressToString().'/'.$this->Prefix.' '.$Result."\n");
    5657    return $Result;
    5758  }
    5859}
    5960
     61define('IPV6_BIT_WIDTH', 128);
     62
    6063class NetworkAddressIPv6
    6164{
    62   var $Address;
    63   var $Prefix;
     65  public string $Address;
     66  public int $Prefix;
    6467
    6568  function __construct()
     
    6972  }
    7073
    71   function AddressToString()
     74  function GetNetMask(): string
     75  {
     76    return Int128Xor(Int128Sub(Int128Shl(IntToInt128(1), IntToInt128(IPV6_BIT_WIDTH)), IntToInt128(1)),
     77      Int128Sub(Int128Shl(IntToInt128(1), IntToInt128(IPV6_BIT_WIDTH - $this->Prefix)), IntToInt128(1)));
     78  }
     79
     80  function AddressToString(): string
    7281  {
    7382    return inet_ntop($this->Address);
    7483  }
    7584
    76   function AddressFromString($Value)
     85  function AddressFromString(string $Value)
    7786  {
    7887    $this->Address = inet_pton($Value);
    7988  }
    8089
    81   function GetOctets()
     90  function ChangePrefix(int $NewPrefix): void
     91  {
     92    $this->Prefix = $NewPrefix;
     93    if ($this->Prefix > IPV6_BIT_WIDTH) $this->Prefix = IPV6_BIT_WIDTH;
     94    if ($this->Prefix < 0) $this->Prefix = 0;
     95    $this->Address = Int128And($this->Address, $this->GetNetMask());
     96  }
     97
     98  function GetOctets(): array
    8299  {
    83100    $Result = array();
     
    85102    foreach ($Data as $Item)
    86103    {
    87 
    88104      $Result[] = dechex($Item & 15);
    89105      $Result[] = dechex(($Item >> 4) & 15);
     
    92108  }
    93109
    94   function EncodeMAC($MAC)
     110  function EncodeMAC(string $MAC): void
    95111  {
    96112    $MAC = explode(':', $MAC);
     
    107123  }
    108124
     125  function Contain(NetworkAddressIPv6 $Address): bool
     126  {
     127    $UpperNetmask = $this->GetNetMask();
     128    if (($this->Prefix < $Address->Prefix) and ((Int128Equal(Int128And($Address->Address, $UpperNetmask), Int128And($this->Address, $UpperNetmask))))) $Result = true;
     129      else $Result = false;
     130    return $Result;
     131  }
    109132}
  • trunk/Packages/Common/Page.php

    r7 r8  
    33class Page extends View
    44{
    5   var $Title;
    6   var $ParentClass;
    7   var $RawPage;
    8   var $OnSystemMessage;
     5  public string $Title;
     6  public string $Description;
     7  public string $ParentClass;
     8  public bool $RawPage;
     9  public $OnSystemMessage;
     10  public string $Load;
     11  public string $Unload;
    912
    1013  function __construct(System $System)
     
    1316    $this->RawPage = false;
    1417    $this->OnSystemMessage = array();
     18    $this->Title = "";
     19    $this->Description = "";
     20    $this->ParentClass = "";
    1521  }
    1622
    17   function Show()
     23  function Show(): string
    1824  {
    1925    return '';
    2026  }
    2127
    22   function GetOutput()
     28  function GetOutput(): string
    2329  {
    2430    $Output = $this->Show();
     
    2632  }
    2733
    28   function SystemMessage($Title, $Text)
     34  function SystemMessage(string $Title, string $Text): string
    2935  {
    3036    return call_user_func_array($this->OnSystemMessage, array($Title, $Text));
  • trunk/Packages/Common/PrefixMultiplier.php

    r7 r8  
    7272class PrefixMultiplier
    7373{
    74   function TruncateDigits($Value, $Digits = 4)
     74  function TruncateDigits($Value, $Digits = 4): string
    7575  {
    7676    for ($II = 2; $II > -6; $II--)
     
    8787  }
    8888
    89   function Add($Value, $Unit, $Digits = 4, $PrefixType = 'Decimal')
     89  function Add($Value, $Unit, $Digits = 4, $PrefixType = 'Decimal'): string
    9090  {
    9191    global $PrefixMultipliers;
  • trunk/Packages/Common/RSS.php

    r7 r8  
    33class RSS
    44{
    5   var $Charset;
    6   var $Title;
    7   var $Link;
    8   var $Description;
    9   var $WebmasterEmail;
    10   var $Items;
     5  public string $Charset;
     6  public string $Title;
     7  public string $Link;
     8  public string $Description;
     9  public string $WebmasterEmail;
     10  public array $Items;
    1111
    1212  function __construct()
    1313  {
    1414    $this->Charset = 'utf8';
     15    $this->Title = '';
     16    $this->Link = '';
     17    $this->Description = '';
     18    $this->WebmasterEmail = '';
    1519    $this->Items = array();
    1620  }
    1721
    18   function Generate()
     22  function Generate(): string
    1923  {
    2024    $Result = '<?xml version="1.0" encoding="'.$this->Charset.'" ?>'."\n". //<?
  • trunk/Packages/Common/Table.php

    r7 r8  
    33class Control
    44{
    5   var $Name;
     5  public string $Name;
    66
    7   function Show()
     7  function Show(): string
    88  {
    99    return '';
     
    1313class Table
    1414{
    15   function GetCell($Y, $X)
     15  function GetCell($Y, $X): string
    1616  {
    1717    return '';
     
    2626  }
    2727
    28   function RowsCount()
     28  function RowsCount(): int
    2929  {
    3030    return 0;
     
    3434class TableMemory extends Table
    3535{
    36   var $Cells;
     36  public array $Cells;
    3737
    38   function GetCell($Y, $X)
     38  function GetCell($Y, $X): string
    3939  {
    4040    return $this->Cells[$Y][$X];
    4141  }
    4242
    43   function RowsCount()
     43  function RowsCount(): int
    4444  {
    4545    return count($this->Cells);
     
    4949class TableSQL extends Table
    5050{
    51   var $Query;
    52   var $Database;
    53   var $Cells;
     51  public string $Query;
     52  public Database $Database;
     53  public array $Cells;
    5454
    55   function GetCell($Y, $X)
     55  function GetCell($Y, $X): string
    5656  {
    5757    return $this->Cells[$Y][$X];
     
    7373  }
    7474
    75   function RowsCount()
     75  function RowsCount(): int
    7676  {
    7777    return count($this->Cells);
     
    8181class TableColumn
    8282{
    83   var $Name;
    84   var $Title;
     83  public string $Name;
     84  public string $Title;
    8585}
    8686
    8787class VisualTable extends Control
    8888{
    89   var $Cells;
    90   var $Columns;
    91   var $OrderSQL;
    92   var $OrderColumn;
    93   var $OrderDirection;
    94   var $OrderArrowImage;
    95   var $DefaultColumn;
    96   var $DefaultOrder;
    97   var $Table;
    98   var $Style;
     89  public array $Cells;
     90  public array $Columns;
     91  public string $OrderSQL;
     92  public string $OrderColumn;
     93  public int $OrderDirection;
     94  public array $OrderArrowImage;
     95  public string $DefaultColumn;
     96  public int $DefaultOrder;
     97  public TableMemory $Table;
     98  public string $Style;
     99  private array $OrderDirSQL;
    99100
    100   function __construct(Application $System)
     101  function __construct()
    101102  {
     103    global $System;
     104
    102105    $this->Columns = array();
    103106    $this->Table = new TableMemory();
     
    124127  }
    125128
    126   function Show()
     129  function Show(): string
    127130  {
    128131    $Output = '<table class="'.$this->Style.'">';
     
    146149  }
    147150
    148   function GetOrderHeader()
     151  function GetOrderHeader(): string
    149152  {
    150153    if (array_key_exists('OrderCol', $_GET)) $_SESSION['OrderCol'] = $_GET['OrderCol'];
  • trunk/Packages/Common/UTF8.php

    r7 r8  
    526526  }
    527527
    528   function ToUTF8($String, $Charset = 'iso2')
     528  function ToUTF8(string $String, string $Charset = 'iso2'): string
    529529  {
    530530    $Result = '';
     
    540540  }
    541541
    542   function FromUTF8($String, $Charset = 'iso2')
     542  function FromUTF8(string $String, string $Charset = 'iso2'): string
    543543  {
    544544    $Result = '';
     
    546546    for ($I = 0; $I < strlen($String); $I++)
    547547    {
    548       if (ord($String{$I}) & 0x80) // UTF control character
     548      if (ord($String[$I]) & 0x80) // UTF control character
    549549      {
    550         if (ord($String{$I}) & 0x40) // First
     550        if (ord($String[$I]) & 0x40) // First
    551551        {
    552552          if ($UTFPrefix != '') $Result .= chr(array_search($UTFPrefix, $this->CharTable[$Charset]));
    553           $UTFPrefix = $String{$I};
     553          $UTFPrefix = $String[$I];
    554554        }
    555         else $UTFPrefix .= $String{$I}; // Next
     555        else $UTFPrefix .= $String[$I]; // Next
    556556      } else
    557557      {
    558558        if ($UTFPrefix != '') $Result .= chr(array_search($UTFPrefix, $this->CharTable[$Charset]));
    559559        $UTFPrefix = '';
    560         $Result .= $String{$I};
     560        $Result .= $String[$I];
    561561      }
    562562    }
  • trunk/Packages/Common/Update.php

    r7 r8  
    33class UpdateManager
    44{
    5   var $Revision;
    6   var $Trace;
    7   var $VersionTable;
    8   /* @var Database */
    9   var $Database;
    10   var $InstallMethod;
     5  public int $Revision;
     6  public array $Trace;
     7  public string $VersionTable;
     8  public Database $Database;
     9  public string $InstallMethod;
     10  public $InsertSampleDataMethod;
    1111
    1212  function __construct()
     
    1919  }
    2020
    21   function GetDbVersion()
     21  function GetDbVersion(): ?int
    2222  {
    2323    $DbResult = $this->Database->select($this->VersionTable, '*', 'Id=1');
     
    2626  }
    2727
    28   function IsInstalled()
     28  function IsInstalled(): bool
    2929  {
    3030    $DbResult = $this->Database->query('SHOW TABLES LIKE "'.$this->VersionTable.'"');
     
    3232  }
    3333
    34   function IsUpToDate()
     34  function IsUpToDate(): bool
    3535  {
    3636    return $this->Revision <= $this->GetDbVersion();
    3737  }
    3838
    39   function Upgrade()
     39  function Upgrade(): string
    4040  {
    4141    $DbRevision = $this->GetDbVersion();
     
    4343    while ($this->Revision > $DbRevision)
    4444    {
     45      if (!array_key_exists($DbRevision, $this->Trace))
     46        die('Missing upgrade trace for revision '.$DbRevision);
    4547      $TraceItem = $this->Trace[$DbRevision];
    4648      $Output .= 'Aktualizace na verzi '.$TraceItem['Revision'].':<br/>';
     
    5759  }
    5860
    59   function Install()
     61  function Install(): void
    6062  {
    6163    $InstallMethod = $this->InstallMethod;
    6264    $InstallMethod($this);
    63     $this->Update();
    6465  }
    6566
    66   function Uninstall()
     67  function Uninstall(): void
    6768  {
    68 
    6969  }
    7070
    71   function InsertSampleData()
     71  function InsertSampleData(): void
    7272  {
    7373    $InstallMethod = $this->InsertSampleDataMethod;
     
    7575  }
    7676
    77   function Execute($Query)
     77  function Execute(string $Query): DatabaseResult
    7878  {
    7979    echo($Query.';<br/>');
Note: See TracChangeset for help on using the changeset viewer.