<?php

/**
 * InstallModel
 *
 */
class InstallModel
{
    public static $version = 'BETA 0.16.0';

    public static function checkInstallationComplete()
    {
        $status = array();
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();
        if (!$database) {
            Session::add('feedback_negative',
                            AdminText::get('FEEDBACK_DATABASE_NOT_CONFIGURED_OR_FALSE'));
            $status['db'] = false;
        } else {
            $status['db'] = true;
        }

        if (Config::getFromDB('MarketInstallationComplete')) {
            $status['installed'] = true;
            if (Config::getFromDB('MarketVersion') != self::$version) {
                UpgradeModel::runUpgrade();
            }
        } else {
            $status['installed'] = false;
        }
        return $status;
    }

    public static function init()
    {
        self::create_table_settings();
        self::create_table_users();
        self::create_table_profiles();
        self::create_table_offers();
        self::create_table_pages();
        self::create_table_places();
        self::create_table_platforms();
        self::create_table_category_platforms();
        self::create_table_sync_log();
        self::create_table_api_log();
        self::create_table_mails();
        self::create_table_searches();
        self::create_standard_images();
    }

    public static function install()
    {
        $install = new stdClass();
        $install->userName = '';
        $install->userEmail = '';
        $install->userPassword = '';
        $install->userPasswordRepeat = '';
        $install->marketName = '';
        if (Request::post('installNow') == 1)
        {
            // clean the input
            $install->userName = strip_tags(Request::post('adminName', true));
            $install->userEmail = strip_tags(Request::post('adminEmail'));
            $install->userPassword = Request::post('adminPW');
            $install->userPasswordRepeat = Request::post('adminPW2');
            $install->marketName = Request::post('platformName', true);

            // crypt the password with the PHP 5.5's password_hash() function,
            // results in a 60 character hash string.
            // @see php.net/manual/en/function.password-hash.php for more
            $userPasswordHash = password_hash($install->userPassword,
                                              PASSWORD_DEFAULT);

            if (!RegistrationModel::validateUserName($install->userName) ||
                !RegistrationModel::validateUserEmail($install->userEmail) ||
                !RegistrationModel::validateUserPassword($install->userPassword,
                                                         $install->userPasswordRepeat) ||
                !AdminModel::validateMarketName($install->marketName))
            {
                return $install;
            } else {
                self::saveUser($install->userName,
                               $userPasswordHash,
                               $install->userEmail);
            }

            // get user_id of the user that has been created,
            // to keep things clean we DON'T use lastInsertId() here
            $user_id = UserModel::getUserIdByUsername($install->userName);

            if (!$user_id) {
                Session::add('feedback_negative', Text::get('FEEDBACK_UNKNOWN_ERROR'));
                return $install;
            } else {
                // GENERATE AND SAVE STANDARD SETTINGS
                self::insertSetting('MarketRegistrationStatus','value_int',2);
                self::insertSetting('MarketName','value_text',$install->marketName);
                self::insertSetting('MarketClaim',
                                    'value_text',
                                    'lokal isst besser!');
                self::insertSetting('MarketURL','value_text',Config::get('URL'));
                // GENERATE UUID
                $uuid = sha1($install->marketName.Config::get('URL').time());
                self::insertSetting('MarketUUID','value_text',$uuid);
                self::insertSetting('MarketUsedTheme','value_text','samarkand');
                self::insertSetting('MarketLogo','value_text','platform/:.png');
                self::insertSetting('MarketHeader','value_text','platform/:.jpeg');
                self::insertSetting('MarketBackground','value_text','platform/:.jpeg');
                self::insertSetting('MarketDetailShort','value_text','');
                self::insertSetting('MarketDetail','value_text','');
                self::insertSetting('MarketDetailLink','value_int',0);
                self::insertSetting('MarketDetailLinkText','value_text',AdminText::get('DEFAULT_DETAIL_LINK_TEXT'));
                self::insertSetting('MarketContactPerson','value_text','');
                self::insertSetting('MarketContactTel','value_text','');
                self::insertSetting('MarketContactFax','value_text','');
                self::insertSetting('MarketContactEmail','value_text','');
                self::insertSetting('MarketContactWeb','value_text','');
                self::insertSetting('MarketAddressStreet','value_text','');
                self::insertSetting('MarketAddressNumber','value_text','');
                self::insertSetting('MarketAddressZipcode','value_text','');
                self::insertSetting('MarketAddressCity','value_text','');
                self::insertSetting('MarketAddressState','value_text','');
                self::insertSetting('MarketAddressCountry','value_text','');
                self::insertSetting('MarketContactLink','value_int',0);
                self::insertSetting('MarketContactLinkText','value_text',AdminText::get('DEFAULT_CONTACT_LINK_TEXT'));
                self::insertSetting('MarketShareStatistics','value_int',1);
                self::insertSetting('MarketAdminEmail','value_text',$install->userEmail);
                self::insertSetting('MarketStatisticsLastSync','value_int',0);
                self::insertSetting('MarketVersion','value_text',self::$version);
                self::insertSetting('MarketInstallationComplete','value_int',1);
                self::insertPage('Beispielseite',
                                 '<h1>Hallo Welt</h1>Dies ist nur eine Beispielseite,
                                  als Administrator können Sie diese im Administrationsmenü
                                  bearbeiten',
                                 'about'
                                 ,1);
                self::insertPage('Impressum',
                                 '<h1>Hallo Welt</h1>Dies ist nur eine Beispielseite,
                                  als Administrator können Sie diese im Administrationsmenü
                                  bearbeiten',
                                 'imprint'
                                 ,1);
                Config::unsetDBConfig();
                ConnectionsModel::connect('https://meta.peeragora.org',true);
                self::populatePlaces();
                Session::add('feedback_positive', '<a href="'.Config::getURL().
                             '">'.AdminText::get('INSTALL_DONE').'</a>');
                return true;
            }
        }
        else
        {
            return $install;
        }
    }

    public static function create_table_settings()
    {
        $tablename = "`".Config::get('DB_PREFIX')."settings`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
              `value_text` text COLLATE utf8_unicode_ci NOT NULL,
              `value_int` int(10) DEFAULT NULL,
              `created` datetime NOT NULL,
              `modified` datetime NOT NULL,
              PRIMARY KEY (`id`),
              UNIQUE KEY `name` (`name`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_users()
    {
        $tablename = "`".Config::get('DB_PREFIX')."users`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `user_id` int(11) NOT NULL AUTO_INCREMENT,
              `user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
              `user_password_hash` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
              `user_email` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
              `user_active` tinyint(1) NOT NULL DEFAULT '0',
              `user_approved` tinyint(1) NOT NULL DEFAULT '0',
              `user_is_admin` tinyint(1) NOT NULL DEFAULT '0',
              `user_remember_me_token` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL,
              `user_creation_timestamp` bigint(20) DEFAULT NULL,
              `user_last_login_timestamp` bigint(20) DEFAULT NULL,
              `user_failed_logins` tinyint(1) NOT NULL DEFAULT '0',
              `user_last_failed_login` int(10) DEFAULT NULL,
              `user_activation_hash` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
              `user_password_reset_hash` char(40) COLLATE utf8_unicode_ci DEFAULT NULL,
              `user_password_reset_timestamp` bigint(20) DEFAULT NULL,
              PRIMARY KEY (`user_id`),
              UNIQUE KEY `user_name` (`user_name`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_profiles()
    {
        $tablename = "`".Config::get('DB_PREFIX')."profiles`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(10) NOT NULL AUTO_INCREMENT,
              `company_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_claim` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_short_info` varchar(500) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_info` varchar(5000) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_opening_hours` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_logo_path` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_header_path` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_contact_person` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_phone` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_fax` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_email` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_website` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_address_street` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_address_street_number` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_address_zipcode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_address_city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_address_state` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
              `company_address_country` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
              `user_id` int(10) NOT NULL,
              `admin_featured` tinyint(1) NOT NULL DEFAULT '0',
              `other_featured` tinyint(1) NOT NULL DEFAULT '0',
              `created` datetime NOT NULL,
              `modified` datetime NOT NULL,
              PRIMARY KEY (`id`),
              KEY `user_id` (`user_id`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_offers()
    {
        $tablename = "`".Config::get('DB_PREFIX')."offers`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(10) NOT NULL AUTO_INCREMENT,
              `type` tinyint(1) NOT NULL DEFAULT '1',
              `title` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
              `detail` text COLLATE utf8_unicode_ci,
              `tags` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
              `price` decimal(20,8) DEFAULT NULL,
              `currency` int(3) NOT NULL,
              `unit` int(3) NOT NULL,
              `image` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
              `user_featured` tinyint(1) NOT NULL DEFAULT '0',
              `admin_featured` tinyint(1) NOT NULL DEFAULT '0',
              `profile_id` int(10) NOT NULL,
              `status` tinyint(1) NOT NULL DEFAULT '0',
              `cat1` smallint(3) NOT NULL,
              `cat2` smallint(3) NOT NULL,
              `cat3` smallint(3) NOT NULL,
              `zipcode` VARCHAR( 10 ) DEFAULT NULL,
              `external` tinyint(1) NOT NULL DEFAULT '0',
              `external_url` varchar(300) COLLATE utf8_unicode_ci DEFAULT NULL,
              `external_id` int(10) DEFAULT NULL,
              `external_platform_id` int(10) DEFAULT NULL,
              `created` datetime DEFAULT NULL,
              `modified` datetime DEFAULT NULL,
              PRIMARY KEY (`id`),
              FULLTEXT KEY `title` (`title`,`detail`,`tags`),
              KEY `type` (`type`),
              KEY `profile_id` (`profile_id`),
              KEY `status` (`status`),
              KEY `cat1` (`cat1`),
              KEY `cat2` (`cat2`),
              KEY `cat3` (`cat3`),
              KEY `external` (`external`),
              KEY `external_id` (`external_id`),
              KEY `external_platform_id` (`external_platform_id`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_pages()
    {
        $tablename = "`".Config::get('DB_PREFIX')."pages`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(9) NOT NULL AUTO_INCREMENT,
              `slug` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
              `title` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
              `body` text COLLATE utf8_unicode_ci,
              `sort_index` int(9) NOT NULL,
              `status` int(9) NOT NULL DEFAULT '0',
              `created` datetime NOT NULL,
              `modified` datetime NOT NULL,
              PRIMARY KEY (`id`),
              KEY `slug` (`slug`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_places()
    {
        $tablename = "`".Config::get('DB_PREFIX')."places`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(20) unsigned NOT NULL AUTO_INCREMENT,
              `plz` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
              `name` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
              `lat` int(11) DEFAULT NULL,
              `lon` int(11) DEFAULT NULL,
              `adm1` varchar(180) COLLATE utf8_unicode_ci DEFAULT NULL,
              `adm2` varchar(180) COLLATE utf8_unicode_ci DEFAULT NULL,
              `adm3` varchar(180) COLLATE utf8_unicode_ci DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_platforms()
    {
        $tablename = "`".Config::get('DB_PREFIX')."platforms`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(30) NOT NULL AUTO_INCREMENT,
              `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
              `url` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
              `location` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
              `short_info` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
              `status` int(1) NOT NULL DEFAULT '0',
              `uuid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
              `remote_public_key` varchar(512) COLLATE utf8_unicode_ci NOT NULL,
              `own_public_key` varchar(512) COLLATE utf8_unicode_ci NOT NULL,
              `private_key` varchar(1024) COLLATE utf8_unicode_ci NOT NULL,
              `send` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
              `receive` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
              `remote_receive` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
              `failed_sync_count` int(4) NOT NULL DEFAULT '0',
              `last_successful_sync` datetime DEFAULT NULL,
              `modified` datetime DEFAULT NULL,
              `created_on` datetime NOT NULL,
              `connected_since` datetime NOT NULL,
              PRIMARY KEY (`id`),
              UNIQUE KEY `uuid` (`uuid`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_category_platforms()
    {
        $tablename = "`".Config::get('DB_PREFIX')."category_platforms`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(30) NOT NULL AUTO_INCREMENT,
              `cat1` int(3) DEFAULT NULL,
              `cat2` int(3) DEFAULT NULL,
              `cat3` int(3) DEFAULT NULL,
              `send` int(10) DEFAULT NULL,
              `receive` int(10) DEFAULT NULL,
              `remote_receive` int(10) DEFAULT NULL,
              PRIMARY KEY (`id`),
              KEY `cat1` (`cat1`),
              KEY `cat2` (`cat2`),
              KEY `cat3` (`cat3`),
              KEY `send` (`send`),
              KEY `receive` (`receive`),
              KEY `remote_receive` (`remote_receive`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_sync_log()
    {
        $tablename = "`".Config::get('DB_PREFIX')."sync_log`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(10) NOT NULL AUTO_INCREMENT,
              `data_id` int(10) NOT NULL,
              `platform_id` int(10) NOT NULL,
              `last_changed` datetime NOT NULL,
              `timestamp` datetime NOT NULL,
              PRIMARY KEY (`id`),
              KEY `data_id` (`data_id`),
              KEY `platform_id` (`platform_id`),
              KEY `last_changed` (`last_changed`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");

        return $created;
    }

    public static function create_table_api_log()
    {
        $tablename = "`".Config::get('DB_PREFIX')."api_log`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(30) NOT NULL AUTO_INCREMENT,
              `success` tinyint(1) NOT NULL DEFAULT '0',
              `external_uuid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
              `endpoint` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
              `data` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
              `timestamp` datetime NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_mails()
    {
        $tablename = "`".Config::get('DB_PREFIX')."mails`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(30) NOT NULL AUTO_INCREMENT,
              `email` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
              `subject` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
              `body` varchar(5000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
              `send_try` int(1) NOT NULL DEFAULT '0',
              PRIMARY KEY (`id`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_table_searches()
    {
        $tablename = "`".Config::get('DB_PREFIX')."searches`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $created = $database->query("
            CREATE TABLE IF NOT EXISTS ".$tablename." (
              `id` int(30) NOT NULL AUTO_INCREMENT,
              `searchterm` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
              `results` int(3) NOT NULL,
              `created` datetime NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
        return $created;
    }

    public static function create_standard_images()
    {
        $error = false;
        $storeFolder = Config::get('PATH_UPLOADS') . 'platform' . DIRECTORY_SEPARATOR;
        if (!is_dir($storeFolder)) {
            if (mkdir($storeFolder, 0755, true)) {
                chmod($storeFolder, 0755);
                $writable = true;
            } else {
                $writable = false;
            }
        } else {
            $allgood = true;
        }
        if (isset($writable) && $writable == true) {
            $images = require Config::get('PATH_UPLOADS').'pix_install.php';
            require Config::get('PATH_LIBS') . 'SimpleImage.php';
            ini_set('memory_limit','128M');
            set_error_handler(function ($errno, $errstr) {
              throw new Exception($errstr, $errno);
            }, E_WARNING);
            foreach ($images as $type => $image) {
              $number = 0;
              try {
                $img = new SimpleImage($image['data']);
                foreach ($image['dimensions'] as $size => $dimensions) {
                  if ($size == 'logo') {
                    $name = 'logo.png';
                  } else {
                    $name = $type.'_'.$size.'.'.$image['extension'];
                  }
                  $img->thumbnail($dimensions['width'], $dimensions['height'])
                  ->save($storeFolder.$name);
                }
              } catch(Exception $e) {
                  $error = true;
              }
            }
            if ($error == true) {
                Session::add('feedback_negative',AdminText::get('FEEDBACK_UPLOAD_DIR_NOT_WRITABLE'));
            }
            restore_error_handler();
        } else {
            if (!isset($allgood)) {
                Session::add('feedback_negative',AdminText::get('FEEDBACK_UPLOAD_DIR_NOT_WRITABLE'));
            }
        }
    }

    public static function check_if_setting_exists($setting)
    {
        $tablename = "`".Config::get('DB_PREFIX')."settings`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $sql = "SELECT id FROM ".$tablename." WHERE name = :setting_name LIMIT 1";
        $query = $database->prepare($sql);
        $query->bindParam(':setting_name', $setting->name, PDO::PARAM_STR);
        $query->execute();
        if ($query->rowCount() == 1)
        {
            return true;
        } else {
            return false;
        }
    }

    public static function insertSetting($setting_name,$field_name,$value)
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        if ($field_name == 'value_text')
        {
            $sql = "INSERT INTO ".$prefix."settings
                           (name,
                            value_text,
                            created)
                    VALUES (:setting_name,
                            :value,
                            NOW())";
        } else {
            $sql = "INSERT INTO ".$prefix."settings
                           (name,
                            value_int,
                            created)
                    VALUES (:setting_name,
                            :value,
                            NOW())";
        }
        $query = $database->prepare($sql);
        $query->execute(array(':setting_name' => $setting_name,
                              ':value' => $value));
        if ($query->rowCount() > 0)
        {
            return true;
        } else {
            return false;
        }
    }

    public static function insertPage($page_title,$page_body,$page_slug,$sort)
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "INSERT INTO ".$prefix."pages
                       (title,
                        body,
                        slug,
                        sort_index,
                        status,
                        created)
                VALUES (:title,
                        :body,
                        :slug,
                        :sort_index,
                        2,
                        NOW())";
        $query = $database->prepare($sql);
        $query->execute(array(':title'      => $page_title,
                              ':body'       => $page_body,
                              ':slug'       => $page_slug,
                              ':sort_index' => $sort));
        if ($query->rowCount() > 0)
        {
            return true;
        } else {
            return false;
        }
    }

    private static function saveUser($user_name,$user_password_hash,$user_email)
    {
        $user_creation_timestamp = time();
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "INSERT INTO ".$prefix."users
                       (user_name,
                        user_password_hash,
                        user_email,
                        user_active,
                        user_approved,
                        user_is_admin,
                        user_creation_timestamp)
                VALUES (:user_name,
                        :user_password_hash,
                        :user_email,
                        1,
                        1,
                        2,
                        :user_creation_timestamp)";
        $query = $database->prepare($sql);
        $query->execute(array(':user_name' => $user_name,
                              ':user_password_hash' => $user_password_hash,
                              ':user_email' => $user_email,
                              ':user_creation_timestamp' => $user_creation_timestamp));
        $count =  $query->rowCount();
        if ($count == 1) {
            return true;
        }

        return false;
    }

    public static function populatePlaces()
    {
        $tablename = "`".Config::get('DB_PREFIX')."places`";
        $database = DatabaseFactory::getFactory()->getConnection();
        $sql = "INSERT INTO ".$tablename." (`id`, `plz`, `name`, `lat`, `lon`) VALUES";
        $sql .= file_get_contents(Config::get('PATH_LIBS').'places_de.sql');
        $query = $database->prepare($sql);
        if ($query->execute())
        {
            return true;
        } else {
            return false;
        }
    }
}
