public function insert_comment($sid, $msg, $parent, $author_name, $author_email)
 {
     // Connect to database
     try {
         $handler = new Database();
         // Insert comment to database
         if ($parent !== 'NULL') {
             $handler->beginTransaction();
             // If comment has a parent begin transaction
         }
         $res = $handler->prepare('INSERT INTO `comment`(`sid`, `author_name`, `author_email`, `message`, `parent`) VALUES (:sid, :author_name, :author_email, :message, :parent)');
         $res->execute(array(':sid' => $sid, ':author_name' => $author_name, ':author_email' => $author_email, ':message' => $msg, ':parent' => $parent));
         if ($res->rowCount() !== 1) {
             return false;
         }
         // Get cid of last comment
         $cid = $handler->lastInsertId();
         if ($parent !== 'NULL') {
             $res = $handler->prepare('UPDATE `comment` SET `children` = 1 WHERE `cid` = :parent');
             $res->execute(array(':parent' => $parent));
             $handler->commit();
             // Commit only if both queries succeed
         }
     } catch (PDOException $e) {
         if ($parent !== 'NULL') {
             $handler->rollback();
         }
         return false;
     }
     return $cid;
 }
 public function evolve($buildingId)
 {
     $query = "\n            SELECT\n                ubl.building_id as 'Id',\n                ubl.level_id AS 'Level',\n                bl.gold AS 'Gold',\n                bl.food AS 'Food'\n            FROM users_buildings_levels ubl\n            JOIN buildings b\n                ON b.id = ubl.building_id\n            JOIN building_levels bl\n                ON bl.building_id = ubl.building_id AND bl.level = ubl.level_id + 1\n            WHERE ubl.user_id = ? AND ubl.building_id = ?\n        ";
     $result = $this->database->prepare($query);
     $result->execute([$_SESSION['id'], $buildingId]);
     $building = $result->fetch(\PDO::FETCH_ASSOC);
     if ($this->user->getGold() < $building['Gold'] || $this->user->getFood() < $building['Food']) {
         throw new \Exception('Insufficient resource to evolve building');
     }
     if ($building['Level'] == 3) {
         throw new \Exception('Building has reached maximum level and cannot be evolved');
     }
     $resourceUpdate = "\n            UPDATE users\n            SET gold = ?, food = ?\n            WHERE id = ?\n        ";
     $result = $this->database->prepare($resourceUpdate);
     $result->execute([$this->user->getGold() - $building['Gold'], $this->user->getFood() - $building['Food'], $_SESSION['id']]);
     if ($result) {
         $buildingUpdate = "\n                UPDATE users_buildings_levels\n                SET level_id = ?\n                WHERE user_id = ? AND building_id = ?\n            ";
         $result = $this->database->prepare($buildingUpdate);
         $result->execute([$building['Level'] + 1, $_SESSION['id'], $buildingId]);
         if ($result) {
             return true;
         }
         throw new \Exception('Error occurred while upgrading building');
     }
     throw new \Exception('Error occurred while upgrading building');
 }
 public function getBuildings()
 {
     $result = $this->db->prepare("\n            SELECT b.id, b.name, bl.level, bl.gold, bl.food\n            FROM players_buildings ub\n            LEFT JOIN buildings b ON b.id = ub.building_id\n            LEFT JOIN levels bl ON bl.building_id = b.id AND bl.level = ub.level_id + 1\n            WHERE user_id = ?");
     $user_id = $this->getUser()->getId();
     $result->execute([$user_id]);
     return $result->fetchAll();
 }
Exemple #4
0
 /**
  * Save layer relations.
  *
  * @param mixed          $layerId       The layer id values.
  * @param \DataContainer $dataContainer The dataContainer driver.
  *
  * @return null
  */
 public function saveLayerRelations($layerId, $dataContainer)
 {
     $new = deserialize($layerId, true);
     $values = array();
     $result = $this->database->prepare('SELECT * FROM tl_leaflet_map_layer WHERE mid=? order BY sorting')->execute($dataContainer->id);
     while ($result->next()) {
         $values[$result->lid] = $result->row();
     }
     $sorting = 0;
     foreach ($new as $layerId) {
         if (!isset($values[$layerId])) {
             $this->database->prepare('INSERT INTO tl_leaflet_map_layer %s')->set(array('tstamp' => time(), 'lid' => $layerId, 'mid' => $dataContainer->id, 'sorting' => $sorting))->execute();
             $sorting += 128;
         } else {
             if ($values[$layerId]['sorting'] <= $sorting - 128 || $values[$layerId]['sorting'] >= $sorting + 128) {
                 $this->database->prepare('UPDATE tl_leaflet_map_layer %s WHERE id=?')->set(array('tstamp' => time(), 'sorting' => $sorting))->execute($values[$layerId]['id']);
             }
             $sorting += 128;
             unset($values[$layerId]);
         }
     }
     $ids = array_map(function ($item) {
         return $item['id'];
     }, $values);
     if ($ids) {
         $this->database->query('DELETE FROM tl_leaflet_map_layer WHERE id IN(' . implode(',', $ids) . ')');
     }
     return null;
 }
 /**
  * Load permissions for the given row id.
  *
  * @param int $rowId The road id.
  *
  * @return void
  */
 private function loadPermissions($rowId)
 {
     $permissions = array();
     $result = $this->database->prepare('SELECT * FROM tl_workflow_permission WHERE source=? AND source_id=?')->execute($this->source, $rowId);
     while ($result->next()) {
         $permissions[$result->permission] = $result->id;
     }
     $this->permissions = $permissions;
 }
 /**
  * Set row's active field to 0. We don't delete rows from database for sake of keeping it consistent
  * @param $id
  * @param $table
  * @return array
  */
 public function delete($id, $table)
 {
     $query = "UPDATE " . $table;
     $query .= ' SET active = 0 WHERE id = ? AND store_id = ?';
     $preparedObj = $this->_db->prepare($query);
     $preparedObj->bind_param('ii', $id, $this->store_id);
     $preparedObj->execute();
     $results = $preparedObj->get_result();
     return $this->result_array($results);
 }
 private function startQuery($search_string)
 {
     $database = new Database();
     $database->Create(new EventTable());
     /*
                 
                $sqlFullText= "CREATE FULLTEXT INDEX If Not Exists search ON ".EventTable::TableName.
                        "(".EventTable::Title.",".
                         EventTable::Description.",".
                         EventTable::SeachableKeywords.",".
                         EventTable::Venue.")";
                 
                  * ".EventTable::Title, "(".EventTable::Title.","
                           .EventTable::Description.",".EventTable::SeachableKeywords.",".EventTable::Venue."
                  * 
                 $database->runCommand($sqlFullText);
                  * */
     $query_string = $database->quote($search_string);
     $squery = "select *from " . EventTable::TableName . " WHERE ( MATCH (" . EventTable::Title . "," . EventTable::Description . "," . EventTable::SeachableKeywords . "," . EventTable::Venue . ") AGAINST ({$query_string} IN BOOLEAN MODE)) AND " . EventTable::Status . " > :zero";
     $stmt = $database->prepare($squery);
     $stmt->bindValue(":zero", 0);
     $status = $stmt->execute();
     if ($status) {
         $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
         for ($i = 0; $i < count($rows); $i++) {
             $rows[$i][EventTable::Image] = IMAGE_EVENT_PATHS . $rows[$i][EventTable::Image];
         }
         return $rows;
     } else {
         print_r($stmt->errorInfo());
         return null;
     }
 }
Exemple #8
0
 static function validateToken($token)
 {
     $db = new Database();
     $query = $db->prepare("SElECT * FROM password_resets where token = :token");
     $query->bindParam(':token', $token);
     $query->execute();
     $data = $query->fetch(PDO::FETCH_ASSOC);
     if (!self::checkTokenDate(strtotime($data['created_at']))) {
         // if self::checkExpirationDate returns 'false'
         $query = $db->prepare("DELETE FROM password_resets where token = :token");
         $query->bindParam(':token', $token);
         $query->execute();
         $_SESSION['error_message'] = self::$ER_MSG;
         View::render('index.php');
     }
 }
Exemple #9
0
 public function initAccount($certrow)
 {
     // Let's see if we have the private accountkey
     $this->accountKey = $certrow['leprivatekey'];
     if (!$this->accountKey || $this->accountKey == 'unset' || Settings::Get('system.letsencryptca') != 'production') {
         // generate and save new private key for account
         // ---------------------------------------------
         $this->log('Starting new account registration');
         $keys = $this->generateKey();
         // Only store the accountkey in production, in staging always generate a new key
         if (Settings::Get('system.letsencryptca') == 'production') {
             $upd_stmt = Database::prepare("UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `lepublickey` = :public, `leprivatekey` = :private " . "WHERE `customerid` = :customerid;");
             Database::pexecute($upd_stmt, array('public' => $keys['public'], 'private' => $keys['private'], 'customerid' => $certrow['customerid']));
         }
         $this->accountKey = $keys['private'];
         $response = $this->postNewReg();
         if ($this->client->getLastCode() != 201) {
             throw new \RuntimeException("Account not initialized, probably due to rate limiting. Whole response: " . $response);
         }
         $this->postNewReg();
         $this->log('New account certificate registered');
     } else {
         $this->log('Account already registered. Continuing.');
     }
 }
 private function updateEvent($user_id, $user_password, $event_id, $searchablekeywords)
 {
     $response = array();
     $response["success"] = 0;
     $jsonView = new JsonViewer();
     $tryLogin = new TryUserLogin($user_id, $user_password);
     if ($tryLogin->isExists()) {
         //update the events
         $database = new Database();
         $sql = "UPDATE " . EventTable::TableName . " set " . EventTable::SeachableKeywords . "=:search_keys WHERE " . EventTable::Id . "=:id";
         $smt = $database->prepare($sql);
         $smt->bindValue(":id", $event_id);
         $smt->bindValue(":search_keys", $searchablekeywords);
         $status = $smt->execute();
         if ($status) {
             $response["success"] = 1;
             $response["message"] = "update searchable keys";
         } else {
             $response["error_message"] = "Invalid event details provided";
         }
     } else {
         $response["error_message"] = "Invalid login details";
     }
     $jsonView->setContent($response);
     return $jsonView;
 }
/**
 * @FIXME remove when fully migrated to new Settings class
 *
 * @param array $settings_data
 *
 * @return array
 */
function loadSettings(&$settings_data)
{
    $settings = array();
    if (is_array($settings_data) && isset($settings_data['groups']) && is_array($settings_data['groups'])) {
        // prepare for use in for-loop
        $row_stmt = Database::prepare("\n\t\t\tSELECT `settinggroup`, `varname`, `value`\n\t\t\tFROM `" . TABLE_PANEL_SETTINGS . "`\n\t\t\tWHERE `settinggroup` = :group AND `varname` = :varname\n\t\t");
        foreach ($settings_data['groups'] as $settings_part => $settings_part_details) {
            if (is_array($settings_part_details) && isset($settings_part_details['fields']) && is_array($settings_part_details['fields'])) {
                foreach ($settings_part_details['fields'] as $field_name => $field_details) {
                    if (isset($field_details['settinggroup']) && isset($field_details['varname']) && isset($field_details['default'])) {
                        // execute prepared statement
                        $row = Database::pexecute_first($row_stmt, array('group' => $field_details['settinggroup'], 'varname' => $field_details['varname']));
                        if (!empty($row)) {
                            $varvalue = $row['value'];
                        } else {
                            $varvalue = $field_details['default'];
                        }
                        $settings[$field_details['settinggroup']][$field_details['varname']] = $varvalue;
                    } else {
                        $varvalue = false;
                    }
                    $settings_data['groups'][$settings_part]['fields'][$field_name]['value'] = $varvalue;
                }
            }
        }
    }
    return $settings;
}
 public static function parent($parent)
 {
     if ($parent === null) {
         // If parent is null
         return true;
     } else {
         if ($parent < 1) {
             // If parent not positive
             return false;
         } else {
             // Check if parent id exists
             // Connect to database
             try {
                 $handler = new Database();
                 // Query database to see if parent id exists
                 $res = $handler->prepare('SELECT `cid` FROM `comment` WHERE `cid` = :parent');
                 $res->execute(array(':parent' => $parent));
             } catch (PDOException $e) {
                 return false;
             } catch (Exception $e) {
                 return false;
             }
             if ($res->rowCount() === 1) {
                 return true;
             }
             return false;
         }
     }
 }
 public function editUser(User $newData)
 {
     $updateQuery = "UPDATE users SET password = ?, username = ? WHERE id = ?";
     $result = $this->database->prepare($updateQuery);
     $result->execute([$newData->getPassword(), $newData->getUsername(), $newData->getId()]);
     return $result->rowCount() > 0;
 }
Exemple #14
0
	/**
	 * Add a log entry
	 * @param string
	 * @param string
	 * @param string
	 */
	protected function log($strText, $strFunction, $strAction)
	{
		$this->import('Database');

		$strUa = 'N/A';
		$strIp = '127.0.0.1';

		if ($this->Environment->httpUserAgent)
		{
			$strUa = $this->Environment->httpUserAgent;
		}
		if ($this->Environment->remoteAddr)
		{
			$strIp = $this->anonymizeIp($this->Environment->remoteAddr);
		}

		$this->Database->prepare("INSERT INTO tl_log (tstamp, source, action, username, text, func, ip, browser) VALUES(?, ?, ?, ?, ?, ?, ?, ?)")
					   ->execute(time(), (TL_MODE == 'FE' ? 'FE' : 'BE'), $strAction, ($GLOBALS['TL_USERNAME'] ? $GLOBALS['TL_USERNAME'] : ''), specialchars($strText), $strFunction, $strIp, $strUa);

		// HOOK: allow to add custom loggers
		if (isset($GLOBALS['TL_HOOKS']['addLogEntry']) && is_array($GLOBALS['TL_HOOKS']['addLogEntry']))
		{
			foreach ($GLOBALS['TL_HOOKS']['addLogEntry'] as $callback)
			{
				$this->import($callback[0]);
				$this->$callback[0]->$callback[1]($strText, $strFunction, $strAction);
			}
		}
	}
function getGraphHeader($database, $photoID)
{
    if (!isset($database, $photoID)) {
        return false;
    }
    $query = Database::prepare($database, "SELECT title, description, url, medium FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photoID));
    $result = $database->query($query);
    $row = $result->fetch_object();
    if ($row->medium === '1') {
        $dir = 'medium';
    } else {
        $dir = 'big';
    }
    $parseUrl = parse_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    $picture = $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['path'] . '/../uploads/' . $dir . '/' . $row->url;
    $return = '<!-- General Meta Data -->';
    $return .= '<meta name="title" content="' . $row->title . '" />';
    $return .= '<meta name="description" content="' . $row->description . ' - via Lychee" />';
    $return .= '<link rel="image_src" type="image/jpeg" href="' . $picture . '" />';
    $return .= '<!-- Twitter Meta Data -->';
    $return .= '<meta name="twitter:card" content="photo">';
    $return .= '<meta name="twitter:title" content="' . $row->title . '">';
    $return .= '<meta name="twitter:image:src" content="' . $picture . '">';
    $return .= '<!-- Facebook Meta Data -->';
    $return .= '<meta property="og:title" content="' . $row->title . '">';
    $return .= '<meta property="og:image" content="' . $picture . '">';
    return $return;
}
/**
 * This file is part of the Froxlor project.
 * Copyright (c) 2003-2009 the SysCP Team (see authors).
 * Copyright (c) 2010 the Froxlor Team (see authors).
 *
 * For the full copyright and license information, please view the COPYING
 * file that was distributed with this source code. You can also view the
 * COPYING file online at http://files.froxlor.org/misc/COPYING.txt
 *
 * @copyright  (c) the authors
 * @author     Florian Lippert <*****@*****.**> (2003-2009)
 * @author     Froxlor team <*****@*****.**> (2010-)
 * @license    GPLv2 http://files.froxlor.org/misc/COPYING.txt
 * @package    Functions
 *
 */
function getIpPortCombinations($ssl = false)
{
    global $userinfo;
    $additional_conditions_params = array();
    $additional_conditions_array = array();
    if ($userinfo['ip'] != '-1') {
        $admin_ip_stmt = Database::prepare("\n\t\t\tSELECT `id`, `ip`, `port` FROM `" . TABLE_PANEL_IPSANDPORTS . "` WHERE `id` = :ipid\n\t\t");
        $admin_ip = Database::pexecute_first($admin_ip_stmt, array('ipid' => $userinfo['ip']));
        $additional_conditions_array[] = "`ip` = :adminip";
        $additional_conditions_params['adminip'] = $admin_ip['ip'];
        $admin_ip = null;
    }
    if ($ssl !== null) {
        $additional_conditions_array[] = "`ssl` = :ssl";
        $additional_conditions_params['ssl'] = $ssl === true ? '1' : '0';
    }
    $additional_conditions = '';
    if (count($additional_conditions_array) > 0) {
        $additional_conditions = " WHERE " . implode(" AND ", $additional_conditions_array) . " ";
    }
    $result_stmt = Database::prepare("\n\t\tSELECT `id`, `ip`, `port` FROM `" . TABLE_PANEL_IPSANDPORTS . "` " . $additional_conditions . " ORDER BY `ip` ASC, `port` ASC\n\t");
    Database::pexecute($result_stmt, $additional_conditions_params);
    $system_ipaddress_array = array();
    while ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) {
        if (filter_var($row['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            $row['ip'] = '[' . $row['ip'] . ']';
        }
        $system_ipaddress_array[$row['id']] = $row['ip'] . ':' . $row['port'];
    }
    return $system_ipaddress_array;
}
 function loadByHost($hostname)
 {
     if (empty($hostname)) {
         return false;
     }
     $stmt = Database::prepare("SELECT * FROM users WHERE hostname=LOWER(?) AND active");
     $res = $stmt->cachedExecute(array($hostname), 3600);
     $stmt = null;
     if (empty($res)) {
         return false;
     }
     foreach (array('id', 'username', 'password', 'hostname', 'private', 'email', 'active', 'fullname', 'notifier_method', 'notifier_params', 'title_name') as $n) {
         $this->{$n} =& $res[$n];
     }
     if ($this->active == 't') {
         $this->active = true;
     } else {
         $this->active = false;
     }
     if ($this->private == 't') {
         $this->private = true;
     } else {
         $this->private = false;
     }
     $this->bin_name = $this->title_name ? $this->title_name : $this->fullname;
     return true;
 }
 /**
  * constructor
  * @param string logFile
  * @param int startTime
  * @param string logFileExim
  */
 public function __construct($startTime = 0)
 {
     $this->startTime = $startTime;
     // Get all domains from Database
     $stmt = Database::prepare("SELECT domain FROM `" . TABLE_PANEL_DOMAINS . "`");
     Database::pexecute($stmt, array());
     while ($domain_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
         $this->myDomains[] = $domain_row["domain"];
     }
     // Parse MTA traffic
     if (Settings::Get("system.mtaserver") == "postfix") {
         $this->_parsePostfixLog(Settings::Get("system.mtalog"));
         $this->_parsePostfixLog(Settings::Get("system.mtalog") . ".1");
     } elseif (Settings::Get("system.mtaserver") == "exim4") {
         $this->_parseExim4Log(Settings::Get("system.mtalog"));
     }
     // Parse MDA traffic
     if (Settings::Get("system.mdaserver") == "dovecot") {
         $this->_parseDovecotLog(Settings::Get("system.mdalog"));
         $this->_parsePostfixLog(Settings::Get("system.mdalog") . ".1");
     } elseif (Settings::Get("system.mdaserver") == "courier") {
         $this->_parseCourierLog(Settings::Get("system.mdalog"));
         $this->_parsePostfixLog(Settings::Get("system.mdalog") . ".1");
     }
 }
/**
 * store the default index-file in a given destination folder
 * 
 * @param string  $loginname   customers loginname
 * @param string  $destination path where to create the file
 * @param object  $logger      FroxlorLogger object
 * @param boolean $force       force creation whatever the settings say (needed for task #2, create new user)
 * 
 * @return null
 */
function storeDefaultIndex($loginname = null, $destination = null, $logger = null, $force = false)
{
    if ($force || (int) Settings::Get('system.store_index_file_subs') == 1) {
        $result_stmt = Database::prepare("\n\t\t\tSELECT `t`.`value`, `c`.`email` AS `customer_email`, `a`.`email` AS `admin_email`, `c`.`loginname` AS `customer_login`, `a`.`loginname` AS `admin_login`\n\t\t\tFROM `" . TABLE_PANEL_CUSTOMERS . "` AS `c` INNER JOIN `" . TABLE_PANEL_ADMINS . "` AS `a`\n\t\t\tON `c`.`adminid` = `a`.`adminid`\n\t\t\tINNER JOIN `" . TABLE_PANEL_TEMPLATES . "` AS `t`\n\t\t\tON `a`.`adminid` = `t`.`adminid`\n\t\t\tWHERE `varname` = 'index_html' AND `c`.`loginname` = :loginname");
        Database::pexecute($result_stmt, array('loginname' => $loginname));
        if (Database::num_rows() > 0) {
            $template = $result_stmt->fetch(PDO::FETCH_ASSOC);
            $replace_arr = array('SERVERNAME' => Settings::Get('system.hostname'), 'CUSTOMER' => $template['customer_login'], 'ADMIN' => $template['admin_login'], 'CUSTOMER_EMAIL' => $template['customer_email'], 'ADMIN_EMAIL' => $template['admin_email']);
            $htmlcontent = replace_variables($template['value'], $replace_arr);
            $indexhtmlpath = makeCorrectFile($destination . '/index.' . Settings::Get('system.index_file_extension'));
            $index_html_handler = fopen($indexhtmlpath, 'w');
            fwrite($index_html_handler, $htmlcontent);
            fclose($index_html_handler);
            if ($logger !== null) {
                $logger->logAction(CRON_ACTION, LOG_NOTICE, 'Creating \'index.' . Settings::Get('system.index_file_extension') . '\' for Customer \'' . $template['customer_login'] . '\' based on template in directory ' . escapeshellarg($indexhtmlpath));
            }
        } else {
            $destination = makeCorrectDir($destination);
            if ($logger !== null) {
                $logger->logAction(CRON_ACTION, LOG_NOTICE, 'Running: cp -a ' . FROXLOR_INSTALL_DIR . '/templates/misc/standardcustomer/* ' . escapeshellarg($destination));
            }
            safe_exec('cp -a ' . FROXLOR_INSTALL_DIR . '/templates/misc/standardcustomer/* ' . escapeshellarg($destination));
        }
    }
    return;
}
 private function updateEvent($user_id, $user_password, $event_id, $desc)
 {
     $response = array();
     $response["success"] = 0;
     $jsonView = new JsonViewer();
     $tryLogin = new TryUserLogin($user_id, $user_password);
     if ($tryLogin->isExists()) {
         //update the events
         $database = new Database();
         $sql = "UPDATE " . EventTable::TableName . " set " . EventTable::Description . "=:desc WHERE " . EventTable::Id . "=:id";
         $smt = $database->prepare($sql);
         $smt->bindValue(":id", $event_id);
         $smt->bindValue(":desc", $desc);
         $status = $smt->execute();
         if ($status) {
             $response["success"] = 1;
             $response["message"] = "Description updated";
         } else {
             $response["error_message"] = "No event with such information found";
         }
     } else {
         $response["error_message"] = "Invalid user login details";
     }
     $jsonView->setContent($response);
     return $jsonView;
 }
Exemple #21
0
 public function initAccount($certrow, $isFroxlorVhost = false)
 {
     // Let's see if we have the private accountkey
     $this->accountKey = $certrow['leprivatekey'];
     if (!$this->accountKey || $this->accountKey == 'unset' || Settings::Get('system.letsencryptca') != 'production') {
         // generate and save new private key for account
         // ---------------------------------------------
         $this->log('Starting new account registration');
         $keys = $this->generateKey();
         // Only store the accountkey in production, in staging always generate a new key
         if (Settings::Get('system.letsencryptca') == 'production') {
             if ($isFroxlorVhost) {
                 Settings::Set('system.lepublickey', $keys['public']);
                 Settings::Set('system.leprivatekey', $keys['private']);
             } else {
                 $upd_stmt = Database::prepare("UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `lepublickey` = :public, `leprivatekey` = :private " . "WHERE `customerid` = :customerid;");
                 Database::pexecute($upd_stmt, array('public' => $keys['public'], 'private' => $keys['private'], 'customerid' => $certrow['customerid']));
             }
         }
         $this->accountKey = $keys['private'];
         $response = $this->postNewReg();
         if ($this->client->getLastCode() != 201) {
             throw new \RuntimeException("Account not initialized, probably due to rate limiting. Whole response: " . json_encode($response));
         }
         $this->license = $this->client->getAgreementURL();
         // Terms of Servce are optional according to ACME specs; if no ToS are presented, no need to update registration
         if (!empty($this->license)) {
             $this->postRegAgreement(parse_url($this->client->getLastLocation(), PHP_URL_PATH));
         }
         $this->log('New account certificate registered');
     } else {
         $this->log('Account already registered. Continuing.');
     }
 }
Exemple #22
0
 public function setSession()
 {
     session_start();
     $page_mode = isset($_POST['page_mode']) ? $_POST['page_mode'] : '';
     if ($page_mode == 'login') {
         $this->password = sha1($_POST['password']);
         $this->userName = $_POST['userName'];
         try {
             $dbh = new Database();
             $data = array(':userName' => $this->userName, ':password' => $this->password);
             $sql = "SELECT * FROM {$this->tableName} WHERE user_name=:userName AND password = :password";
             $sth = $dbh->prepare($sql);
             $sth->execute($data);
             $sth->setFetchMode(PDO::FETCH_ASSOC);
             $row = $sth->fetch();
         } catch (PDOException $e) {
             echo "I'm sorry, Dave. I'm afraid I can't do that.";
             file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
             echo $e->getMessage();
         }
         if (!$row) {
             $this->errorString = 'Clave o nombre de usuario incorrectos';
         } else {
             $_SESSION['userId'] = $row["{$this->tableId}"];
             $_SESSION['userName'] = $row['user_name'];
             header('Location: index.php');
         }
     }
 }
/**
 * Whenever the webserver- / FCGID- or FPM-user gets updated
 * we need to update ftp_groups accordingly
 */
function storeSettingWebserverFcgidFpmUser($fieldname, $fielddata, $newfieldvalue)
{
    if (is_array($fielddata) && isset($fielddata['settinggroup']) && isset($fielddata['varname'])) {
        $update_user = null;
        // webserver
        if ($fielddata['settinggroup'] == 'system' && $fielddata['varname'] == 'httpuser') {
            $update_user = Settings::Get('system.httpuser');
        }
        // fcgid
        if ($fielddata['settinggroup'] == 'system' && $fielddata['varname'] == 'mod_fcgid_httpuser') {
            $update_user = Settings::Get('system.mod_fcgid_httpuser');
        }
        // webserver
        if ($fielddata['settinggroup'] == 'phpfpm' && $fielddata['varname'] == 'vhost_httpuser') {
            $update_user = Settings::Get('phpfpm.vhost_httpuser');
        }
        $returnvalue = storeSettingField($fieldname, $fielddata, $newfieldvalue);
        if ($returnvalue !== false) {
            /**
             * only update if anything changed
             */
            if ($update_user != null && $newfieldvalue != $update_user) {
                $upd_stmt = Database::prepare("UPDATE `" . TABLE_FTP_GROUPS . "` SET `members` = REPLACE(`members`, :olduser, :newuser)");
                Database::pexecute($upd_stmt, array('olduser' => $update_user, 'newuser' => $newfieldvalue));
            }
        }
    }
    return $returnvalue;
}
/**
 * This file is part of the Froxlor project.
 * Copyright (c) 2003-2009 the SysCP Team (see authors).
 * Copyright (c) 2010 the Froxlor Team (see authors).
 *
 * For the full copyright and license information, please view the COPYING
 * file that was distributed with this source code. You can also view the
 * COPYING file online at http://files.froxlor.org/misc/COPYING.txt
 *
 * @copyright  (c) the authors
 * @author     Florian Lippert <*****@*****.**> (2003-2009)
 * @author     Froxlor team <*****@*****.**> (2010-)
 * @license    GPLv2 http://files.froxlor.org/misc/COPYING.txt
 * @package    Functions
 *
 */
function storeSettingDefaultIp($fieldname, $fielddata, $newfieldvalue)
{
    $defaultips_old = Settings::Get('system.defaultip');
    $returnvalue = storeSettingField($fieldname, $fielddata, $newfieldvalue);
    if ($returnvalue !== false && is_array($fielddata) && isset($fielddata['settinggroup']) && $fielddata['settinggroup'] == 'system' && isset($fielddata['varname']) && $fielddata['varname'] == 'defaultip') {
        $customerstddomains_result_stmt = Database::prepare("\n\t\t\tSELECT `standardsubdomain` FROM `" . TABLE_PANEL_CUSTOMERS . "` WHERE `standardsubdomain` <> '0'\n\t\t");
        Database::pexecute($customerstddomains_result_stmt);
        $ids = array();
        while ($customerstddomains_row = $customerstddomains_result_stmt->fetch(PDO::FETCH_ASSOC)) {
            $ids[] = (int) $customerstddomains_row['standardsubdomain'];
        }
        if (count($ids) > 0) {
            $defaultips_new = explode(',', $newfieldvalue);
            // Delete the existing mappings linking to default IPs
            $del_stmt = Database::prepare("\n\t\t\t\t\tDELETE FROM `" . TABLE_DOMAINTOIP . "`\n\t\t\t\t\tWHERE `id_domain` IN (" . implode(', ', $ids) . ")\n\t\t\t\t\tAND `id_ipandports` IN (" . $defaultips_old . ", " . $newfieldvalue . ")\n\t\t\t");
            Database::pexecute($del_stmt);
            // Insert the new mappings
            $ins_stmt = Database::prepare("\n\t\t\t\tINSERT INTO `" . TABLE_DOMAINTOIP . "`\n\t\t\t\tSET `id_domain` = :domainid, `id_ipandports` = :ipandportid\n\t\t\t");
            foreach ($ids as $id) {
                foreach ($defaultips_new as $defaultip_new) {
                    Database::pexecute($ins_stmt, array('domainid' => $id, 'ipandportid' => $defaultip_new));
                }
            }
        }
    }
    return $returnvalue;
}
 /**
  * returns an array with all entries required for all
  * webserver-vhost-configs
  *
  * @return array
  */
 public static function getVhostsToCreate()
 {
     $query = "SELECT `d`.*, `pd`.`domain` AS `parentdomain`, `c`.`loginname`,\n\t\t\t\t`d`.`phpsettingid`, `c`.`adminid`, `c`.`guid`, `c`.`email`,\n\t\t\t\t`c`.`documentroot` AS `customerroot`, `c`.`deactivated`,\n\t\t\t\t`c`.`phpenabled` AS `phpenabled`, `d`.`mod_fcgid_starter`,\n\t\t\t\t`d`.`mod_fcgid_maxrequests`\n\t\t\t\tFROM `" . TABLE_PANEL_DOMAINS . "` `d`\n\n\t\t\t\tLEFT JOIN `" . TABLE_PANEL_CUSTOMERS . "` `c` USING(`customerid`)\n\t\t\t\tLEFT JOIN `" . TABLE_PANEL_DOMAINS . "` `pd` ON (`pd`.`id` = `d`.`parentdomainid`)\n\n\t\t\t\tWHERE `d`.`aliasdomain` IS NULL AND `d`.`email_only` <> '1'\n\t\t\t\tORDER BY `d`.`parentdomainid` DESC, `d`.`iswildcarddomain`, `d`.`domain` ASC;\n\t\t";
     $result_domains_stmt = Database::query($query);
     $domains = array();
     while ($domain = $result_domains_stmt->fetch(PDO::FETCH_ASSOC)) {
         if (!checkDomainIPConfigured($domain['id'])) {
             continue;
         }
         // set whole domain
         $domains[$domain['domain']] = $domain;
         // set empty-defaults for non-ssl
         $domains[$domain['domain']]['ssl'] = '';
         $domains[$domain['domain']]['ssl_cert_file'] = '';
         $domains[$domain['domain']]['ssl_key_file'] = '';
         $domains[$domain['domain']]['ssl_ca_file'] = '';
         $domains[$domain['domain']]['ssl_cert_chainfile'] = '';
         // now, if the domain has an ssl ip/port assigned, get
         // the corresponding information from the db
         if (domainHasSslIpPort($domain['id'])) {
             $ip_stmt = Database::prepare("\n\t\t\t\t\t\tSELECT `di`.`id_domain` , `p`.`ssl`, `p`.`ssl_cert_file`, `p`.`ssl_key_file`, `p`.`ssl_ca_file`, `p`.`ssl_cert_chainfile`\n\t\t\t\t\t\tFROM `" . TABLE_DOMAINTOIP . "` `di`, `" . TABLE_PANEL_IPSANDPORTS . "` `p`\n\t\t\t\t\t\tWHERE `p`.`id` = `di`.`id_ipandports`\n\t\t\t\t\t\tAND `di`.`id_domain` = :domainid\n\t\t\t\t\t\tAND `p`.`ssl` = '1'\n\t\t\t\t\t\t");
             $ssl_ip = Database::pexecute_first($ip_stmt, array('domainid' => $domain['id']));
             // set ssl info for domain
             $domains[$domain['domain']]['ssl'] = '1';
             $domains[$domain['domain']]['ssl_cert_file'] = $ssl_ip['ssl_cert_file'];
             $domains[$domain['domain']]['ssl_key_file'] = $ssl_ip['ssl_key_file'];
             $domains[$domain['domain']]['ssl_ca_file'] = $ssl_ip['ssl_ca_file'];
             $domains[$domain['domain']]['ssl_cert_chainfile'] = $ssl_ip['ssl_cert_chainfile'];
         }
     }
     return $domains;
 }
/**
 * Function validatePasswordLogin
 *
 * compare user password-hash with given user-password
 * and check if they are the same
 * additionally it updates the hash if the system settings changed
 * or if the very old md5() sum is used
 *
 * @param array $userinfo user-data from table
 * @param string $password the password to validate
 * @param string $table either panel_customers or panel_admins
 * @param string $uid user-id-field in $table
 *
 * @return boolean
 */
function validatePasswordLogin($userinfo = null, $password = null, $table = 'panel_customers', $uid = 'customerid')
{
    $systype = 3;
    // SHA256
    if (Settings::Get('system.passwordcryptfunc') !== null) {
        $systype = (int) Settings::Get('system.passwordcryptfunc');
    }
    $pwd_hash = $userinfo['password'];
    $update_hash = false;
    // check for good'ole md5
    if (strlen($pwd_hash) == 32 && ctype_xdigit($pwd_hash)) {
        $pwd_check = md5($password);
        $update_hash = true;
    } else {
        // cut out the salt from the hash
        $pwd_salt = str_replace(substr(strrchr($pwd_hash, "\$"), 1), "", $pwd_hash);
        // create same hash to compare
        $pwd_check = crypt($password, $pwd_salt);
        // check whether the hash needs to be updated
        $hash_type_chk = substr($pwd_hash, 0, 3);
        if ($systype == 1 && $hash_type_chk != '$1$' || $systype == 2 && $hash_type_chk != '$2$' || $systype == 3 && $hash_type_chk != '$5$' || $systype == 4 && $hash_type_chk != '$6$') {
            $update_hash = true;
        }
    }
    if ($pwd_hash == $pwd_check) {
        // check for update of hash
        if ($update_hash) {
            $upd_stmt = Database::prepare("\n\t\t\t\tUPDATE " . $table . " SET `password` = :newpasswd WHERE `" . $uid . "` = :uid\n\t\t\t");
            $params = array('newpasswd' => makeCryptPassword($password), 'uid' => $userinfo[$uid]);
            Database::pexecute($upd_stmt, $params);
        }
        return true;
    }
    return false;
}
 /**
  * read domain-related (or if empty, parentdomain-related) ssl-certificates from the database
  * and (if not empty) set the corresponding array-indices (ssl_cert_file, ssl_key_file,
  * ssl_ca_file and ssl_cert_chainfile). Hence the parameter as reference.
  *
  * @param array $domain domain-array as reference so we can set the corresponding array-indices
  *
  * @return null
  */
 public function setDomainSSLFilesArray(array &$domain = null)
 {
     // check if the domain itself has a certificate defined
     $dom_certs_stmt = Database::prepare("\n\t\t\tSELECT * FROM `" . TABLE_PANEL_DOMAIN_SSL_SETTINGS . "` WHERE `domainid` = :domid\n\t\t");
     $dom_certs = Database::pexecute_first($dom_certs_stmt, array('domid' => $domain['id']));
     if (!is_array($dom_certs) || !isset($dom_certs['ssl_cert_file']) || $dom_certs['ssl_cert_file'] == '') {
         // maybe its parent?
         if ($domain['parentdomainid'] != null) {
             $dom_certs = Database::pexecute_first($dom_certs_stmt, array('domid' => $domain['parentdomainid']));
         }
     }
     // check if it's an array and if the most important field is set
     if (is_array($dom_certs) && isset($dom_certs['ssl_cert_file']) && $dom_certs['ssl_cert_file'] != '') {
         // get destination path
         $sslcertpath = makeCorrectDir(Settings::Get('system.customer_ssl_path'));
         // create path if it does not exist
         if (!file_exists($sslcertpath)) {
             safe_exec('mkdir -p ' . escapeshellarg($sslcertpath));
         }
         // make correct files for the certificates
         $ssl_files = array('ssl_cert_file' => makeCorrectFile($sslcertpath . '/' . $domain['domain'] . '.crt'), 'ssl_key_file' => makeCorrectFile($sslcertpath . '/' . $domain['domain'] . '.key'));
         if (Settings::Get('system.webserver') == 'lighttpd') {
             // put my.crt and my.key together for lighty.
             $dom_certs['ssl_cert_file'] = trim($dom_certs['ssl_cert_file']) . "\n" . trim($dom_certs['ssl_key_file']) . "\n";
             $ssl_files['ssl_key_file'] = '';
         }
         // initialize optional files
         $ssl_files['ssl_ca_file'] = '';
         $ssl_files['ssl_cert_chainfile'] = '';
         // set them if they are != empty
         if ($dom_certs['ssl_ca_file'] != '') {
             $ssl_files['ssl_ca_file'] = makeCorrectFile($sslcertpath . '/' . $domain['domain'] . '_CA.pem');
         }
         if ($dom_certs['ssl_cert_chainfile'] != '') {
             if (Settings::Get('system.webserver') == 'nginx') {
                 // put ca.crt in my.crt, as nginx does not support a separate chain file.
                 $dom_certs['ssl_cert_file'] = trim($dom_certs['ssl_cert_file']) . "\n" . trim($dom_certs['ssl_cert_chainfile']) . "\n";
             } else {
                 $ssl_files['ssl_cert_chainfile'] = makeCorrectFile($sslcertpath . '/' . $domain['domain'] . '_chain.pem');
             }
         }
         // create them on the filesystem
         foreach ($ssl_files as $type => $filename) {
             if ($filename != '') {
                 touch($filename);
                 $_fh = fopen($filename, 'w');
                 fwrite($_fh, $dom_certs[$type]);
                 fclose($_fh);
                 chmod($filename, 0600);
             }
         }
         // override corresponding array values
         $domain['ssl_cert_file'] = $ssl_files['ssl_cert_file'];
         $domain['ssl_key_file'] = $ssl_files['ssl_key_file'];
         $domain['ssl_ca_file'] = $ssl_files['ssl_ca_file'];
         $domain['ssl_cert_chainfile'] = $ssl_files['ssl_cert_chainfile'];
     }
     return;
 }
Exemple #28
0
 /**
  * Store a new message (of the appropriate type) in the message log.
  *
  * @param string    $message
  * @param string    $log_type
  * @param Tree|null $tree
  */
 private static function addLog($message, $log_type, Tree $tree = null)
 {
     global $WT_TREE;
     if (!$tree) {
         $tree = $WT_TREE;
     }
     Database::prepare("INSERT INTO `##log` (log_type, log_message, ip_address, user_id, gedcom_id) VALUES (?, ?, ?, ?, ?)")->execute(array($log_type, $message, WT_CLIENT_IP, Auth::id(), $tree ? $tree->getTreeId() : null));
 }
 public function deleteClient($cliId)
 {
     $objConn = new Database();
     $sql = $objConn->prepare('	DELETE FROM cliente WHERE cli_id = :cliId');
     $sql->bindParam(':cliId', $cliId);
     $this->cliente = $sql->execute();
     return $this->cliente;
 }
Exemple #30
0
 public function testGetRowWrongParam()
 {
     $db = new Database();
     $get_logs_stmt = $db->prepare('SELECT id FROM Users');
     $get_logs_stmt->execute();
     $results = $db->getRow($db);
     $this->assertTrue(empty($results));
 }