Merged in marcoAntonioNina/processmaker/PM-295 (pull request #799)

PM-295 Plugin Enterprise que sea parte del core SOLVED
This commit is contained in:
Julio Cesar Laura Avendaño
2014-09-19 13:59:29 -04:00
76 changed files with 11992 additions and 10 deletions

View File

@@ -0,0 +1,94 @@
<?php
G::LoadClass("system");
G::LoadClass("wsTools");
/*
//Support ProcessMaker 1.8 which doesn't have the CLI class.
define("CLI2", class_exists("CLI"));
if (CLI2) {
CLI::taskName("addon-install");
CLI::taskDescription(<<<EOT
Download and install an addon
EOT
);
CLI::taskRun(run_addon_install);
} else {
pake_desc("install addon");
pake_task("addon-install");
}
*/
//function run_addon_install($args, $opts) {
function run_addon_install($args)
{
try {
if (!extension_loaded("mysql")) {
if (strtoupper(substr(PHP_OS, 0, 3)) === "WIN") {
dl("mysql.dll");
} else {
dl("mysql.so");
}
}
///////
/*
if (!CLI2) {
$args = $opts;
}
*/
$workspace = $args[0];
$storeId = $args[1];
$addonName = $args[2];
if (!defined("SYS_SYS")) {
define("SYS_SYS", $workspace);
}
if (!defined("PATH_DATA_SITE")) {
define("PATH_DATA_SITE", PATH_DATA . "sites/" . SYS_SYS . "/");
}
if (!defined("DB_ADAPTER")) {
define("DB_ADAPTER", $args[3]);
}
///////
//***************** Plugins **************************
G::LoadClass("plugin");
//Here we are loading all plugins registered
//the singleton has a list of enabled plugins
$sSerializedFile = PATH_DATA_SITE . "plugin.singleton";
$oPluginRegistry = &PMPluginRegistry::getSingleton();
if (file_exists($sSerializedFile)) {
$oPluginRegistry->unSerializeInstance(file_get_contents($sSerializedFile));
}
///////
//echo "** Installation starting... (workspace: $workspace, store: $storeId, id: $addonName)\n";
$ws = new workspaceTools($workspace);
$ws->initPropel(false);
require_once PATH_CORE . 'methods' . PATH_SEP . 'enterprise' . PATH_SEP . 'enterprise.php';
require_once PATH_CORE . 'classes' . PATH_SEP . 'model' . PATH_SEP . 'AddonsManagerPeer.php';
$addon = AddonsManagerPeer::retrieveByPK($addonName, $storeId);
if ($addon == null) {
throw new Exception("Id $addonName not found in store $storeId");
}
//echo "Downloading...\n";
$download = $addon->download();
//echo "Installing...\n";
$addon->install();
if ($addon->isCore()) {
$ws = new workspaceTools($workspace);
$ws->initPropel(false);
$addon->setState("install-finish");
} else {
$addon->setState();
}
} catch (Exception $e) {
$addon->setState("error");
//fwrite(STDERR, "\n[ERROR: {$e->getMessage()}]\n");
//fwrite(STDOUT, "\n[ERROR: {$e->getMessage()}]\n");
}
//echo "** Installation finished\n";
}

View File

@@ -0,0 +1,143 @@
<?php
G::LoadClass("system");
G::LoadClass("wsTools");
function ls_dir($dir, $basename = null)
{
$files = array();
//if (substr($dir, -1) != "/")
// $dir .= "/";
if ($basename == null) {
$basename = $dir;
}
foreach (glob("$dir/*") as $filename) {
//var_dump(substr($filename, strlen($basename) + 1));
if (is_dir($filename)) {
$files = array_merge($files, ls_dir($filename, $basename));
} else {
$files[] = substr($filename, strlen($basename) + 1);
}
}
return $files;
}
class Upgrade
{
private $addon = null;
public function __construct($addon)
{
$this->addon = $addon;
}
public function install()
{
//echo "Starting core installation...\n";
$start = microtime(1);
$filename = $this->addon->getDownloadFilename();
$time = microtime(1);
G::LoadThirdParty( 'pear/Archive','Tar');
$archive = new Archive_Tar ($filename);
//printf("Time to open archive: %f\n", microtime(1) - $time);
$time = microtime(1);
$extractDir = dirname($this->addon->getDownloadFilename()) . "/extract";
$backupDir = dirname($this->addon->getDownloadFilename()) . "/backup";
if (file_exists($extractDir)) {
G::rm_dir($extractDir);
}
if (file_exists($backupDir)) {
G::rm_dir($backupDir);
}
if (!is_dir($backupDir)) {
mkdir($backupDir);
}
//printf("Time to remove old directory: %f\n", microtime(1) - $time);
$time = microtime(1);
echo "Extracting files...\n";
$archive->extractModify($extractDir, 'processmaker');
//printf("Time to extract all files: %f\n", microtime(1) - $time);
//$time = microtime(1);
//$files = $archive->listContent();
//printf("Time to get list of contents: %f\n", microtime(1) - $time);
/*$time = microtime(1);
foreach ($files as $fileinfo)
if (basename($fileinfo['filename']) == 'checksum.txt') {
$checksumFile = $archive->extractInString($fileinfo['filename']);
break;
}
printf("Time to get checksum.txt: %f\n", microtime(1) - $time);
*/
$checksumFile = file_get_contents("$extractDir/checksum.txt");
$time = microtime(1);
$checksums = array();
foreach (explode("\n", $checksumFile) as $line) {
$checksums[trim(substr($line, 33))] = substr($line, 0, 32);
}
//printf("Time to assemble list of checksums: %f\n", microtime(1) - $time);
$checksum = array();
$changedFiles = array();
$time = microtime(1);
$files = ls_dir($extractDir);
//printf("Time to list files: %f\n", microtime(1) - $time);
echo "Updating ProcessMaker files...\n";
$time = microtime(1);
$checksumTime = 0;
foreach ($checksums as $filename => $checksum) {
if (is_dir("$extractDir/$filename")) {
print $filename;
continue;
}
$installedFile = PATH_TRUNK . "/$filename";
if (!file_exists($installedFile)) {
$installedMD5 = "";
} else {
$time = microtime(1);
$installedMD5 = md5_file($installedFile);
$checksumTime += microtime(1) - $time;
}
$archiveMD5 = $checksum;
if (strcasecmp($archiveMD5, $installedMD5) != 0) {
$changedFiles[] = $filename;
if (!is_dir(dirname("$backupDir/$filename"))) {
mkdir(dirname("$backupDir/$filename"), 0777, true);
}
if (file_exists($installedFile) && is_file($installedFile)) {
copy($installedFile, "$backupDir/$filename");
}
if (!is_dir(dirname($installedFile))) {
mkdir(dirname($installedFile), 0777, true);
}
if (!copy("$extractDir/$filename", $installedFile)) {
throw new Exception("Could not overwrite '$filename'");
}
}
}
//printf("Time to create all checksums: %f\n", $checksumTime);
//printf("Time to copy files: %f\n", microtime(1) - $time);
printf("Updated %d files\n", count($changedFiles));
printf("Clearing cache...\n");
if (defined('PATH_C')) {
G::rm_dir(PATH_C);
mkdir(PATH_C, 0777, true);
}
$workspaces = System::listWorkspaces();
$count = count($workspaces);
$first = true;
$num = 0;
foreach ($workspaces as $index => $workspace) {
try {
$num += 1;
printf("Upgrading workspaces ($num/$count): {$workspace->name}\n");
$workspace->upgrade($first);
$workspace->close();
$first = false;
} catch (Exception $e) {
printf("Errors upgrading workspace {$workspace->name}: {$e->getMessage()}\n");
//$errors = true;
}
}
//printf("Time to install: %f\n", microtime(1) - $start);
}
}

View File

@@ -0,0 +1,125 @@
<?php
require_once (PATH_PLUGINS . "enterprise" . PATH_SEP . "classes" . PATH_SEP . "class.enterpriseUtils.php");
if (!defined("PM_VERSION")) {
if (file_exists(PATH_METHODS . "login/version-pmos.php")) {
include (PATH_METHODS . "login/version-pmos.php");
} else {
define("PM_VERSION", "2.0.0");
}
}
class enterpriseClass extends PMPlugin
{
public function __construct()
{
set_include_path(PATH_PLUGINS . 'enterprise' . PATH_SEPARATOR . get_include_path());
}
public function getFieldsForPageSetup()
{
return array();
}
//update fields
public function updateFieldsForPageSetup($oData)
{
return array();
}
public function setup()
{
}
public function enterpriseSystemUpdate($data) //$data = $oData
{
require_once ("classes/model/Users.php");
$user = $data;
$criteria = new Criteria("workflow");
//SELECT
$criteria->addSelectColumn(UsersPeer::USR_UID);
//FROM
//WHERE
$criteria->add(UsersPeer::USR_USERNAME, $user->lName); //$user->lPassword
$criteria->add(UsersPeer::USR_ROLE, "PROCESSMAKER_ADMIN");
//query
$rsSQLUSR = UsersPeer::doSelectRS($criteria);
$rsSQLUSR->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$sw = 0;
if (UsersPeer::doCount($criteria) > 0) {
//if ($rsSQLUSR->getRecordCount() > 0) {
$sw = 1;
}
/*
$cnn = Propel::getConnection("workflow");
$stmt = $cnn->createStatement();
$sql = "SELECT USR.USR_UID
FROM USERS AS USR
WHERE USR.USR_USERNAME = '" . $user->lName . "' AND USR.USR_ROLE = 'PROCESSMAKER_ADMIN'";
$rsSQLUSR = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
$sw = 0;
if ($rsSQLUSR->getRecordCount() > 0) {
$sw = 1;
}
*/
if ($sw == 1) {
//Upgrade available
$swUpgrade = 0;
$addonList = AddonsStore::addonList();
$addon = $addonList["addons"];
if (count($addon) > 0) {
$status = array("ready", "upgrade", "available");
$pmVersion = EnterpriseUtils::pmVersion(PM_VERSION);
foreach ($addon as $index => $value) {
if ($addon[$index]["id"] == "processmaker") {
if (version_compare($pmVersion . "", (EnterpriseUtils::pmVersion($addon[$index]["version"])) . "", "<")) {
$swUpgrade = 1;
break;
}
} else {
if (in_array($addon[$index]["status"], $status)) {
$swUpgrade = 1;
break;
}
}
}
}
if ($swUpgrade == 1) {
$_SESSION["__ENTERPRISE_SYSTEM_UPDATE__"] = 1;
}
}
}
public function enterpriseLimitCreateUser()
{
G::LoadClass('serverConfiguration');
$oServerConf = &serverConf::getSingleton();
$infoLicense =$oServerConf->getProperty('LICENSE_INFO');
if (isset($infoLicense[SYS_SYS]['LIMIT_USERS'])) {
$criteria = new Criteria('workflow');
$criteria->add(UsersPeer::USR_STATUS, 'CLOSED', Criteria::NOT_EQUAL);
$count = UsersPeer::doCount($criteria);
if ($count >= $infoLicense[SYS_SYS]['LIMIT_USERS'] ) {
throw new Exception("You can\'t add more users to the System, this reach the limit of allowed users by license that it has installed now");
}
}
}
}
if (!class_exists("pmLicenseManager")) {
require_once (PATH_PLUGINS . 'enterprise/class.pmLicenseManager.php');
}

View File

@@ -0,0 +1,152 @@
<?php
require_once ("classes/model/Configuration.php");
class EnterpriseUtils
{
public static function getInternetConnection()
{
$data = array();
$criteria = new Criteria("workflow");
$criteria->addSelectColumn(ConfigurationPeer::CFG_VALUE);
$criteria->add(ConfigurationPeer::CFG_UID, "EE");
$criteria->add(ConfigurationPeer::OBJ_UID, "enterpriseConfiguration");
$rsCriteria = ConfigurationPeer::doSelectRS($criteria);
if ($rsCriteria->next()) {
$row = $rsCriteria->getRow();
$data = unserialize($row[0]);
}
return ((isset($data["internetConnection"]))? intval($data["internetConnection"]) : 1);
}
public static function checkConnectivity($url)
{
try {
if (extension_loaded('curl')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_VERBOSE, true);
//Apply proxy settings
$sysConf = System::getSystemConfiguration();
if (isset($sysConf['proxy_host'])) {
if ($sysConf['proxy_host'] != '') {
curl_setopt($ch, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : ''));
if ($sysConf['proxy_port'] != '') {
curl_setopt($ch, CURLOPT_PROXYPORT, $sysConf['proxy_port']);
}
if ($sysConf['proxy_user'] != '') {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
}
}
$content = curl_exec($ch);
$headers = curl_getinfo($ch);
$content = substr($content, $headers['header_size']);
if ($headers['http_code'] === 200) {
return $content;
}
} else {
throw (new Exception('The "CURL" extension not loaded.'));
}
} catch (Exception $e) {
//Log the error
}
return false;
}
public static function checkFolderPermissions($folderPath, $result)
{
$directorio = opendir($folderPath);
if (is_writable ($folderPath)) {
while (false !== ($archivo = readdir($directorio)) && $result == true) {
if ($archivo != '.') {
if ($archivo != '..') {
if (is_dir("$folderPath/$archivo")) {
$result = self::checkFolderPermissions($folderPath."/".$archivo, $result);
} else {
if (!is_writable ($folderPath."/".$archivo)) {
$result = false;
return $result;
}
}
}
}
}
} else {
$result = false;
return $result;
}
closedir($directorio);
return $result;
}
public static function pmVersion($version)
{
if (preg_match("/^([\d\.]+).*$/", $version, $matches)) {
$version = $matches[1];
}
return $version;
}
public static function getUrlServerName()
{
$s = (empty($_SERVER["HTTPS"]))? null : (($_SERVER["HTTPS"] == "on")? "s" : null);
$p = strtolower($_SERVER["SERVER_PROTOCOL"]);
$protocol = substr($p, 0, strpos($p, "/")) . $s;
$port = ($_SERVER["SERVER_PORT"] == "80")? null : ":" . $_SERVER["SERVER_PORT"];
return ($protocol . "://" . $_SERVER["SERVER_NAME"] . $port);
}
public static function getUrl()
{
return (self::getUrlServerName() . $_SERVER["REQUEST_URI"]);
}
public static function getUrlPartSetup()
{
$setup = "setup/main";
if (substr(SYS_SKIN, 0, 2) == "ux" && SYS_SKIN != "uxs") {
$setup = "setup/main_init";
}
return $setup;
}
public static function skinIsUx()
{
$sw = 0;
if (substr(SYS_SKIN, 0, 2) == "ux" && SYS_SKIN != "uxs") {
$sw = 1;
}
return $sw;
}
}

View File

@@ -0,0 +1,507 @@
<?php
/**
* Project: Distrubution License Class
* File: class.license.app.php
*
* Copyright (C) 2005 Oliver Lillie
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @link http://www.buggedcom.co.uk/
* @link http://www.phpclasses.org/browse/package/2298.html
* @author Oliver Lillie, buggedcom <publicmail at buggedcom dot co dot uk>
* @history---------------------------------------------
* see CHANGELOG
*/
class license_application extends padl
{
/**
* The number of allowed differences between the $_SERVER vars and the vars
* stored in the key
*
* @var number
*/
public $_ALLOWED_SERVER_DIFS = 0;
/**
* The number of allowed differences between the $ip vars in the key and the ip
* vars collected from the server
*
* @var number
*/
public $_ALLOWED_IP_DIFS = 0;
/**
* the path of the license key file, remember this would be relative to the
* include path of the class file.
*/
public $_LICENSE_PATH;
/**
* Constructor
*
* @access public
* @param $use_mcrypt boolean Determines if mcrypt encryption is used or not (defaults to true,
* however if mcrypt is not available, it is set to false)
* @param $use_time boolean Sets if time binding should be used in the key (defaults to true)
* @param $use_server boolean Sets if server binding should be used in the key (defaults to true)
* @param $allow_local boolean Sets if server binding is in use then localhost servers are valid (defaults to false)
* */
public function license_application($license_path = 'license.dat', $use_mcrypt = true, $use_time = true, $use_server = true, $allow_local = false, $challenge = false)
{
# check to see if the class has been secured
unset($_SESSION['__sw__']);
if ($challenge) {
$_SESSION['__sw__'] = true;
}
$this->_check_secure();
$this->_LICENSE_PATH = $license_path;
$this->init($use_mcrypt, $use_time, $use_server, $allow_local);
if ($this->USE_SERVER) {
$this->_MAC = $this->_get_mac_address();
}
}
/**
* set_server_vars
*
* to protect against spoofing you should copy the $_SERVER vars into a
* seperate array right at the first line of your script so parameters can't
* be changed in unencoded php files. This doesn't have to be set. If it is
* not set then the $_SERVER is copied when _get_server_info (private) function
* is called.
*
* @access public
* @param $array array The copied $_SERVER array
* */
public function set_server_vars($array)
{
# check to see if the class has been secured
$this->_check_secure();
$this->_SERVER_VARS = $array;
# some of the ip data is dependant on the $_SERVER vars, so update them
# after the vars have been set
$this->_IPS = $this->_get_ip_address();
# update the server info
$this->_SERVER_INFO = $this->_get_server_info();
}
/**
* _get_os_var
*
* gets various vars depending on the os type
*
* @access private
* @return string various values
* */
public function _get_os_var($var_name, $os)
{
$var_name = strtolower($var_name);
# switch between the os's
switch ($os) {
# not sure if the string is correct for FreeBSD
# not tested
case 'freebsd':
# not sure if the string is correct for NetBSD
# not tested
case 'netbsd':
# not sure if the string is correct for Solaris
# not tested
case 'solaris':
# not sure if the string is correct for SunOS
# not tested
case 'sunos':
# darwin is mac os x
# tested only on the client os
case 'darwin':
# switch the var name
switch ($var_name) {
case 'conf':
$var = '/sbin/ifconfig';
break;
case 'mac':
$var = 'ether';
break;
case 'ip':
$var = 'inet ';
break;
}
break;
# linux variation
# tested on server
case 'linux':
# switch the var name
switch ($var_name) {
case 'conf':
$var = '/sbin/ifconfig';
break;
case 'mac':
$var = 'HWaddr';
break;
case 'ip':
$var = 'inet addr:';
break;
}
break;
}
return $var;
}
/**
* _get_config
*
* gets the server config file and returns it. tested on Linux,
* Darwin (Mac OS X), and Win XP. It may work with others as some other
* os's have similar ifconfigs to Darwin but they haven't been tested
*
* @access private
* @return string config file data
* */
public function _get_config()
{
# check to see if the class has been secured
$this->_check_secure();
if (ini_get('safe_mode')) {
# returns invalid because server is in safe mode thus not allowing
# sbin reads but will still allow it to open. a bit weird that one.
return 'SAFE_MODE';
}
# if anyone has any clues for windows environments
# or other server types let me know
$os = strtolower(PHP_OS);
if (substr($os, 0, 3) == 'win') {
# this windows version works on xp running apache
# based server. it has not been tested with anything
# else, however it should work with NT, and 2000 also
# execute the ipconfig
@exec('ipconfig/all', $lines);
# count number of lines, if none returned return MAC_404
# thanks go to Gert-Rainer Bitterlich <bitterlich -at- ima-dresden -dot- de>
if (count($lines) == 0) {
return 'ERROR_OPEN';
}
# $path the lines together
$conf = implode($this->_LINEBREAK, $lines);
} else {
# get the conf file name
$os_file = $this->_get_os_var('conf', $os);
# open the ipconfig
$fp = @popen($os_file, "rb");
# returns invalid, cannot open ifconfig
if (!$fp) {
return 'ERROR_OPEN';
}
# read the config
$conf = @fread($fp, 4096);
@pclose($fp);
}
return $conf;
}
/**
* _get_ip_address
*
* Used to get the MAC address of the host server. It works with Linux,
* Darwin (Mac OS X), and Win XP. It may work with others as some other
* os's have similar ifconfigs to Darwin but they haven't been tested
*
* @access private
* @return array IP Address(s) if found (Note one machine may have more than one ip)
* @return string ERROR_OPEN means config can't be found and thus not opened
* @return string IP_404 means ip adress doesn't exist in the config file and can't be found in the $_SERVER
* @return string SAFE_MODE means server is in safe mode so config can't be read
* */
public function _get_ip_address()
{
$ips = array();
# get the cofig file
$conf = $this->_get_config();
# if the conf has returned and error return it
if ($conf != 'SAFE_MODE' && $conf != 'ERROR_OPEN') {
# if anyone has any clues for windows environments
# or other server types let me know
$os = strtolower(PHP_OS);
if (substr($os, 0, 3) == 'win') {
# anyone any clues on win ip's
} else {
# explode the conf into seperate lines for searching
$lines = explode($this->_LINEBREAK, $conf);
# get the ip delim
$ip_delim = $this->_get_os_var('ip', $os);
# ip pregmatch
$num = "(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])";
# seperate the lines
foreach ($lines as $key => $line) {
# check for the ip signature in the line
if (!preg_match("/^$num\\.$num\\.$num\\.$num$/", $line) && strpos($line, $ip_delim)) {
# seperate out the ip
$ip = substr($line, strpos($line, $ip_delim) + strlen($ip_delim));
$ip = trim(substr($ip, 0, strpos($ip, " ")));
# add the ip to the collection
if (!isset($ips[$ip])) {
$ips[$ip] = $ip;
}
}
}
}
}
# if the conf has returned nothing
# attempt to use the $_SERVER data
if (isset($this->_SERVER_VARS['SERVER_NAME'])) {
$ip = gethostbyname($this->_SERVER_VARS['SERVER_NAME']);
if (!isset($ips[$ip])) {
$ips[$ip] = $ip;
}
}
if (isset($this->_SERVER_VARS['SERVER_ADDR'])) {
$name = gethostbyaddr($this->_SERVER_VARS['SERVER_ADDR']);
$ip = gethostbyname($name);
if (!isset($ips[$ip])) {
$ips[$ip] = $ip;
}
# if the $_SERVER addr is not the same as the returned ip include it aswell
if ($ip != $this->_SERVER_VARS['SERVER_ADDR']) {
if (!isset($ips[$this->_SERVER_VARS['SERVER_ADDR']])) {
$ips[$this->_SERVER_VARS['SERVER_ADDR']] = $this->_SERVER_VARS['SERVER_ADDR'];
}
}
}
# count return ips and return if found
if (count($ips) > 0) {
return $ips;
}
# failed to find an ip check for conf error or return 404
if ($conf == 'SAFE_MODE' || $conf == 'ERROR_OPEN') {
return $conf;
}
return 'IP_404';
}
/**
* _get_mac_address
*
* Used to get the MAC address of the host server. It works with Linux,
* Darwin (Mac OS X), and Win XP. It may work with others as some other
* os's have similar ifconfigs to Darwin but they haven't been tested
*
* @access private
* @return string Mac address if found
* @return string ERROR_OPEN means config can't be found and thus not opened
* @return string MAC_404 means mac adress doesn't exist in the config file
* @return string SAFE_MODE means server is in safe mode so config can't be read
* */
public function _get_mac_address()
{
# open the config file
$conf = $this->_get_config();
# if anyone has any clues for windows environments
# or other server types let me know
$os = strtolower(PHP_OS);
if (substr($os, 0, 3) == 'win') {
# explode the conf into lines to search for the mac
$lines = explode($this->_LINEBREAK, $conf);
# seperate the lines for analysis
foreach ($lines as $key => $line) {
# check for the mac signature in the line
# originally the check was checking for the existence of string 'physical address'
# however Gert-Rainer Bitterlich pointed out this was for english language
# based servers only. preg_match updated by Gert-Rainer Bitterlich. Thanks
if (preg_match("/([0-9a-f][0-9a-f][-:]){5}([0-9a-f][0-9a-f])/i", $line)) {
$trimmed_line = trim($line);
# take of the mac addres and return
return trim(substr($trimmed_line, strrpos($trimmed_line, " ")));
}
}
} else {
# get the mac delim
$mac_delim = $this->_get_os_var('mac', $os);
# get the pos of the os_var to look for
$pos = strpos($conf, $mac_delim);
if ($pos) {
# seperate out the mac address
$str1 = trim(substr($conf, ($pos + strlen($mac_delim))));
return trim(substr($str1, 0, strpos($str1, "\n")));
}
}
# failed to find the mac address
return 'MAC_404';
}
/**
* _get_server_info
*
* used to generate the server binds when server binding is needed.
*
* @access private
* @return array server bindings
* @return boolean false means that the number of bindings failed to
* meet the required number
* */
public function _get_server_info()
{
if (empty($this->_SERVER_VARS)) {
$this->set_server_vars($_SERVER);
}
# get the server specific uris
$a = array();
if (isset($this->_SERVER_VARS['SERVER_ADDR']) && (!strrpos($this->_SERVER_VARS['SERVER_ADDR'], '127.0.0.1') || $this->ALLOW_LOCAL)) {
$a['SERVER_ADDR'] = $this->_SERVER_VARS['SERVER_ADDR'];
}
# corrected by Gert-Rainer Bitterlich <bitterlich -at- ima-dresden -dot- de>, Thanks
if (isset($this->_SERVER_VARS['HTTP_HOST']) && (!strrpos($this->_SERVER_VARS['HTTP_HOST'], '127.0.0.1') || $this->ALLOW_LOCAL)) {
$a['HTTP_HOST'] = $this->_SERVER_VARS['HTTP_HOST'];
}
if (isset($this->_SERVER_VARS['SERVER_NAME'])) {
$a['SERVER_NAME'] = $this->_SERVER_VARS['SERVER_NAME'];
}
if (isset($this->_SERVER_VARS['PATH_TRANSLATED'])) {
$a['PATH_TRANSLATED'] = substr($this->_SERVER_VARS['PATH_TRANSLATED'], 0, strrpos($this->_SERVER_VARS['PATH_TRANSLATED'], '/'));
} elseif (isset($this->_SERVER_VARS['SCRIPT_FILENAME'])) {
$a['SCRIPT_FILENAME'] = substr($this->_SERVER_VARS['SCRIPT_FILENAME'], 0, strrpos($this->_SERVER_VARS['SCRIPT_FILENAME'], '/'));
}
if (isset($_SERVER['SCRIPT_URI'])) {
$a['SCRIPT_URI'] = substr($this->_SERVER_VARS['SCRIPT_URI'], 0, strrpos($this->_SERVER_VARS['SCRIPT_URI'], '/'));
}
# if the number of different uris is less than the required amount,
# fail the request
if (count($a) < $this->REQUIRED_URIS) {
return 'SERVER_FAILED';
}
return $a;
}
/**
* validate
*
* validates the server key and returns a data array.
*
* @access public
* @return array Main object in array is 'RESULT', it contains the result
* of the validation.
* OK - key is valid
* CORRUPT - key has been tampered with
* TMINUS - the key is being used before the valid start date
* EXPIRED - the key has expired
* ILLEGAL - the key is not on the same server the license was registered to
* ILLEGAL_LOCAL - the key is not allowed to be installed on a local machine
* INVALID - the the encryption key used to encrypt the key differs or the key is not complete
* EMPTY - the the key is empty
* 404 - the the key is missing
* */
public function validate($str = false, $dialhome = false, $dialhost = "", $dialpath = "", $dialport = "80")
{
# check to see if the class has been secured
$this->_check_secure();
# get the dat string
$dat_str = (!$str) ? @file_get_contents($this->_LICENSE_PATH) : $str;
if (strlen($dat_str) > 0) {
# decrypt the data
$DATA = $this->_unwrap_license($dat_str);
if (is_array($DATA)) {
# missing / incorrect id therefore it has been tampered with
if ($DATA['ID'] != md5($this->ID1)) {
$DATA['RESULT'] = 'CORRUPT';
}
if ($this->USE_TIME) {
# the license is being used before it's official start
if ($DATA['DATE']['START'] > time() + $this->START_DIF) {
$DATA['RESULT'] = 'TMINUS';
}
# the license has expired
if ($DATA['DATE']['END'] - time() < 0 && $DATA['DATE']['SPAN'] != 'NEVER' && $DATA['DATE']['SPAN'] != '~') {
$DATA['RESULT'] = 'EXPIRED';
}
$DATA['DATE']['HUMAN']['START'] = date($this->DATE_STRING, $DATA['DATE']['START']);
if (($DATA['DATE']['END'] == "") || ($DATA['DATE']['END'] == "NEVER")) {
$DATA['DATE']['HUMAN']['END'] = "PERPETUAL";
} else {
$DATA['DATE']['HUMAN']['END'] = date($this->DATE_STRING, $DATA['DATE']['END']);
}
}
if ($this->USE_SERVER) {
$mac = $DATA['SERVER']['MAC'] == $this->_MAC;
$path = count(array_diff($this->_SERVER_INFO, $DATA['SERVER']['PATH'])) <= $this->_ALLOWED_SERVER_DIFS;
$domain = $this->_compare_domain_ip($DATA['SERVER']['DOMAIN'], $this->_IPS);
$ip = count(array_diff($this->_IPS, $DATA['SERVER']['IP'])) <= $this->_ALLOWED_IP_DIFS;
# the server details
if (!$mac || !$path || !$domain || !$ip) {
$DATA['RESULT'] = 'ILLEGAL';
}
# check if local
$local = $this->ALLOW_LOCAL && (in_array('127.0.0.1', $DATA['SERVER']['IP']) || $DATA['PATH']['SERVER_ADDR'] == '127.0.0.1' || $DATA['PATH']['HTTP_HOST'] == '127.0.0.1');
if (!$local) {
$DATA['RESULT'] = 'ILLEGAL_LOCAL';
}
}
# passed all current test so license is ok
if (!isset($DATA['RESULT'])) {
# dial to home server if required
if ($dialhome) {
# create the details to send to the home server
$stuff_to_send = array();
$stuff_to_send['LICENSE_DATA'] = $DATA;
$stuff_to_send['LICENSE_DATA']['KEY'] = md5($dat_str);
# dial home
$DATA['RESULT'] = $this->_call_home($stuff_to_send, $dialhost, $dialpath, $dialport);
} else {
# result is ok all test passed, license is legal
$DATA['RESULT'] = 'OK';
}
}
/*
*/
# data is returned for use
return $DATA;
} else {
# the are two reason that mean a invalid return
# 1 - the other hash key is different
# 2 - the key has been tampered with
return array('RESULT' => 'INVALID');
}
}
# returns empty because there is nothing in the dat_string
return array('RESULT' => 'EMPTY');
}
/**
* _call_home
*
* calls the dial home server (your server) andvalidates the clients license
* with the info in the mysql db
*
* @access private
* @param $data array Array that contains the info to be validated
* @param $dialhost string Host name of the server to be contacted
* @param $dialpath string Path of the script for the data to be sent to
* @param $dialport number Port Number to send the data through
* @return string Returns: the encrypted server validation result from the dial home call
* : SOCKET_FAILED => socket failed to connect to the server
* */
public function _call_home($data, $dialhost, $dialpath, $dialport)
{
print "_call_home($data, $dialhost, $dialpath, $dialport)";
# post the data home
$data = $this->_post_data($dialhost, $dialpath, $data, $dialport);
return (empty($data['RESULT'])) ? 'SOCKET_FAILED' : $data['RESULT'];
}
}

View File

@@ -0,0 +1,704 @@
<?php
/**
* Project: Distrubution License Class
* File: class.license.lib.php
*
* Copyright (C) 2005 Oliver Lillie
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @link http://www.buggedcom.co.uk/
* @link http://www.phpclasses.org/browse/package/2298.html
* @author Oliver Lillie, buggedcom <publicmail at buggedcom dot co dot uk>
* @version 0.1
* @history---------------------------------------------
* see CHANGELOG
*/
class padl
{
/**
* hash key 1 used to encrypt the generate key data.
* hash key 2 used to encrypt the request data
* hash key 3 used to encrypt the dial home data
* NOTE1 : there are three different hash keys for the three different operations
* NOTE2 : these hash key's are for use by both mcrypt and alternate cryptions
* and although mcrypts keys are typically short they should be kept long
* for the sake of the other functions
*
* @var string
* @var string
* @var string
*/
public $HASH_KEY1 = 'YmUzYWM2sNGU24NbA363zA7IDSDFGDFGB5aVi35BDFGQ3YNO36ycDFGAATq4sYmSFVDFGDFGps7XDYEzGDDw96OnMW3kjCFJ7M+UV2kHe1WTTEcM09UMHHT';
public $HASH_KEY2 = '80dSbqylf4Cu5e5OYdAoAVkzpRDWAt7J1Vp27sYDU52ZBJprdRL1KE0il8KQXuKCK3sdA51P9w8U60wohX2gdmBu7uVhjxbS8g4y874Ht8L12W54Q6T4R4a';
public $HASH_KEY3 = 'ant9pbc3OK28Li36Mi4d3fsWJ4tQSN4a9Z2qa8W66qR7ctFbljsOc9J4wa2Bh6j8KB3vbEXB18i6gfbE0yHS0ZXQCceIlG7jwzDmN7YT06mVwcM9z0vy62T';
/**
* You may not want to use mcrypt even if your system has it installed
* make this false to use a regular encryption method
*
* @var boolean
*/
public $USE_MCRYPT = true;
/**
* The algorythm to be used by mcrypt
*
* @var string
*/
public $ALGORITHM = 'blowfish';
/**
* use time binding vars inited.
*/
public $USE_TIME;
/**
* time checking start period difference allowance ie if the user has slightly different time
* setting on their server make an allowance for the diff period. carefull to not make it too
* much otherwise they could just reset their server to a time period before the license expires.
*
* @var number (seconds)
*/
public $START_DIF = 129600;
/**
* id 1 used to validate license keys
* id 2 used to validate license key requests
* id 2 used to validate dial home data
*
* @var string
* @var string
* @var string
*/
# id to check for to validate source
public $ID1 = 'nSpkAHRiFfM2hE588eB';
public $ID2 = 'NWCy0s0JpGubCVKlkkK';
public $ID3 = 'G95ZP2uS782cFey9x5A';
/**
* begining and end strings
*
* @var strings
*/
public $BEGIN1 = 'BEGIN LICENSE KEY';
public $END1 = 'END LICENSE KEY';
/**
* wrap key settings
*
* @var number
* @var string
* @var string
*/
public $_WRAPTO = 80;
public $_PAD = "-";
/**
* init the linebreak var
*/
public $_LINEBREAK;
/**
* dial home return query deliminators
*
* @var string
* @var string
*/
public $BEGIN2 = '_DATA{';
public $END2 = '}DATA_';
/**
* init the key data array.
*
* @var array
*/
public $_DATA = array();
/**
* use server binding vars inited.
*/
public $USE_SERVER;
public $_SERV;
public $_MAC;
public $ALLOW_LOCAL;
public $_SERVER_INFO = array();
/**
* this is the number of required server stats for the key generation to be successfull
* if the server can't produce this number of details then the key fails to be generated
* you can set it to however many you wish, the max is 5
*
* @var number
*/
public $REQUIRED_URIS = 2;
/**
* the date string for human readable format
*
* @var string
*/
public $DATE_STRING = 'M/d/Y H:i:s';
/**
* Constructor
*
* @access private
* */
public function padl()
{
# check to see if the class has been secured
$this->_check_secure();
}
/**
* init
*
* init the license class
*
* @access public
* @param $use_mcrypt boolean Determines if mcrypt encryption is used or not (defaults to true,
* however if mcrypt is not available, it is set to false)
* @param $use_time boolean Sets if time binding should be used in the key (defaults to true)
* @param $use_server boolean Sets if server binding should be used in the key (defaults to true)
* @param $allow_local boolean Sets if server binding is in use then localhost servers are valid (defaults to false)
* */
public function init($use_mcrypt = true, $use_time = true, $use_server = true, $allow_local = false, $challenge = false)
{
# check to see if the class has been secured
if (!$challenge) {
$this->_check_secure();
}
$this->USE_MCRYPT = ($use_mcrypt && function_exists('mcrypt_generic'));
$this->USE_TIME = $use_time;
$this->ALLOW_LOCAL = $allow_local;
$this->USE_SERVER = $use_server;
$this->_LINEBREAK = $this->_get_os_linebreak();
}
/**
* _get_os_linebreak
*
* get's the os linebreak
*
* @access private
* @param $true_val boolean If the true value is needed for writing files, make true
* defaults to false
* @return string Returns the os linebreak
* */
public function _get_os_linebreak($true_val = false)
{
$os = strtolower(PHP_OS);
switch ($os) {
# not sure if the string is correct for FreeBSD
# not tested
case 'freebsd':
# not sure if the string is correct for NetBSD
# not tested
case 'netbsd':
# not sure if the string is correct for Solaris
# not tested
case 'solaris':
# not sure if the string is correct for SunOS
# not tested
case 'sunos':
# linux variation
# tested on server
case 'linux':
$nl = "\n";
break;
# darwin is mac os x
# tested only on the client os
case 'darwin':
# note os x has \r line returns however it appears that the ifcofig
# file used to source much data uses \n. let me know if this is
# just my setup and i will attempt to fix.
if ($true_val) {
$nl = "\r";
} else {
$nl = "\n";
}
break;
# defaults to a win system format;
default:
$nl = "\r\n";
}
return $nl;
}
public function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
// Proxy settings
$sysConf = System::getSystemConfiguration();
if ($sysConf['proxy_host'] != '') {
if (!is_array($params['http'])) {
$params['http'] = array();
}
$params['http']['request_fulluri'] = true;
$params['http']['proxy'] = 'tcp://' . $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '');
if ($sysConf['proxy_user'] != '') {
if (!isset($params['http']['header'])) {
$params['http']['header'] = '';
}
$params['http']['header'] .= 'Proxy-Authorization: Basic ' . base64_encode($sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
}
}
$ctx = stream_context_create($params);
//G::pr($ctx);
$fp = @fopen($url, 'rb', false, $ctx);
//G::pr($fp);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
/**
* _post_data
*
* Posts data to and recieves data from dial home server. Returned info
* contains the dial home validation result
*
* @access private
* @param $host string Host name of the server to be contacted
* @param $path string Path of the script for the data to be sent to
* @param $query_array array Array that contains the license key info to be validated
* @param $port number Port Number to send the data through
* @return array Result of the dialhome validation
* @return string - SOCKET_FAILED will be returned if it was not possible to open a socket to the home server
* */
public function _post_data($host, $path, $query_array, $port = 80)
{
# generate the post query info
$query = 'POSTDATA=' . $this->_encrypt($query_array, 'HOMEKEY');
$query .= '&MCRYPT=' . $this->USE_MCRYPT;
$query .= '&TYPE=' . $query_array['DATA']['TYPE'];
$query .= '&PLAN=' . $query_array['DATA']['PLAN'];
//G::pr($path);
//G::pr($query);
# init the return string
//$return = '';
//$return=$this->do_post_request($host.$path, $query);
# separate out the data using the delims
//$leftpos = strpos($return, $this->BEGIN2)+strlen($this->BEGIN2);
//$rightpos = strpos($return, $this->END2)-$leftpos;
# decrypt and return the data
//return $this->_decrypt(substr($return, $leftpos, $rightpos), 'HOMEKEY');
//die;
# generate the post headers
$post = "POST $path HTTP/1.1\r\n";
$post .= "Host: $host\r\n";
$post .= "Content-type: application/x-www-form-urlencoded\r\n";
$post .= "Content-length: " . strlen($query) . "\r\n";
$post .= "Connection: close\r\n";
$post .= "\r\n";
$post .= $query;
# open a socket
$ip = gethostbyname($host);
if ($ip == $host) {
$ip = rtrim(`/usr/bin/dig $host A +short | /usr/bin/tail -1`);
}
$header = @fsockopen($ip, $port);
//print "fsockopen($host, $port)";
//G::pr($header);
if (!$header) {
# if the socket fails return failed
return array('RESULT' => 'SOCKET_FAILED');
}
@fputs($header, $post);
//G::pr($post);
# read the returned data
while (!@feof($header)) {
$return .= @ fgets($header, 1024);
}
fclose($header);
# separate out the data using the delims
$leftpos = strpos($return, $this->BEGIN2) + strlen($this->BEGIN2);
$rightpos = strpos($return, $this->END2) - $leftpos;
#trace($return);
# decrypt and return the data
return $this->_decrypt(substr($return, $leftpos, $rightpos), 'HOMEKEY');
}
/**
* _compare_domain_ip
*
* uses the supplied domain in the key and runs a check against the collected
* ip addresses. If there are matching ips it returns true as the domain
* and ip address match up
*
* @access private
* @return boolean
* */
public function _compare_domain_ip($domain, $ips = false)
{
# if no ips are supplied get the ip addresses for the server
if (!$ips) {
$ips = $this->_get_ip_address();
}
# get the domain ip list
$domain_ips = gethostbynamel($domain);
# loop through the collected ip's searching for matches against the domain ips
if (is_array($domain_ips) && count($domain_ips) > 0) {
foreach ($domain_ips as $ip) {
if (in_array($ip, $ips)) {
return true;
}
}
}
return false;
}
/**
* _pad
*
* pad out the begin and end seperators
*
* @access private
* @param $str string The string to be padded
* @return string Returns the padded string
* */
public function _pad($str)
{
$str_len = strlen($str);
$spaces = ($this->_WRAPTO - $str_len) / 2;
$str1 = '';
for ($i = 0; $i < $spaces; $i++) {
$str1 = $str1 . $this->_PAD;
}
if ($spaces / 2 != round($spaces / 2)) {
$str = substr($str1, 0, strlen($str1) - 1) . $str;
} else {
$str = $str1 . $str;
}
$str = $str . $str1;
return $str;
}
/**
* _get_key
*
* gets the hash key for the current encryption
*
* @access private
* @param $key_type string The license key type being produced
* @return string Returns the hash key
* */
public function _get_key($key_type)
{
switch ($key_type) {
case 'KEY':
return $this->HASH_KEY1;
case 'REQUESTKEY':
return $this->HASH_KEY2;
case 'HOMEKEY':
return $this->HASH_KEY3;
default:
}
}
/**
* _get_begin
*
* gets the begining license key seperator text
*
* @access private
* @param $key_type string The license key type being produced
* @return string Returns the begining string
* */
public function _get_begin($key_type)
{
switch ($key_type) {
case 'KEY':
return $this->BEGIN1;
case 'REQUESTKEY':
return $this->BEGIN2;
case 'HOMEKEY':
return '';
}
}
/**
* _get_end
*
* gets the ending license key seperator text
*
* @access private
* @param $key_type string The license key type being produced
* @return string Returns the ending string
* */
public function _get_end($key_type)
{
switch ($key_type) {
case 'KEY':
return $this->END1;
case 'REQUESTKEY':
return $this->_END2;
case 'HOMEKEY':
return '';
}
}
/**
* _generate_random_string
*
* generates a random string
*
* @access private
* @param $length number The length of the random string
* @param $seeds string The string to pluck the characters from
* @return string Returns random string
* */
public function _generate_random_string($length = 10, $seeds = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890123456789')
{
$str = '';
$seeds_count = strlen($seeds);
list($usec, $sec) = explode(' ', microtime());
$seed = (float) $sec + ((float) $usec * 100000);
mt_srand($seed);
for ($i = 0; $length > $i; $i++) {
$str .= $seeds{mt_rand(0, $seeds_count - 1)};
}
return $str;
}
/**
* _encrypt
*
* encrypts the key
*
* @access private
* @param $src_array array The data array that contains the key data
* @return string Returns the encrypted string
* */
public function _encrypt($src_array, $key_type = 'KEY')
{
# check to see if the class has been secured
$this->_check_secure();
$rand_add_on = $this->_generate_random_string(3);
# get the key
$key = $this->_get_key($key_type);
$key = $rand_add_on . $key;
# check to see if mycrypt exists
if ($this->USE_MCRYPT) {
# openup mcrypt
$td = mcrypt_module_open($this->ALGORITHM, '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
# process the key
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
# init mcrypt
mcrypt_generic_init($td, $key, $iv);
# encrypt data
# double base64 gets makes all the characters alpha numeric
# and gets rig of the special characters
$crypt = mcrypt_generic($td, serialize($src_array));
# shutdown mcrypt
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
} else {
# if mcrypt doesn't exist use regular encryption method
# init the vars
$crypt = '';
$str = serialize($src_array);
# loop through the str and encrypt it
for ($i = 1; $i <= strlen($str); $i++) {
$char = substr($str, $i - 1, 1);
$keychar = substr($key, ($i % strlen($key)) - 1, 1);
$char = chr(ord($char) + ord($keychar));
$crypt .= $char;
}
}
# return the key
return $rand_add_on . base64_encode(base64_encode(trim($crypt)));
}
/**
* _decrypt
*
* decrypts the key
*
* @access private
* @param $enc_string string The key string that contains the data
* @return array Returns decrypted array
* */
public function _decrypt($str, $key_type = 'KEY')
{
# check to see if the class has been secured
$this->_check_secure();
$rand_add_on = substr($str, 0, 3);
$str = base64_decode(base64_decode(substr($str, 3)));
# get the key
$key = $rand_add_on . $this->_get_key($key_type);
# check to see if mycrypt exists
if ($this->USE_MCRYPT) {
# openup mcrypt
$td = mcrypt_module_open($this->ALGORITHM, '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
# process the key
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
# init mcrypt
mcrypt_generic_init($td, $key, $iv);
# decrypt the data and return
$decrypt = mdecrypt_generic($td, $str);
# shutdown mcrypt
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
} else {
# if mcrypt doesn't exist use regular decryption method
# init the decrypt vars
$decrypt = '';
# loop through the text and decode the string
for ($i = 1; $i <= strlen($str); $i++) {
$char = substr($str, $i - 1, 1);
$keychar = substr($key, ($i % strlen($key)) - 1, 1);
$char = chr(ord($char) - ord($keychar));
$decrypt .= $char;
}
}
# return the key
return unserialize($decrypt);
}
/**
* _wrap_license
*
* wraps up the license key in a nice little package
*
* @access private
* @param $src_array array The array that needs to be turned into a license str
* @param $key_type string The type of key to be wrapped (KEY=license key, REQUESTKEY=license request key)
* @return string Returns encrypted and formatted license key
* */
public function _wrap_license($src_array, $key_type = 'KEY')
{
# sort the variables
$begin = $this->_pad($this->_get_begin($key_type));
$end = $this->_pad($this->_get_end($key_type));
# encrypt the data
$str = $this->_encrypt($src_array, $key_type);
# return the wrap
return $begin . $this->_LINEBREAK . wordwrap($str, $this->_WRAPTO, $this->_LINEBREAK, 1) . $this->_LINEBREAK . $end;
}
/**
* _unwrap_license
*
* unwraps license key back into it's data array
*
* @access private
* @param $enc_str string The encrypted license key string that needs to be decrypted
* @param $key_type string The type of key to be unwrapped (KEY=license key, REQUESTKEY=license request key)
* @return array Returns license data array
* */
public function _unwrap_license($enc_str, $key_type = 'KEY')
{
# sort the variables
$begin = $this->_pad($this->_get_begin($key_type));
$end = $this->_pad($this->_get_end($key_type));
# get string without seperators
$str = trim(str_replace(array($begin, $end, "\r", "\n", "\t"), '', $enc_str));
# decrypt and return the key
return $this->_decrypt($str, $key_type);
}
/**
* make_secure
*
* deletes all class values to prevent re-writing of a key;
*
* @access public
* */
public function make_secure($report = false)
{
if ($report) {
define('_PADL_REPORT_ABUSE_', true);
}
# walkthrough and delete the class vars
foreach (array_keys(get_object_vars($this)) as $value) {
unset($this->$value);
}
# define that class is secure
define('_PADL_SECURE_', 1);
}
/**
* _check_secure
*
* checks to see if the class has been made secure
*
* @access private
* */
public function _check_secure()
{
if (!isset($_SESSION['__sw__'])) {
# check to see if padl has been made secure
if (defined('_PADL_SECURE_')) {
# if(defined('_PADL_REPORT_ABUSE_')) $this->_post_data($this->_HOST, $this->_PATH, array());
# trigger the error because user has attempted to access secured functions
# after the call has been made to 'make_secure'
trigger_error("<br /><br /><span style='color: #F00;font-weight: bold;'>The PHP Application Distribution License System (PADL) has been made secure.<br />You have attempted to use functions that have been protected and this has terminated your script.<br /><br /></span>", E_USER_ERROR);
exit;
}
}
}
}
/**
* custom functions to aid in debugging
*
* @var mixed
*/
function trace()
{
$message = '';
for ($i = 0; $i < func_num_args(); $i++) {
if (is_array(func_get_arg($i))) {
trace_r(func_get_arg($i));
} else {
$message .= func_get_arg($i);
}
if ($i <= func_num_args() - 2) {
$message.=' : ';
}
}
echo "<br><b>\r\r" . $message . "\r\r</b>";
}
function trace_r($array = "array is empty")
{
echo "<pre><b>\r\r";
print_r($array);
echo "\r\r</b></pre>";
}

View File

@@ -83,7 +83,7 @@ class PMPlugin
public function registerMenu($menuId, $menuFilename)
{
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$sMenuFilename = PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $menuFilename;
$sMenuFilename = ($this->sClassName == 'enterprisePlugin') ? PATH_CORE . 'methods' . PATH_SEP . 'enterprise' . PATH_SEP . $menuFilename : PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $menuFilename;
$oPluginRegistry->registerMenu($this->sNamespace, $menuId, $sMenuFilename);
}

View File

@@ -32,6 +32,7 @@
require_once 'class.plugin.php';
class pluginDetail
{
public $sNamespace;
@@ -294,17 +295,19 @@ class PMPluginRegistry
*/
public function disablePlugin ($sNamespace, $eventPlugin = 1)
{
//require_once PATH_CORE . 'methods' . PATH_SEP . 'enterprise' . PATH_SEP . 'enterprise.php';
$sw = false;
//G::pr($this->_aPluginDetails);die;
foreach ($this->_aPluginDetails as $namespace => $detail) {
if ($namespace == $sNamespace) {
//G::pr($detail);die;
unset( $this->_aPluginDetails[$sNamespace] );
if ($eventPlugin == 1) {
$plugin = new $detail->sClassName( $detail->sNamespace, $detail->sFilename );
$this->_aPlugins[$detail->sNamespace] = $plugin;
if (method_exists( $plugin, "disable" )) {
$plugin->disable();
//$plugin = new $detail->sClassName( $detail->sNamespace, $detail->sFilename );
$this->_aPlugins[$detail->sNamespace] = $detail;
if (method_exists( $detail, "disable" )) {
$detail->disable();
}
}

View File

@@ -0,0 +1,502 @@
<?php
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.enterpriseUtils.php';
/**
* class.pmLicenseManager.php
*
*/
class pmLicenseManager
{
private static $instance = null;
public function __construct()
{
G::LoadClass('serverConfiguration');
$oServerConf = &serverConf::getSingleton();
$oServerConf->setProperty('LOGIN_NO_WS', true);
//to do: this files probably needs to be in core, since they are GPL2
//include_once (PATH_PLUGINS . 'enterprise' . PATH_SEP . 'classes' . PATH_SEP . 'class.license.lib.php');
//include_once (PATH_PLUGINS . 'enterprise' . PATH_SEP . 'classes' . PATH_SEP . 'class.license.app.php');
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.license.lib.php';
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.license.app.php';
//searching .dat files in workspace folder
$server_array = $_SERVER;
$licfile = glob(PATH_DATA_SITE . "*.dat");
if (count($licfile) > 0 && is_file($licfile[0])) {
$oServerConf->setProperty('ACTIVE_LICENSE', array(SYS_SYS => ""));
}
$activeLicenseSetting = $oServerConf->getProperty('ACTIVE_LICENSE');
if ((isset($activeLicenseSetting[SYS_SYS])) && (file_exists($activeLicenseSetting[SYS_SYS]))) {
$licenseFile = $activeLicenseSetting[SYS_SYS];
} else {
$activeLicense = $this->getActiveLicense();
$oServerConf->setProperty('ACTIVE_LICENSE', array(SYS_SYS => $activeLicense ['LICENSE_PATH']));
$licenseFile = $activeLicense['LICENSE_PATH'];
}
$application = new license_application($licenseFile, false, true, false, true);
$application->set_server_vars($server_array);
$application->DATE_STRING = 'Y-m-d H:i:s';
$results = $application->validate();
$application->make_secure();
$validStatus = array(
'OK',
'EXPIRED',
'TMINUS'
);
$this->result = $results['RESULT'];
if (in_array($this->result, $validStatus)) {
$this->serial="3ptta7Xko2prrptrZnSd356aqmPXvMrayNPFj6CLdaR1pWtrW6qPw9jV0OHjxrDGu8LVxtmSm9nP5kR23HRpdZWccpeui+bKkK<6B>DoqCt2Kqgpq6Vg37s";
$info['FIRST_NAME'] = $results['DATA']['FIRST_NAME'];
$info['LAST_NAME'] = $results['DATA']['LAST_NAME'];
$info['DOMAIN_WORKSPACE'] = $results['DATA']['DOMAIN_WORKSPACE'];
$this->date = $results ['DATE'];
$this->info = $info;
$this->type = $results ['DATA']['TYPE'];
$this->plan = isset($results ['DATA']['PLAN'])?$results ['DATA']['PLAN']:"";
$this->id = $results ['ID'];
$this->expireIn = $this->getExpireIn ();
$this->features = $this->result!='TMINUS'?isset($results ['DATA']['CUSTOMER_PLUGIN'])?$results ['DATA']['CUSTOMER_PLUGIN']:$this->getActiveFeatures():array();
$this->status = $this->getCurrentLicenseStatus ();
if (isset ( $results ['LIC'] )) {
$resultsRegister = $results['LIC'];
$this->server = $results['LIC']['SRV'];
$this->file = $results['LIC']['FILE'];
$this->licenseSerial = (isset($results['LIC']['SERIAL'])) ? $results['LIC']['SERIAL'] : '';
$this->supportStartDate = (isset($results['DATA']['SUPPORT_START_DATE'])) ? $results['DATA']['SUPPORT_START_DATE'] : '';
$this->supportEndDate = (isset($results['DATA']['SUPPORT_END_DATE'])) ? $results['DATA']['SUPPORT_END_DATE'] : '';
$this->supportStartDate = date("Y-m-d H:i:s", strtotime($this->supportStartDate));
$this->supportEndDate = date("Y-m-d H:i:s", strtotime($this->supportEndDate));
G::LoadClass( "configuration" );
$conf = new Configurations();
if ( defined('SYS_SYS') && $conf->exists("ENVIRONMENT_SETTINGS")) {
$this->supportStartDate = $conf->getSystemDate($this->supportStartDate);
$this->supportEndDate = $conf->getSystemDate($this->supportEndDate);
} else {
$this->supportStartDate = G::getformatedDate($this->supportStartDate, 'M d, yyyy', SYS_LANG);
$this->supportEndDate = G::getformatedDate($this->supportEndDate, 'M d, yyyy', SYS_LANG);
}
} else {
$resultsRegister=array();
$resultsRegister['ID']=$results ['DATA'] ['DOMAIN_WORKSPACE'];
$this->server = null;
$this->file = null;
}
$resultsRegister['date'] = $results ['DATE'];
$resultsRegister['info'] = $info;
$resultsRegister['type'] = $results ['DATA'] ['TYPE'];
if ($oServerConf->getProperty ( 'LICENSE_INFO')) {
$licInfoA = $oServerConf->getProperty ( 'LICENSE_INFO');
} else {
$licInfoA = array();
}
$licInfoA[SYS_SYS]=$resultsRegister;
$oServerConf->setProperty ( 'LICENSE_INFO', $licInfoA );
}
$this->activateFeatures ();
}
public function &getSingleton()
{
if (self::$instance == null) {
self::$instance = new pmLicenseManager ();
}
return self::$instance;
}
public function serializeInstance()
{
return serialize ( self::$instance );
}
public function activateFeatures()
{
//Get a list of all Enterprise plugins and active/inactive them
if (file_exists ( PATH_PLUGINS . 'enterprise/data/default' )) {
if ($this->result=="OK") {
//Disable
if (file_exists ( PATH_PLUGINS . 'enterprise/data/data' )) {
$oPluginRegistry = & PMPluginRegistry::getSingleton ();
$aPlugins = unserialize ( trim ( file_get_contents ( PATH_PLUGINS . 'enterprise/data/data' ) ) );
foreach ($aPlugins as $aPlugin) {
$sClassName = substr ( $aPlugin ['sFilename'], 0, strpos ( $aPlugin ['sFilename'], '-' ) );
require_once PATH_PLUGINS . $sClassName . '.php';
$oDetails = $oPluginRegistry->getPluginDetails ( $sClassName . '.php' );
$oPluginRegistry->disablePlugin ( $oDetails->sNamespace );
file_put_contents ( PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance () );
}
unlink(PATH_PLUGINS . 'enterprise/data/data');
}
//Enable
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$aPlugins = unserialize(trim(file_get_contents(PATH_PLUGINS . "enterprise/data/default")));
foreach ($aPlugins as $aPlugin) {
if ($aPlugin ["bActive"]) {
$sClassName = substr($aPlugin["sFilename"], 0, strpos($aPlugin["sFilename"], "-"));
require_once (PATH_PLUGINS . $sClassName . ".php");
$oDetails = $oPluginRegistry->getPluginDetails($sClassName . ".php");
$oPluginRegistry->enablePlugin($oDetails->sNamespace);
file_put_contents ( PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance () );
}
}
if (file_exists(PATH_DATA_SITE . "ee")) {
$aPlugins = unserialize ( trim ( file_get_contents ( PATH_DATA_SITE.'ee' ) ) );
$aDenied=array();
foreach ($aPlugins as $aPlugin) {
$sClassName = substr ( $aPlugin ['sFilename'], 0, strpos ( $aPlugin ['sFilename'], '-' ) );
if (!(in_array($sClassName,$this->features))) {
if (file_exists(PATH_PLUGINS . $sClassName . '.php')) {
require_once PATH_PLUGINS . $sClassName . '.php';
$oDetails = $oPluginRegistry->getPluginDetails ( $sClassName . '.php' );
$oPluginRegistry->disablePlugin ( $oDetails->sNamespace );
file_put_contents ( PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance () );
$aDenied[]=$oDetails->sNamespace;
}
}
}
if (!(empty($aDenied))) {
if ((SYS_COLLECTION=="enterprise")&&(SYS_TARGET=="pluginsList")) {
G::SendMessageText("The following plugins were restricted due to your enterprise license: ".implode(", ",$aDenied),"INFO");
}
}
}
} else {
//Disable
$oPluginRegistry = & PMPluginRegistry::getSingleton ();
$aPlugins = unserialize ( trim ( file_get_contents ( PATH_PLUGINS . 'enterprise/data/default' ) ) );
foreach ($aPlugins as $aPlugin) {
$sClassName = substr ( $aPlugin ['sFilename'], 0, strpos ( $aPlugin ['sFilename'], '-' ) );
//To avoid self disable
if (($sClassName != "pmLicenseManager") && ($sClassName != "pmTrial") && ($sClassName != "enterprise")) {
require_once PATH_PLUGINS . $sClassName . '.php';
$oDetails = $oPluginRegistry->getPluginDetails ( $sClassName . '.php' );
$oPluginRegistry->disablePlugin ( $oDetails->sNamespace );
} else {
//Enable default and required plugins
require_once PATH_PLUGINS . $sClassName . '.php';
$oDetails = $oPluginRegistry->getPluginDetails ( $sClassName . '.php' );
$oPluginRegistry->enablePlugin ( $oDetails->sNamespace );
}
}
if (file_exists(PATH_DATA_SITE.'ee')) {
$aPlugins = unserialize ( trim ( file_get_contents ( PATH_DATA_SITE.'ee' ) ) );
foreach ($aPlugins as $aPlugin) {
$sClassName = substr ( $aPlugin ['sFilename'], 0, strpos ( $aPlugin ['sFilename'], '-' ) );
if ( strlen($sClassName) > 0 ) {
if (!class_exists($sClassName)) {
require_once PATH_PLUGINS . $sClassName . '.php';
}
$oDetails = $oPluginRegistry->getPluginDetails ( $sClassName . '.php' );
if ($oDetails) {
$oPluginRegistry->disablePlugin ( $oDetails->sNamespace );
}
}
}
}
file_put_contents ( PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance () );
}
}
}
public function getCurrentLicenseStatus()
{
$result = array ();
switch ($this->result) {
case 'OK':
$result ['result'] = 'ok';
$result ['message'] = "";
break;
case 'TMINUS':
$result ['result'] = 'tminus';
$startDateA=explode(" ",$this->date['HUMAN']['START']);
$result ['message'] = "License will be active on ".$startDateA[0];
break;
case 'EXPIRED':
$result ['result'] = 'expired';
$result ['message'] = "License Expired";
break;
case 'ILLEGAL':
$result ['result'] = 'illegal';
$result ['message'] = "Illegal License";
break;
case 'ILLEGAL_LOCAL':
$result ['result'] = 'illegal';
$result ['message'] = "Illegal Local License";
break;
case 'INVALID':
$result ['result'] = 'invalid';
$result ['message'] = "Invalid License";
break;
case 'EMPTY':
$result ['result'] = 'empty';
$result ['message'] = "Empty License";
if (defined ( 'write_error' )) {
$result ['message'] = "Write error" . $result ['message'];
}
break;
default:
break;
}
return $result;
}
public function unSerializeInstance($serialized)
{
if (self::$instance == null) {
self::$instance = new PMPluginRegistry ();
}
$instance = unserialize ( $serialized );
self::$instance = $instance;
}
public function getExpireIn()
{
$status = $this->getCurrentLicenseStatus ();
$expireIn = 0;
if ($status ['result'] == 'ok') {
if ($this->date ['END']!="NEVER") {
$expireIn = ceil ( ($this->date ['END'] - time ()) / 60 / 60 / 24 );
} else {
$expireIn = "NEVER";
}
}
return $expireIn;
}
public function getLicenseInfo()
{
$validStatus = array (
'ok',
'expired'
);
$status = $this->getCurrentLicenseStatus ();
$infoText = "";
if (in_array ( $status ['result'], $validStatus )) {
$start = explode ( " ", $this->date ['HUMAN'] ['START'] );
$end = explode ( " ", $this->date ['HUMAN'] ['END'] );
$infoText .= "<b>" . "Issued to" . ":</b> " . $this->info ['FIRST_NAME'] . " " . $this->info ['LAST_NAME'] . "<br>";
$infoText .= "<b>" . G::LoadTranslation('ID_WORKSPACE') .":</b> " . $this->info ['DOMAIN_WORKSPACE'] . "<br>";
$infoText .= "<i>" . G::LoadTranslation('ID_VALID_FROM') . " " . $start [0] . " " . G::LoadTranslation('ID_TO') . " " . $end [0] . "</i>";
}
if ($status ['message'] != "") {
$infoText .= "&nbsp;<font color=red><b>- " . $status ['message'] . "</b></font>";
}
$info ['infoText'] = $infoText;
$info ['infoLabel'] = $status ['message'];
return $info;
}
public function getExpireInLabel()
{
$linkText = null;
if ($this->getExpireIn() != "NEVER" && ((int)$this->getExpireIn() <= 30) && ((int)$this->getExpireIn() > 0)) {
$infoO = $this->getLicenseInfo();
$infoText = $infoO['infoText'];
$js = (EnterpriseUtils::skinIsUx() == 1)? "Ext.MessageBox.show({title: '', msg: '$infoText', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.INFO});" : "msgBox('$infoText');";
$linkText = $linkText . "<a href=\"javascript:;\" onclick=\"$js return (false);\"><span style=\"color: red;\">" . G::LoadTranslation('ID_EXPIRES_IN') ." " . $this->getExpireIn () . " " . G::LoadTranslation('ID_DAYS') ."</span></a>";
} else {
if ($this->getExpireIn() != "NEVER" && (int)$this->getExpireIn() <= 0) {
$infoO = $this->getLicenseInfo();
$infoText = $infoO['infoText'];
$infoLabel = $infoO['infoLabel'];
$js = (EnterpriseUtils::skinIsUx() == 1)? "Ext.MessageBox.show({title: '', msg: '$infoText', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.INFO});" : "msgBox('$infoText');";
$linkText = $linkText . "<a href=\"javascript:;\" onclick=\"$js return (false);\"><span style=\"color: red;\">" . $infoLabel . "</span></a>";
}
}
if (class_exists('pmTrialPlugin')) {
$linkText = $linkText . "<a href='/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN . "/pmTrial/services/buyNow?n=true" . "'> <img align='absmiddle' src='/plugin/pmLicenseManager/btn_buy_now.gif' border='0' /></a>";
}
if (isset($_SESSION["__ENTERPRISE_SYSTEM_UPDATE__"]) && $_SESSION["__ENTERPRISE_SYSTEM_UPDATE__"] == 1) {
$aOnclick = "onclick=\"this.href='" . EnterpriseUtils::getUrlServerName() . "/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN . "/setup/main?s=PMENTERPRISE';\"";
if (EnterpriseUtils::skinIsUx() == 1) {
$aOnclick = "onclick=\"Ext.ComponentMgr.get('mainTabPanel').setActiveTab('pm-option-setup'); Ext.ComponentMgr.get('pm-option-setup').setLocation(Ext.ComponentMgr.get('pm-option-setup').defaultSrc + 's=PMENTERPRISE', true); return (false);\"";
}
$linkText = $linkText . (($linkText != null)? " | " : null) . "<a href=\"javascript:;\" $aOnclick style=\"color: #008000;\">" . G::LoadTranslation('ID_UPGRADE_SYSTEM') . "</a>";
}
$linkText = ($linkText != null)? $linkText . ((EnterpriseUtils::skinIsUx() == 1)? null : " |") : null;
return ($linkText);
}
public function validateLicense($path)
{
$application = new license_application ( $path, false, true, false, true, true );
$results = $application->validate ( false, false, "", "", "80", true );
if ($results ['RESULT'] != 'OK') {
return true;
} else {
return false;
}
}
public function installLicense($path, $redirect = true)
{
$application = new license_application ( $path, false, true, false, true, true );
$results = $application->validate ( false, false, "", "", "80", true );
//if the result is ok then it is saved into DB
$res = $results ['RESULT'];
if (( $res != 'OK') && ($res != 'EXPIRED' ) && ($res != 'TMINUS') ) {
G::SendTemporalMessage ( 'ID_ISNT_LICENSE', 'tmp-info', 'labels' );
return false;
} else {
G::LoadClass ( 'serverConfiguration' );
$oServerConf = & serverConf::getSingleton ();
$oServerConf->setProperty ( 'ACTIVE_LICENSE',array(SYS_SYS => $path));
$this->saveDataLicense( $results, $path, $redirect );
if ($redirect) {
G::Header ( 'location: licenseManagerList' );
} else {
return true;
}
}
}
/*
get Active License
*/
public function getActiveLicense()
{
//Autoinstall license if exists in data folder and move to license folder
$dirData = PATH_DATA;
$dirDataSite = PATH_DATA_SITE;
$dirDataSiteLic = PATH_DATA_SITE . "licenses";
G::verifyPath($dirDataSiteLic, true);
$licfile = glob($dirDataSite . "*.dat");
if (count($licfile) > 0 && is_file($licfile[0])) {
$file = $licfile[0];
@copy($file, $dirDataSiteLic . PATH_SEP . basename($file));
$this->installLicense($dirDataSiteLic . PATH_SEP . basename($file), false);
@unlink($file);
}
//get license from database, table LICENSE_MANAGER
try {
$aRow = array();
require_once ("classes/model/LicenseManager.php");
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(LicenseManagerPeer::LICENSE_USER);
$oCriteria->addSelectColumn(LicenseManagerPeer::LICENSE_START);
$oCriteria->addSelectColumn(LicenseManagerPeer::LICENSE_PATH);
$oCriteria->addSelectColumn(LicenseManagerPeer::LICENSE_DATA);
$oCriteria->add(LicenseManagerPeer::LICENSE_STATUS, 'ACTIVE');
$oDataset = LicenseManagerPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
} catch (Exception $e) {
G::pr ($e);
}
return $aRow;
}
public function lookForStatusLicense()
{
require_once ("classes/model/LicenseManager.php");
//obtening info in a row that has ACTIVE status
$oCtia = new Criteria ( 'workflow' );
$oCtia->add ( LicenseManagerPeer::LICENSE_STATUS, 'ACTIVE' );
$oDataset = LicenseManagerPeer::doSelectRS ( $oCtia );
$oDataset->next ();
$aRow = $oDataset->getRow ();
$oCtiaA = new Criteria ( 'workflow' );
$oCtiaA->add ( LicenseManagerPeer::LICENSE_UID, $aRow [0] );
$oCtiaB = new Criteria ( 'workflow' );
$oCtiaB->add ( LicenseManagerPeer::LICENSE_STATUS, 'INACTIVE' );
BasePeer::doUpdate ( $oCtiaA, $oCtiaB, Propel::getConnection ( 'workflow' ) );
return 'ACTIVE';
}
public function saveDataLicense($results, $path)
{
try {
//getting info about file
$LicenseUid = G::generateUniqueID ();
$LicenseUser = $results ['DATA'] ['FIRST_NAME'] . ' ' . $results ['DATA'] ['LAST_NAME'];
$LicenseStart = $results ['DATE'] ['START'];
$LicenseEnd = $results ['DATE'] ['END'];
$LicenseSpan = $results ['DATE'] ['SPAN'];
$LicenseStatus = $this->lookForStatusLicense(); //we're looking for a status ACTIVE
//getting the content from file
$handle = fopen ( $path, "r" );
$contents = fread ( $handle, filesize ( $path ) );
fclose ( $handle );
$LicenseData = $contents;
$LicensePath = $path;
$LicenseWorkspace = isset($results['DATA']['DOMAIN_WORKSPACE']) ? $results['DATA']['DOMAIN_WORKSPACE'] : '';
$LicenseType = $results['DATA']['TYPE'];
require_once ("classes/model/LicenseManager.php");
//if exists the row in the database propel will update it, otherwise will insert.
$tr = LicenseManagerPeer::retrieveByPK ( $LicenseUid );
if (! (is_object ( $tr ) && get_class ( $tr ) == 'LicenseManager')) {
$tr = new LicenseManager ();
}
$tr->setLicenseUid ( $LicenseUid );
$tr->setLicenseUser ( $LicenseUser );
$tr->setLicenseStart ( $LicenseStart );
$tr->setLicenseEnd ( $LicenseEnd );
$tr->setLicenseSpan ( $LicenseSpan );
$tr->setLicenseStatus ( $LicenseStatus );
$tr->setLicenseData ( $LicenseData );
$tr->setLicensePath ( $LicensePath );
$tr->setLicenseWorkspace ( $LicenseWorkspace );
$tr->setLicenseType ( $LicenseType );
$res = $tr->save ();
} catch ( Exception $e ) {
G::pr($e);
}
}
public function getResultQry($sNameTable, $sfield, $sCondition)
{
try {
require_once ("classes/model/LicenseManager.php");
$oCriteria = new Criteria ( 'workflow' );
$oCriteria->addSelectColumn ( LicenseManagerPeer::LICENSE_USER );
$oCriteria->addSelectColumn ( LicenseManagerPeer::LICENSE_START );
$oCriteria->addSelectColumn ( LicenseManagerPeer::LICENSE_PATH );
$oCriteria->addSelectColumn ( LicenseManagerPeer::LICENSE_DATA );
$oCriteria->add ( LicenseManagerPeer::LICENSE_STATUS, 'ACTIVE' );
$oDataset = LicenseManagerPeer::doSelectRS ( $oCriteria );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$aRow = $oDataset->getRow ();
} catch (Exception $e) {
G::pr ( $e );
$aRow = array ();
}
return $aRow;
}
public function getActiveFeatures()
{
return unserialize(G::decrypt($this->serial, file_get_contents(PATH_PLUGINS . 'enterprise/data/default')));
}
}

View File

@@ -0,0 +1,454 @@
<?php
require_once 'classes/model/om/BaseAddonsManager.php';
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.enterpriseUtils.php';
if (!defined("BUFSIZE")) {
define("BUFSIZE", 16384);
}
/**
* Skeleton subclass for representing a row from the 'UPGRADE_MANAGER' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package classes.model
*/
class AddonsManager extends BaseAddonsManager
{
/**
* Returns the download filename
*
* @return string download filename
*/
public function getDownloadFilename()
{
$filename = $this->getAddonDownloadFilename();
if (!isset($filename) || empty($filename)) {
$filename = "download.tar";
}
$dir = $this->getDownloadDirectory();
return "$dir/$filename";
}
public function getDownloadDirectory()
{
$dir = PATH_DATA . "upgrade/{$this->getStoreId()}_{$this->getAddonName()}";
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
return ($dir);
}
/**
* Check to see if the download file exists and has the right data.
*
* @return mixed true if exists and md5 is good, false otherwise. Returns null
* if file exists but md5 for the download is not available.
*/
public function checkDownload()
{
$filename = $this->getDownloadFilename();
if (!file_exists($filename)) {
return false;
}
$download_md5 = $this->getAddonDownloadMd5();
if ($download_md5 == null) {
return null;
}
return (strcasecmp(md5_file($filename), $download_md5) == 0);
}
/**
* Returns if this addon is of type 'plugin'
*
* @return bool true if is of type 'plugin', false otherwise
*/
public function isPlugin()
{
return ($this->getAddonType() == 'plugin');
}
/**
* Returns if this addon is of type 'core'
*
* @return bool true if is of type 'core', false otherwise
*/
public function isCore()
{
return ($this->getAddonType() == 'core');
}
/**
* Returns if this addon is installed or not-
*
* @return bool true if installed, false otherwise
*/
public function isInstalled()
{
if ($this->isCore()) {
return ($this->getAddonVersion() == $this->getInstalledVersion());
} elseif ($this->isPlugin()) {
return (file_exists(PATH_PLUGINS . "{$this->getAddonName()}.php"));
} else {
throw new Exception("Addon type '{$this->getAddonType()}' unsupported");
}
}
/**
* Returns if this addon is enabled or not.
*
* @return bool true if enabled, false otherwise
*/
public function isEnabled()
{
if ($this->isCore()) {
return $this->isInstalled();
} elseif ($this->isPlugin()) {
if (!$this->isInstalled()) {
return false;
}
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$status = $oPluginRegistry->getStatusPlugin($this->getAddonName());
return (strcmp($status, "enabled") == 0);
} else {
throw new Exception("Addon type '{$this->getAddonType()}' unsupported");
}
}
public function setEnabled($enable = true)
{
if (!$this->isInstalled() || !$this->isPlugin()) {
return false;
}
if ($this->getAddonName() == "enterprise") {
return false;
}
$oPluginRegistry = &PMPluginRegistry::getSingleton();
require_once (PATH_PLUGINS . $this->getAddonName() . ".php");
if ($enable) {
//$oDetails = $oPluginRegistry->getPluginDetails($this->getAddonName());
//$oPluginRegistry->enablePlugin($oDetails->sNamespace);
//require_once (PATH_PLUGINS . $this->getAddonName() . ".php"); //ok
$oPluginRegistry->enablePlugin($this->getAddonName());
} else {
//$oDetails = $oPluginRegistry->getPluginDetails($this->getAddonName());
//$oPluginRegistry->disablePlugin($oDetails->sNamespace);
$oPluginRegistry->disablePlugin($this->getAddonName());
}
//$oPluginRegistry->setupPlugins();
file_put_contents(PATH_DATA_SITE . "plugin.singleton", $oPluginRegistry->serializeInstance());
return true;
}
/**
* Returns the currently installed version of this addon.
*
* @return string the installed version or an empty string otherwise.
*/
public function getInstalledVersion()
{
if ($this->isCore()) {
G::LoadClass("system");
return (EnterpriseUtils::pmVersion(System::getVersion()));
} else {
if ($this->isPlugin()) {
if (!$this->isInstalled()) {
return (null);
}
///////
if (file_exists(PATH_PLUGINS . $this->getAddonName() . PATH_SEP . "VERSION")) {
return (trim(file_get_contents(PATH_PLUGINS . $this->getAddonName() . PATH_SEP . "VERSION")));
}
///////
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$details = $oPluginRegistry->getPluginDetails($this->getAddonName() . ".php");
$v = (!($details == null))? $details->iVersion : null;
return ($v);
} else {
if ($this->getAddonType() == "core") {
throw new Exception("Addon type \"" . $this->getAddonType() . "\" unsupported");
}
}
}
}
public function refresh()
{
/* Update our information from the db */
$rs = $this->getPeer()->doSelectRS($this->buildPkeyCriteria());
$rs->first();
$this->hydrate($rs);
}
/**
* Download this addon from the download url.
*
* @return bool true on success, false otherwise.
*/
public function download()
{
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php';
$this->setState("download");
///////
$aux = explode("?", $this->getAddonDownloadUrl());
$url = $aux[0];
$var = explode("&", $aux[1]);
///////
$boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
$data = null;
for ($i = 0; $i <= count($var) - 1; $i++) {
$aux = explode("=", $var[$i]);
$data = $data . "--$boundary\n";
$data = $data . "Content-Disposition: form-data; name=\"" . $aux[0] . "\"\n\n" . $aux[1] . "\n";
}
if (count($var) > 0) {
$data = $data . "--$boundary\n";
}
///////
$licenseManager = &pmLicenseManager::getSingleton();
$activeLicense = $licenseManager->getActiveLicense();
$data = $data . "Content-Disposition: form-data; name=\"licenseFile\"; filename=\"" . $licenseManager->file . "\"\n";
$data = $data . "Content-Type: text/plain\n";
//$data = $data . "Content-Type: image/jpeg\n";
$data = $data . "Content-Transfer-Encoding: binary\n\n";
$data = $data . file_get_contents($activeLicense["LICENSE_PATH"]) . "\n";
$data = $data . "--$boundary\n";
///////
$option = array(
"http" => array(
"method" => "POST",
//"method" => "post",
"header" => "Content-Type: multipart/form-data; boundary=" . $boundary,
"content" => $data
)
);
// Proxy settings
$sysConf = System::getSystemConfiguration();
if ($sysConf['proxy_host'] != '') {
if (!is_array($option['http'])) {
$option['http'] = array();
}
$option['http']['request_fulluri'] = true;
$option['http']['proxy'] = 'tcp://' . $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '');
if ($sysConf['proxy_user'] != '') {
if (!isset($option['http']['header'])) {
$option['http']['header'] = '';
}
$option['http']['header'] .= 'Proxy-Authorization: Basic ' . base64_encode($sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
}
}
$context = stream_context_create($option);
///////
$handle = fopen($url, "rb", false, $context);
if ($handle === false) {
throw new Exception("Could not open download url.");
}
$this->setAddonDownloadFilename(null);
//Try to get the download size and filename (ok if it fails)
$meta = stream_get_meta_data($handle);
$totalSize = 0;
if ($meta["wrapper_type"] == "http") {
foreach ($meta["wrapper_data"] as $info) {
$info = explode(":", $info);
if (strcasecmp(trim($info[0]), "Content-Length") == 0) {
$totalSize = intval(trim($info[1]));
}
if (strcasecmp(trim($info[0]), "Content-Disposition") == 0) {
foreach (explode(";", $info[1]) as $params) {
$params = explode("=", $params);
if (count($params) <= 1) {
continue;
}
if (strcasecmp(trim($params[0]), "filename") == 0) {
$this->setAddonDownloadFilename(trim($params[1], "\" "));
}
}
}
}
}
//Save the filename
$this->save();
$units = array(" B", " KB", " MB", " GB", " TB");
//if ($totalSize) {
// $bytes = $totalSize;
// for ($i = 0; $bytes >= 1024 && $i < 4; $i++) $bytes /= 1024;
// printf("Download size: %.2f%s\n", round($bytes, 2), $units[$i]);
//}
$downloadFile = $this->getDownloadFilename();
$file = @fopen($downloadFile, "wb");
if ($file === false) {
throw new Exception("Could not open destination file.");
}
$start = microtime(true);
while (!feof($handle)) {
$this->refresh();
/* Check if download was cancelled from the ui */
if ($this->getAddonState() == "cancel" || $this->getAddonState() == "") {
$this->setState();
break;
}
/* Update the database information to show we are still alive */
$this->setState("download");
$data = fread($handle, BUFSIZE);
//TODO: We should use these values for something
$elapsed = microtime(true) - $start;
$position = ftell($handle);
$rate = $position / $elapsed;
if ($totalSize) {
$progress = 100 * ($position / $totalSize);
$this->setAddonDownloadProgress($progress);
$this->save();
}
/* Just to be safe, check all error conditions */
if ($data === "" or $data === false) {
break;
}
if (fwrite($file, $data) === false) {
break;
}
}
fclose($handle);
fclose($file);
if ($elapsed > 60) {
$time = sprintf("%.0f minutes and %.0f seconds", round($elapsed / 60), round($elapsed) % 60);
} else {
$time = sprintf("%.0f seconds", round($elapsed));
}
for ($i = 0; $position >= 1024 && $i < 4; $i++) {
$position /= 1024;
}
for ($j = 0; $rate >= 1024 && $j < 4; $j++) {
$rate /= 1024;
}
//printf("Downloaded %.2f%s in %s (rate: %.2f%s/s)\n", $position, $units[$i], $time, $rate, $units[$j]);
return ($this->checkDownload());
}
/**
* Install this addon from the downloaded file.
*/
public function install()
{
$this->setState("install");
$filename = $this->getDownloadFilename();
//if ($this->checkDownload() === false) {
// throw new Exception("Download file is invalid");
//}
if ($this->isPlugin()) {
if ($this->getAddonId() == "enterprise") {
$_SESSION["__ENTERPRISE_INSTALL__"] = 1;
}
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$oPluginRegistry->installPluginArchive($filename, $this->getAddonName());
$this->setState();
} else {
if ($this->getAddonType() == "core") {
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.Upgrade.php';
$upgrade = new Upgrade($this);
$upgrade->install();
} else {
throw new Exception("Addon type {$this->getAddonType()} not supported.");
}
}
}
public function uninstall()
{
if ($this->isPlugin()) {
if (!$this->isInstalled()) {
return false;
}
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$oPluginRegistry->uninstallPlugin($this->getAddonName());
return true;
}
}
public function getInstallLog()
{
$logFile = $this->getDownloadDirectory() . "/download.log";
$contents = false;
if (file_exists($logFile)) {
$contents = @file_get_contents($logFile);
}
if ($contents === false) {
return null;
}
return $contents;
}
public function setState($state = "")
{
$this->setAddonState($state);
$this->setAddonStateChanged('now');
$this->save();
}
public function checkState()
{
if ($this->getAddonState() == 'error') {
$this->setState();
return false;
}
if ($this->getAddonState() == '' || $this->getAddonState() == 'install-finish') {
return true;
}
$elapsed = time() - strtotime($this->getAddonStateChanged());
$timeout = 3;
if ($this->isCore()) {
$timeout = 10;
}
if ($elapsed > $timeout * 60) {
$this->setState();
return false;
}
return true;
}
}

View File

@@ -0,0 +1,24 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseAddonsManagerPeer.php';
// include object class
include_once 'classes/model/AddonsManager.php';
/**
* Skeleton subclass for performing query and update operations on the 'UPGRADE_MANAGER' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package classes.model
*/
class AddonsManagerPeer extends BaseAddonsManagerPeer
{
}

View File

@@ -0,0 +1,463 @@
<?php
require_once 'classes/model/om/BaseAddonsStore.php';
G::LoadClass("system");
define("STORE_VERSION", 1);
class AddonsStore extends BaseAddonsStore
{
/**
* Add a store to the database
*
* @param string $storeId 32-character long store id
* @param string $storeLocation URL to obtain the store info
* @param string $storeType type of store (only "license" supported now)
* @param string $storeVersion version of the data store
*/
public static function addStore($storeId, $storeLocation, $storeType = "license", $storeVersion = STORE_VERSION)
{
$store = new AddonsStore();
$store->setStoreId($storeId);
$store->setStoreLocation($storeLocation);
$store->setStoreVersion($storeVersion);
$store->setStoreType($storeType);
return AddonsStorePeer::doInsert($store);
}
/**
* Check if the current license has a store and removes unwanted stores.
*
* @return bool true if a store was added, false otherwise.
*/
public static function checkLicenseStore()
{
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php';
//getting the licenseManager....
$licenseManager = &pmLicenseManager::getSingleton();
if (isset($licenseManager->id)) {
//Remove any license store that is not the active license
$criteria = new Criteria(AddonsStorePeer::DATABASE_NAME);
$criteria->addSelectColumn("*");
$criteria->add(AddonsStorePeer::STORE_TYPE, "license", Criteria::EQUAL);
$criteria->add(AddonsStorePeer::STORE_ID, $licenseManager->id, Criteria::NOT_EQUAL);
foreach (AddonsStorePeer::doSelect($criteria) as $store) {
$store->clear();
}
AddonsStorePeer::doDelete($criteria);
//If the active license doesn't have a store, add one for it
if (AddonsStorePeer::retrieveByPK($licenseManager->id) === null) {
preg_match("/^license_(.*).dat$/", $licenseManager->file, $matches);
$realId = urlencode($matches[1]);
$addonLocation = "http://{$licenseManager->server}/syspmLicenseSrv/en/green/services/addonsStore?action=getInfo&licId=$realId";
self::addStore($licenseManager->id, $addonLocation);
return true;
}
}
return false;
}
public static function addonList()
{
$result = array();
AddonsStore::checkLicenseStore();
$licenseManager = &pmLicenseManager::getSingleton(); //Getting the licenseManager
$result["store_errors"] = array();
list($stores, $errors) = AddonsStore::updateAll(false);
foreach ($errors as $store_id => $store_error) {
$result["store_errors"][] = array("id" => $store_id, "msg" => $store_error);
}
$result["addons"] = array();
$result["errors"] = array();
$criteria = new Criteria();
$criteria->addAscendingOrderByColumn(AddonsManagerPeer::ADDON_TYPE);
$criteria->addAscendingOrderByColumn(AddonsManagerPeer::ADDON_ID);
$addons = AddonsManagerPeer::doSelect($criteria);
foreach ($addons as $addon) {
$status = $addon->getAddonStatus();
$version = $addon->getAddonVersion();
$enabled = null;
if (!$addon->checkState()) {
$result["errors"][] = array("addonId" => $addon->getAddonId(), "storeId" => $addon->getStoreId());
}
$sw = 1;
$addonInLicense = in_array($addon->getAddonId(), $licenseManager->features);
if ($sw == 1 && $addon->getAddonId() != "enterprise" && !$addonInLicense) {
$sw = 0;
}
if ($sw == 1 && $addon->isInstalled()) {
if ($addon->isEnabled()) {
$status = "installed";
} else {
$status = "disabled";
}
$version = $addon->getInstalledVersion();
if (version_compare($version . "", $addon->getAddonVersion() . "", "<")) {
$status = "upgrade";
}
$enabled = $addon->isEnabled();
$sw = 0;
}
if ($sw == 1 && $addonInLicense) {
$status = "ready";
$sw = 0;
}
$state = $addon->getAddonState();
$log = null;
if ($state != null) {
$status = $state;
$log = $addon->getInstallLog();
}
if ($addon->getAddonId() == "enterprise" && $status== 'ready') {
$status = 'installed';
}
$result["addons"][$addon->getAddonId()] = array(
"id" => $addon->getAddonId(),
"store" => $addon->getStoreId(),
"name" => $addon->getAddonName(),
"nick" => $addon->getAddonNick(),
"version" => $version,
"enabled" => $enabled,
"latest_version" => $addon->getAddonVersion(),
"type" => $addon->getAddonType(),
"release_type" => $addon->getAddonReleaseType(),
"url" => $addon->getAddonDownloadUrl(),
"publisher" => $addon->getAddonPublisher(),
"description" => $addon->getAddonDescription(),
"status" => $status,
"log" => $log,
"progress" => round($addon->getAddonDownloadProgress())
);
}
return $result;
}
/**
* Returns all stores as AddonsStore objects.
*
* @return array of AddonsStore objects
*/
public static function listStores()
{
$criteria = new Criteria(AddonsStorePeer::DATABASE_NAME);
return AddonsStorePeer::doSelect($criteria);
}
/**
* Updates all stores
*
* @return array containing a 'stores' array and a 'errors' array
*/
public static function updateAll($force = false)
{
$stores = array();
$errors = array();
foreach (self::listStores() as $store) {
try {
$stores[$store->getStoreId()] = $store->update($force);
} catch (Exception $e) {
$errors[$store->getStoreId()] = $e->getMessage();
}
}
return array($stores, $errors);
}
/**
* Clear this store addons
*
* @return int number of addons removed
*/
public function clear()
{
/* Remove old items from this store */
$criteria = new Criteria(AddonsManagerPeer::DATABASE_NAME);
$criteria->add(AddonsManagerPeer::STORE_ID, $this->getStoreId(), Criteria::EQUAL);
return AddonsManagerPeer::doDelete($criteria);
}
/**
* Update this store information from the store location.
*
* @return bool true if updated, false otherwise
*/
public function update($force = false)
{
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php';
if (!class_exists('AddonsManagerPeer')) {
require_once ('classes/model/AddonsManager.php');
}
//If we have any addon that is installing or updating, don't update store
$criteria = new Criteria(AddonsManagerPeer::DATABASE_NAME);
$criteria->add(AddonsManagerPeer::ADDON_STATE, '', Criteria::NOT_EQUAL);
if (AddonsManagerPeer::doCount($criteria) > 0) {
return false;
}
$this->clear();
//Fill with local information
//List all plugins installed
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$aPluginsPP = array();
if (file_exists(PATH_DATA_SITE . 'ee')) {
$aPluginsPP = unserialize(trim(file_get_contents(PATH_DATA_SITE . 'ee')));
}
$pmLicenseManagerO = &pmLicenseManager::getSingleton();
$localPlugins = array();
foreach ($aPluginsPP as $aPlugin) {
$sClassName = substr($aPlugin['sFilename'], 0, strpos($aPlugin['sFilename'], '-'));
if (file_exists(PATH_PLUGINS . $sClassName . '.php')) {
require_once PATH_PLUGINS . $sClassName . '.php';
$oDetails = $oPluginRegistry->getPluginDetails($sClassName . '.php');
if ($oDetails) {
$sStatus = $oDetails->enabled ? G::LoadTranslation('ID_ENABLED') : G::LoadTranslation('ID_DISABLED');
if (isset($oDetails->aWorkspaces)) {
if (!in_array(SYS_SYS, $oDetails->aWorkspaces)) {
continue;
}
}
if ($sClassName == "pmLicenseManager" || $sClassName == "pmTrial") {
continue;
}
$sEdit = (($oDetails->sSetupPage != '') && ($oDetails->enabled)? G::LoadTranslation('ID_SETUP') : ' ');
$aPlugin = array();
$aPluginId = $sClassName;
$aPluginTitle = $oDetails->sFriendlyName;
$aPluginDescription = $oDetails->sDescription;
$aPluginVersion = $oDetails->iVersion;
if (@in_array($sClassName, $pmLicenseManagerO->features)) {
$aPluginStatus = $sStatus;
$aPluginLinkStatus = 'pluginsChange?id=' . $sClassName . '.php&status=' . $oDetails->enabled;
$aPluginEdit = $sEdit;
$aPluginLinkEdit = 'pluginsSetup?id=' . $sClassName . '.php';
$aPluginStatusA = $sStatus == "Enabled" ? "installed" : 'disabled';
$enabledStatus = true;
} else {
$aPluginStatus = "";
$aPluginLinkStatus = '';
$aPluginEdit = '';
$aPluginLinkEdit = '';
$aPluginStatusA = 'minus-circle';
$enabledStatus = false;
}
$addon = new AddonsManager();
//G::pr($addon);
$addon->setAddonId($aPluginId);
$addon->setStoreId($this->getStoreId());
//Don't trust external data
$addon->setAddonName($aPluginId);
$addon->setAddonDescription($aPluginDescription);
$addon->setAddonNick($aPluginTitle);
$addon->setAddonVersion("");
$addon->setAddonStatus($aPluginStatusA);
$addon->setAddonType("plugin");
$addon->setAddonPublisher("Colosa");
$addon->setAddonDownloadUrl("");
$addon->setAddonDownloadMd5("");
$addon->setAddonReleaseDate(null);
$addon->setAddonReleaseType('localRegistry');
$addon->setAddonReleaseNotes("");
$addon->setAddonState("");
$addon->save();
$localPlugins[$aPluginId] = $addon;
}
}
}
$this->setStoreLastUpdated(time());
$this->save();
$url = $this->getStoreLocation();
//Validate url
$licenseInfo = $pmLicenseManagerO->getActiveLicense();
$licenseId = str_replace('.dat', '', str_replace('license_', '', basename($licenseInfo['LICENSE_PATH'])));
$url = explode('&', $url);
$url[count($url) - 1] = 'licId=' . urlencode($licenseId);
$url = implode('&', $url);
if (EnterpriseUtils::getInternetConnection() == 1 && EnterpriseUtils::checkConnectivity($url) == true) {
$option = array(
"http" => array(
"method" => "POST",
"header" => "Content-type: application/x-www-form-urlencoded\r\n",
"content" => http_build_query(
array(
"pmVersion" => System::getVersion(),
"version" => STORE_VERSION
)
)
)
);
// Proxy settings
$sysConf = System::getSystemConfiguration();
if (isset($sysConf['proxy_host'])) {
if ($sysConf['proxy_host'] != '') {
if (!is_array($option['http'])) {
$option['http'] = array();
}
$option['http']['request_fulluri'] = true;
$option['http']['proxy'] = 'tcp://' . $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '');
if ($sysConf['proxy_user'] != '') {
if (!isset($option['http']['header'])) {
$option['http']['header'] = '';
}
$option['http']['header'] .= 'Proxy-Authorization: Basic ' . base64_encode($sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
}
}
}
$context = stream_context_create($option);
//This may block for a while, always use AJAX to call this method
$data = file_get_contents($url, false, $context);
if ($data === false) {
throw new Exception("Could not contact store");
}
$serverData = G::json_decode($data);
//Don't trust external data
if (empty($serverData)) {
throw (new Exception("Store data invalid ('$data')"));
}
if (isset($serverData->error)) {
throw (new Exception("Store sent us an error: {$serverData->error}"));
}
if (!isset($serverData->version)) {
throw (new Exception("Store version not found"));
}
if ($serverData->version != STORE_VERSION) {
throw (new Exception("Store version '{$serverData->version}' unsupported"));
}
if (!isset($serverData->addons)) {
throw (new Exception("Addons not found on store data"));
}
$this->clear();
try {
//Add each item to this stores addons
$addons = @get_object_vars($serverData->addons);
if (!empty($addons)) {
foreach (get_object_vars($serverData->addons) as $addonId => $addonInfo) {
$addon = new AddonsManager();
$addon->setAddonId($addonId);
$addon->setStoreId($this->getStoreId());
//Don't trust external data
$addon->setAddonName(isset($addonInfo->name)? $addonInfo->name : $addonId);
$addon->setAddonDescription(isset($addonInfo->description)? $addonInfo->description : "");
$addon->setAddonNick(isset($addonInfo->nick)? $addonInfo->nick : "");
$addon->setAddonVersion(isset($addonInfo->version)? $addonInfo->version : "");
$addon->setAddonStatus(isset($addonInfo->status)? $addonInfo->status : "");
$addon->setAddonType(isset($addonInfo->type)? $addonInfo->type : "");
$addon->setAddonPublisher(isset($addonInfo->publisher)? $addonInfo->publisher : "");
$addon->setAddonDownloadUrl(isset($addonInfo->download_url)? $addonInfo->download_url : "http://" . $pmLicenseManagerO->server . "/syspmLicenseSrv/en/green/services/rest?action=getPlugin&OBJ_UID=" . $addonInfo->guid);
$addon->setAddonDownloadMd5(isset($addonInfo->download_md5)? $addonInfo->download_md5 : "");
$addon->setAddonReleaseDate(isset($addonInfo->release_date)? $addonInfo->release_date : "");
$addon->setAddonReleaseType(isset($addonInfo->release_type)? $addonInfo->release_type : '');
$addon->setAddonReleaseNotes(isset($addonInfo->release_notes)? $addonInfo->release_notes : "");
$addon->setAddonState("");
$addon->save();
if (isset($localPlugins[$addonId])) {
unset($localPlugins[$addonId]);
}
}
foreach ($localPlugins as $keyPlugin => $addonA) {
//G::pr($addonA );
//$addonA->save();
$addon = new AddonsManager();
//G::pr($addon);
$addon->setAddonId($addonA->getAddonId());
$addon->setStoreId($addonA->getStoreId());
//Don't trust external data
$addon->setAddonName($addonA->getAddonName());
$addon->setAddonDescription($addonA->getAddonDescription());
$addon->setAddonNick($addonA->getAddonNick());
$addon->setAddonVersion("");
$addon->setAddonStatus($addonA->getAddonStatus());
$addon->setAddonType($addonA->getAddonType());
$addon->setAddonPublisher($addonA->getAddonPublisher());
$addon->setAddonDownloadUrl($addonA->getAddonDownloadUrl());
$addon->setAddonDownloadMd5($addonA->getAddonDownloadMd5());
$addon->setAddonReleaseDate(null);
$addon->setAddonReleaseType('localRegistry');
$addon->setAddonReleaseNotes("");
$addon->setAddonState("");
$addon->save();
}
}
$this->setStoreLastUpdated(time());
$this->save();
} catch (Exception $e) {
//If we had issues, don't keep only a part of the items
$this->clear();
throw $e;
}
}
return true;
}
}

View File

@@ -0,0 +1,24 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseAddonsStorePeer.php';
// include object class
include_once 'classes/model/AddonsStore.php';
/**
* Skeleton subclass for performing query and update operations on the 'ADDONS_STORE' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package classes.model
*/
class AddonsStorePeer extends BaseAddonsStorePeer
{
}

View File

@@ -0,0 +1,20 @@
<?php
require_once 'classes/model/om/BaseLicenseManager.php';
/**
* Skeleton subclass for representing a row from the 'LICENSE_MANAGER' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package classes.model
*/
class LicenseManager extends BaseLicenseManager
{
}

View File

@@ -0,0 +1,24 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseLicenseManagerPeer.php';
// include object class
include_once 'classes/model/LicenseManager.php';
/**
* Skeleton subclass for performing query and update operations on the 'LICENSE_MANAGER' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package classes.model
*/
class LicenseManagerPeer extends BaseLicenseManagerPeer
{
}

View File

@@ -0,0 +1,70 @@
<?php
require_once 'propel/map/MapBuilder.php';
include_once 'creole/CreoleTypes.php';
/**
* This class adds structure of 'ADDON_STORE' table to 'propel' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package workflow.classes.model.map
*/
class AddonStoreMapBuilder
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'classes.model.map.AddonStoreMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('propel');
$tMap = $this->dbMap->addTable('ADDON_STORE');
$tMap->setPhpName('AddonStore');
$tMap->setUseIdGenerator(false);
$tMap->addPrimaryKey('STORE_ID', 'StoreId', 'string', CreoleTypes::VARCHAR, true, 32);
$tMap->addColumn('STORE_VERSION', 'StoreVersion', 'int', CreoleTypes::INTEGER, false, null);
$tMap->addColumn('STORE_LOCATION', 'StoreLocation', 'string', CreoleTypes::VARCHAR, true, 2048);
$tMap->addColumn('LAST_UPDATED', 'LastUpdated', 'int', CreoleTypes::TIMESTAMP, false, null);
}
}

View File

@@ -0,0 +1,101 @@
<?php
require_once 'propel/map/MapBuilder.php';
include_once 'creole/CreoleTypes.php';
/**
* This class adds structure of 'ADDONS_MANAGER' table to 'workflow' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package workflow.classes.model.map
*/
class AddonsManagerMapBuilder
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'classes.model.map.AddonsManagerMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('workflow');
$tMap = $this->dbMap->addTable('ADDONS_MANAGER');
$tMap->setPhpName('AddonsManager');
$tMap->setUseIdGenerator(false);
$tMap->addPrimaryKey('ADDON_ID', 'AddonId', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addPrimaryKey('STORE_ID', 'StoreId', 'string', CreoleTypes::VARCHAR, true, 32);
$tMap->addColumn('ADDON_NAME', 'AddonName', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('ADDON_NICK', 'AddonNick', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('ADDON_DOWNLOAD_FILENAME', 'AddonDownloadFilename', 'string', CreoleTypes::VARCHAR, false, 1024);
$tMap->addColumn('ADDON_DESCRIPTION', 'AddonDescription', 'string', CreoleTypes::VARCHAR, false, 2048);
$tMap->addColumn('ADDON_STATE', 'AddonState', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('ADDON_STATE_CHANGED', 'AddonStateChanged', 'int', CreoleTypes::TIMESTAMP, false, null);
$tMap->addColumn('ADDON_STATUS', 'AddonStatus', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('ADDON_VERSION', 'AddonVersion', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('ADDON_TYPE', 'AddonType', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('ADDON_PUBLISHER', 'AddonPublisher', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('ADDON_RELEASE_DATE', 'AddonReleaseDate', 'int', CreoleTypes::TIMESTAMP, false, null);
$tMap->addColumn('ADDON_RELEASE_TYPE', 'AddonReleaseType', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('ADDON_RELEASE_NOTES', 'AddonReleaseNotes', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('ADDON_DOWNLOAD_URL', 'AddonDownloadUrl', 'string', CreoleTypes::VARCHAR, false, 2048);
$tMap->addColumn('ADDON_DOWNLOAD_PROGRESS', 'AddonDownloadProgress', 'double', CreoleTypes::FLOAT, false, null);
$tMap->addColumn('ADDON_DOWNLOAD_MD5', 'AddonDownloadMd5', 'string', CreoleTypes::VARCHAR, false, 32);
}
}

View File

@@ -0,0 +1,80 @@
<?php
require_once 'propel/map/MapBuilder.php';
include_once 'creole/CreoleTypes.php';
/**
* This class adds structure of 'ADDONS_STORE' table to 'workflow' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package workflow.classes.model.map
*/
class AddonsStoreMapBuilder
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'classes.model.map.AddonsStoreMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('workflow');
$tMap = $this->dbMap->addTable('ADDONS_STORE');
$tMap->setPhpName('AddonsStore');
$tMap->setUseIdGenerator(false);
$tMap->addPrimaryKey('STORE_ID', 'StoreId', 'string', CreoleTypes::VARCHAR, true, 32);
$tMap->addColumn('STORE_VERSION', 'StoreVersion', 'int', CreoleTypes::INTEGER, false, null);
$tMap->addColumn('STORE_LOCATION', 'StoreLocation', 'string', CreoleTypes::VARCHAR, true, 2048);
$tMap->addColumn('STORE_TYPE', 'StoreType', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('STORE_LAST_UPDATED', 'StoreLastUpdated', 'int', CreoleTypes::TIMESTAMP, false, null);
}
}

View File

@@ -0,0 +1,88 @@
<?php
require_once 'propel/map/MapBuilder.php';
include_once 'creole/CreoleTypes.php';
/**
* This class adds structure of 'LICENSE_MANAGER' table to 'workflow' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package classes.model.map
*/
class LicenseManagerMapBuilder
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'classes.model.map.LicenseManagerMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('workflow');
$tMap = $this->dbMap->addTable('LICENSE_MANAGER');
$tMap->setPhpName('LicenseManager');
$tMap->setUseIdGenerator(false);
$tMap->addPrimaryKey('LICENSE_UID', 'LicenseUid', 'string', CreoleTypes::VARCHAR, true, 32);
$tMap->addColumn('LICENSE_USER', 'LicenseUser', 'string', CreoleTypes::VARCHAR, true, 32);
$tMap->addColumn('LICENSE_START', 'LicenseStart', 'int', CreoleTypes::INTEGER, true, null);
$tMap->addColumn('LICENSE_END', 'LicenseEnd', 'int', CreoleTypes::INTEGER, true, null);
$tMap->addColumn('LICENSE_SPAN', 'LicenseSpan', 'int', CreoleTypes::INTEGER, true, null);
$tMap->addColumn('LICENSE_STATUS', 'LicenseStatus', 'string', CreoleTypes::VARCHAR, false, 100);
$tMap->addColumn('LICENSE_DATA', 'LicenseData', 'string', CreoleTypes::LONGVARCHAR, true, null);
$tMap->addColumn('LICENSE_PATH', 'LicensePath', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('LICENSE_WORKSPACE', 'LicenseWorkspace', 'string', CreoleTypes::VARCHAR, true, 32);
$tMap->addColumn('LICENSE_TYPE', 'LicenseType', 'string', CreoleTypes::VARCHAR, true, 32);
}
}

View File

@@ -0,0 +1,79 @@
<?php
require_once 'propel/map/MapBuilder.php';
include_once 'creole/CreoleTypes.php';
/**
* This class adds structure of 'UPGRADE_MANAGER' table to 'workflow' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package workflow.classes.model.map
*/
class UpgradeManagerMapBuilder
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'classes.model.map.UpgradeManagerMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('workflow');
$tMap = $this->dbMap->addTable('UPGRADE_MANAGER');
$tMap->setPhpName('UpgradeManager');
$tMap->setUseIdGenerator(false);
$tMap->addPrimaryKey('COMPONENT_NAME', 'ComponentName', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('COMPONENT_NICK', 'ComponentNick', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('COMPONENT_STATE', 'ComponentState', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('COMPONENT_STATUS', 'ComponentStatus', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('COMPONENT_VERSION', 'ComponentVersion', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('COMPONENT_TYPE', 'ComponentType', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('STORE_ID', 'StoreId', 'string', CreoleTypes::VARCHAR, true, 32);
}
}

View File

@@ -0,0 +1,74 @@
<?php
require_once 'propel/map/MapBuilder.php';
include_once 'creole/CreoleTypes.php';
/**
* This class adds structure of 'UPGRADE_STORE' table to 'workflow' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package workflow.classes.model.map
*/
class UpgradeStoreMapBuilder
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'classes.model.map.UpgradeStoreMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('workflow');
$tMap = $this->dbMap->addTable('UPGRADE_STORE');
$tMap->setPhpName('UpgradeStore');
$tMap->setUseIdGenerator(false);
$tMap->addPrimaryKey('STORE_ID', 'StoreId', 'string', CreoleTypes::VARCHAR, true, 32);
$tMap->addColumn('STORE_VERSION', 'StoreVersion', 'int', CreoleTypes::INTEGER, false, null);
$tMap->addColumn('STORE_LOCATION', 'StoreLocation', 'string', CreoleTypes::VARCHAR, true, 2048);
$tMap->addColumn('LAST_UPDATED', 'LastUpdated', 'int', CreoleTypes::TIMESTAMP, false, null);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,699 @@
<?php
require_once 'propel/util/BasePeer.php';
// The object class -- needed for instanceof checks in this class.
// actual class may be a subclass -- as returned by AddonsManagerPeer::getOMClass()
include_once 'classes/model/AddonsManager.php';
/**
* Base static class for performing query and update operations on the 'ADDONS_MANAGER' table.
*
*
*
* @package workflow.classes.model.om
*/
abstract class BaseAddonsManagerPeer
{
/**
* the default database name for this class
*/
const DATABASE_NAME = 'workflow';
/**
* the table name for this class
*/
const TABLE_NAME = 'ADDONS_MANAGER';
/**
* A class that can be returned by this peer.
*/
const CLASS_DEFAULT = 'classes.model.AddonsManager';
/**
* The total number of columns.
*/
const NUM_COLUMNS = 18;
/**
* The number of lazy-loaded columns.
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* the column name for the ADDON_ID field
*/
const ADDON_ID = 'ADDONS_MANAGER.ADDON_ID';
/**
* the column name for the STORE_ID field
*/
const STORE_ID = 'ADDONS_MANAGER.STORE_ID';
/**
* the column name for the ADDON_NAME field
*/
const ADDON_NAME = 'ADDONS_MANAGER.ADDON_NAME';
/**
* the column name for the ADDON_NICK field
*/
const ADDON_NICK = 'ADDONS_MANAGER.ADDON_NICK';
/**
* the column name for the ADDON_DOWNLOAD_FILENAME field
*/
const ADDON_DOWNLOAD_FILENAME = 'ADDONS_MANAGER.ADDON_DOWNLOAD_FILENAME';
/**
* the column name for the ADDON_DESCRIPTION field
*/
const ADDON_DESCRIPTION = 'ADDONS_MANAGER.ADDON_DESCRIPTION';
/**
* the column name for the ADDON_STATE field
*/
const ADDON_STATE = 'ADDONS_MANAGER.ADDON_STATE';
/**
* the column name for the ADDON_STATE_CHANGED field
*/
const ADDON_STATE_CHANGED = 'ADDONS_MANAGER.ADDON_STATE_CHANGED';
/**
* the column name for the ADDON_STATUS field
*/
const ADDON_STATUS = 'ADDONS_MANAGER.ADDON_STATUS';
/**
* the column name for the ADDON_VERSION field
*/
const ADDON_VERSION = 'ADDONS_MANAGER.ADDON_VERSION';
/**
* the column name for the ADDON_TYPE field
*/
const ADDON_TYPE = 'ADDONS_MANAGER.ADDON_TYPE';
/**
* the column name for the ADDON_PUBLISHER field
*/
const ADDON_PUBLISHER = 'ADDONS_MANAGER.ADDON_PUBLISHER';
/**
* the column name for the ADDON_RELEASE_DATE field
*/
const ADDON_RELEASE_DATE = 'ADDONS_MANAGER.ADDON_RELEASE_DATE';
/**
* the column name for the ADDON_RELEASE_TYPE field
*/
const ADDON_RELEASE_TYPE = 'ADDONS_MANAGER.ADDON_RELEASE_TYPE';
/**
* the column name for the ADDON_RELEASE_NOTES field
*/
const ADDON_RELEASE_NOTES = 'ADDONS_MANAGER.ADDON_RELEASE_NOTES';
/**
* the column name for the ADDON_DOWNLOAD_URL field
*/
const ADDON_DOWNLOAD_URL = 'ADDONS_MANAGER.ADDON_DOWNLOAD_URL';
/**
* the column name for the ADDON_DOWNLOAD_PROGRESS field
*/
const ADDON_DOWNLOAD_PROGRESS = 'ADDONS_MANAGER.ADDON_DOWNLOAD_PROGRESS';
/**
* the column name for the ADDON_DOWNLOAD_MD5 field
*/
const ADDON_DOWNLOAD_MD5 = 'ADDONS_MANAGER.ADDON_DOWNLOAD_MD5';
/**
* The PHP to DB Name Mapping
*/
private static $phpNameMap = null;
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('AddonId','StoreId','AddonName','AddonNick','AddonDownloadFilename','AddonDescription','AddonState','AddonStateChanged','AddonStatus','AddonVersion','AddonType','AddonPublisher','AddonReleaseDate','AddonReleaseType','AddonReleaseNotes','AddonDownloadUrl','AddonDownloadProgress','AddonDownloadMd5'),
BasePeer::TYPE_COLNAME => array (AddonsManagerPeer::ADDON_ID,AddonsManagerPeer::STORE_ID,AddonsManagerPeer::ADDON_NAME,AddonsManagerPeer::ADDON_NICK,AddonsManagerPeer::ADDON_DOWNLOAD_FILENAME,AddonsManagerPeer::ADDON_DESCRIPTION,AddonsManagerPeer::ADDON_STATE,AddonsManagerPeer::ADDON_STATE_CHANGED,AddonsManagerPeer::ADDON_STATUS,AddonsManagerPeer::ADDON_VERSION,AddonsManagerPeer::ADDON_TYPE,AddonsManagerPeer::ADDON_PUBLISHER,AddonsManagerPeer::ADDON_RELEASE_DATE,AddonsManagerPeer::ADDON_RELEASE_TYPE,AddonsManagerPeer::ADDON_RELEASE_NOTES,AddonsManagerPeer::ADDON_DOWNLOAD_URL,AddonsManagerPeer::ADDON_DOWNLOAD_PROGRESS,AddonsManagerPeer::ADDON_DOWNLOAD_MD5),
BasePeer::TYPE_FIELDNAME => array ('ADDON_ID','STORE_ID','ADDON_NAME','ADDON_NICK','ADDON_DOWNLOAD_FILENAME','ADDON_DESCRIPTION','ADDON_STATE','ADDON_STATE_CHANGED','ADDON_STATUS','ADDON_VERSION','ADDON_TYPE','ADDON_PUBLISHER','ADDON_RELEASE_DATE','ADDON_RELEASE_TYPE','ADDON_RELEASE_NOTES','ADDON_DOWNLOAD_URL','ADDON_DOWNLOAD_PROGRESS','ADDON_DOWNLOAD_MD5'),
BasePeer::TYPE_NUM => array (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17)
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('AddonId' => 0,'StoreId' => 1,'AddonName' => 2,'AddonNick' => 3,'AddonDownloadFilename' => 4,'AddonDescription' => 5,'AddonState' => 6,'AddonStateChanged' => 7,'AddonStatus' => 8,'AddonVersion' => 9,'AddonType' => 10,'AddonPublisher' => 11,'AddonReleaseDate' => 12,'AddonReleaseType' => 13,'AddonReleaseNotes' => 14,'AddonDownloadUrl' => 15,'AddonDownloadProgress' => 16,'AddonDownloadMd5' => 17),
BasePeer::TYPE_COLNAME => array (AddonsManagerPeer::ADDON_ID => 0,AddonsManagerPeer::STORE_ID => 1,AddonsManagerPeer::ADDON_NAME => 2,AddonsManagerPeer::ADDON_NICK => 3,AddonsManagerPeer::ADDON_DOWNLOAD_FILENAME => 4,AddonsManagerPeer::ADDON_DESCRIPTION => 5,AddonsManagerPeer::ADDON_STATE => 6,AddonsManagerPeer::ADDON_STATE_CHANGED => 7,AddonsManagerPeer::ADDON_STATUS => 8,AddonsManagerPeer::ADDON_VERSION => 9,AddonsManagerPeer::ADDON_TYPE => 10,AddonsManagerPeer::ADDON_PUBLISHER => 11,AddonsManagerPeer::ADDON_RELEASE_DATE => 12,AddonsManagerPeer::ADDON_RELEASE_TYPE => 13,AddonsManagerPeer::ADDON_RELEASE_NOTES => 14,AddonsManagerPeer::ADDON_DOWNLOAD_URL => 15,AddonsManagerPeer::ADDON_DOWNLOAD_PROGRESS => 16,AddonsManagerPeer::ADDON_DOWNLOAD_MD5 => 17),
BasePeer::TYPE_FIELDNAME => array ('ADDON_ID' => 0,'STORE_ID' => 1,'ADDON_NAME' => 2,'ADDON_NICK' => 3,'ADDON_DOWNLOAD_FILENAME' => 4,'ADDON_DESCRIPTION' => 5,'ADDON_STATE' => 6,'ADDON_STATE_CHANGED' => 7,'ADDON_STATUS' => 8,'ADDON_VERSION' => 9,'ADDON_TYPE' => 10,'ADDON_PUBLISHER' => 11,'ADDON_RELEASE_DATE' => 12,'ADDON_RELEASE_TYPE' => 13,'ADDON_RELEASE_NOTES' => 14,'ADDON_DOWNLOAD_URL' => 15,'ADDON_DOWNLOAD_PROGRESS' => 16,'ADDON_DOWNLOAD_MD5' => 17),
BasePeer::TYPE_NUM => array (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17)
);
/**
*
* @return MapBuilder the map builder for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getMapBuilder ()
{
include_once 'classes/model/map/AddonsManagerMapBuilder.php';
return BasePeer::getMapBuilder( 'classes.model.map.AddonsManagerMapBuilder' );
}
/**
* Gets a map (hash) of PHP names to DB column names.
*
* @return array The PHP to DB name map for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @deprecated Use the getFieldNames() and translateFieldName() methods instead of this.
*/
public static function getPhpNameMap ()
{
if (self::$phpNameMap === null) {
$map = AddonsManagerPeer::getTableMap();
$columns = $map->getColumns();
$nameMap = array ();
foreach ($columns as $column) {
$nameMap[$column->getPhpName()] = $column->getColumnName();
}
self::$phpNameMap = $nameMap;
}
return self::$phpNameMap;
}
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
*/
static public function translateFieldName ($name, $fromType, $toType)
{
$toNames = self::getFieldNames( $toType );
$key = isset( self::$fieldKeys[$fromType][$name] ) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException( "'$name' could not be found in the field names of type '$fromType'. These are: " . print_r( self::$fieldKeys[$fromType], true ) );
}
return $toNames[$key];
}
/**
* Returns an array of of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return array A list of field names
*/
static public function getFieldNames ($type = BasePeer::TYPE_PHPNAME)
{
if (! array_key_exists( $type, self::$fieldNames )) {
throw new PropelException( 'Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.' );
}
return self::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
*
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. AddonsManagerPeer::COLUMN_NAME).
* @return string
*/
public static function alias ($alias, $column)
{
return str_replace( AddonsManagerPeer::TABLE_NAME . '.', $alias . '.', $column );
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param criteria object containing the columns to add.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns (Criteria $criteria)
{
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_ID );
$criteria->addSelectColumn( AddonsManagerPeer::STORE_ID );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_NAME );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_NICK );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_DOWNLOAD_FILENAME );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_DESCRIPTION );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_STATE );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_STATE_CHANGED );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_STATUS );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_VERSION );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_TYPE );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_PUBLISHER );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_RELEASE_DATE );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_RELEASE_TYPE );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_RELEASE_NOTES );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_DOWNLOAD_URL );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_DOWNLOAD_PROGRESS );
$criteria->addSelectColumn( AddonsManagerPeer::ADDON_DOWNLOAD_MD5 );
}
const COUNT = 'COUNT(ADDONS_MANAGER.ADDON_ID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT ADDONS_MANAGER.ADDON_ID)';
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCount (Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array( Criteria::DISTINCT, $criteria->getSelectModifiers() )) {
$criteria->addSelectColumn( AddonsManagerPeer::COUNT_DISTINCT );
} else {
$criteria->addSelectColumn( AddonsManagerPeer::COUNT );
}
// just in case we're grouping: add those columns to the select statement
foreach ($criteria->getGroupByColumns() as $column) {
$criteria->addSelectColumn( $column );
}
$rs = AddonsManagerPeer::doSelectRS( $criteria, $con );
if ($rs->next()) {
return $rs->getInt( 1 );
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Method to select one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param Connection $con
* @return AddonsManager
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne (Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit( 1 );
$objects = AddonsManagerPeer::doSelect( $critcopy, $con );
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Method to do selects.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con
* @return array Array of selected Objects
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect (Criteria $criteria, $con = null)
{
return AddonsManagerPeer::populateObjects( AddonsManagerPeer::doSelectRS( $criteria, $con ) );
}
/**
* Prepares the Criteria object and uses the parent doSelect()
* method to get a ResultSet.
*
* Use this method directly if you want to just get the resultset
* (instead of an array of objects).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return ResultSet The resultset object with numerically-indexed fields.
* @see BasePeer::doSelect()
*/
public static function doSelectRS (Criteria $criteria, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
if (! $criteria->getSelectColumns()) {
$criteria = clone $criteria;
AddonsManagerPeer::addSelectColumns( $criteria );
}
// Set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
// BasePeer returns a Creole ResultSet, set to return
// rows indexed numerically.
return BasePeer::doSelect( $criteria, $con );
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects (ResultSet $rs)
{
$results = array ();
// set the class once to avoid overhead in the loop
$cls = AddonsManagerPeer::getOMClass();
$cls = Propel::import( $cls );
// populate the object(s)
while ($rs->next()) {
$obj = new $cls();
$obj->hydrate( $rs );
$results[] = $obj;
}
return $results;
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
*
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap ()
{
return Propel::getDatabaseMap( self::DATABASE_NAME )->getTable( self::TABLE_NAME );
}
/**
* The class that the Peer will make instances of.
*
* This uses a dot-path notation which is tranalted into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @return string path.to.ClassName
*/
public static function getOMClass ()
{
return AddonsManagerPeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a AddonsManager or Criteria object.
*
* @param mixed $values Criteria or AddonsManager object containing data that is used to create the INSERT statement.
* @param Connection $con the connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert ($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from AddonsManager object
}
// Set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->begin();
$pk = BasePeer::doInsert( $criteria, $con );
$con->commit();
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
return $pk;
}
/**
* Method perform an UPDATE on the database, given a AddonsManager or Criteria object.
*
* @param mixed $values Criteria or AddonsManager object containing data that is used to create the UPDATE statement.
* @param Connection $con The connection to use (specify Connection object to exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate ($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$selectCriteria = new Criteria( self::DATABASE_NAME );
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison( AddonsManagerPeer::ADDON_ID );
$selectCriteria->add( AddonsManagerPeer::ADDON_ID, $criteria->remove( AddonsManagerPeer::ADDON_ID ), $comparison );
$comparison = $criteria->getComparison( AddonsManagerPeer::STORE_ID );
$selectCriteria->add( AddonsManagerPeer::STORE_ID, $criteria->remove( AddonsManagerPeer::STORE_ID ), $comparison );
} else {
// $values is AddonsManager object
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
return BasePeer::doUpdate( $selectCriteria, $criteria, $con );
}
/**
* Method to DELETE all rows from the ADDONS_MANAGER table.
*
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll ($con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDeleteAll( AddonsManagerPeer::TABLE_NAME, $con );
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a AddonsManager or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or AddonsManager object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param Connection $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete ($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( AddonsManagerPeer::DATABASE_NAME );
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof AddonsManager) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria( self::DATABASE_NAME );
// primary key is composite; we therefore, expect
// the primary key passed to be an array of pkey
// values
if (count( $values ) == count( $values, COUNT_RECURSIVE )) {
// array is not multi-dimensional
$values = array (
$values
);
}
$vals = array ();
foreach ($values as $value) {
$vals[0][] = $value[0];
$vals[1][] = $value[1];
}
$criteria->add( AddonsManagerPeer::ADDON_ID, $vals[0], Criteria::IN );
$criteria->add( AddonsManagerPeer::STORE_ID, $vals[1], Criteria::IN );
}
// Set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDelete( $criteria, $con );
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Validates all modified columns of given AddonsManager object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param AddonsManager $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate (AddonsManager $obj, $cols = null)
{
$columns = array ();
if ($cols) {
$dbMap = Propel::getDatabaseMap( AddonsManagerPeer::DATABASE_NAME );
$tableMap = $dbMap->getTable( AddonsManagerPeer::TABLE_NAME );
if (! is_array( $cols )) {
$cols = array (
$cols
);
}
foreach ($cols as $colName) {
if ($tableMap->containsColumn( $colName )) {
$get = 'get' . $tableMap->getColumn( $colName )->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
return BasePeer::doValidate( AddonsManagerPeer::DATABASE_NAME, AddonsManagerPeer::TABLE_NAME, $columns );
}
/**
* Retrieve object using using composite pkey values.
*
* @param string $addon_id
* @param string $store_id
*
* @param Connection $con
* @return AddonsManager
*/
public static function retrieveByPK ($addon_id, $store_id, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$criteria = new Criteria();
$criteria->add( AddonsManagerPeer::ADDON_ID, $addon_id );
$criteria->add( AddonsManagerPeer::STORE_ID, $store_id );
$v = AddonsManagerPeer::doSelect( $criteria, $con );
return ! empty( $v ) ? $v[0] : null;
}
}
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
BaseAddonsManagerPeer::getMapBuilder();
} catch (Exception $e) {
Propel::log( 'Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR );
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
require_once 'classes/model/map/AddonsManagerMapBuilder.php';
Propel::registerMapBuilder( 'classes.model.map.AddonsManagerMapBuilder' );
}

View File

@@ -0,0 +1,728 @@
<?php
require_once 'propel/om/BaseObject.php';
require_once 'propel/om/Persistent.php';
include_once 'propel/util/Criteria.php';
include_once 'classes/model/AddonsStorePeer.php';
/**
* Base class that represents a row from the 'ADDONS_STORE' table.
*
*
*
* @package workflow.classes.model.om
*/
abstract class BaseAddonsStore extends BaseObject implements Persistent
{
/**
* The Peer class.
* Instance provides a convenient way of calling static methods on a class
* that calling code may not be able to identify.
*
* @var AddonsStorePeer
*/
protected static $peer;
/**
* The value for the store_id field.
*
* @var string
*/
protected $store_id;
/**
* The value for the store_version field.
*
* @var int
*/
protected $store_version;
/**
* The value for the store_location field.
*
* @var string
*/
protected $store_location;
/**
* The value for the store_type field.
*
* @var string
*/
protected $store_type;
/**
* The value for the store_last_updated field.
*
* @var int
*/
protected $store_last_updated;
/**
* Flag to prevent endless save loop, if this object is referenced
* by another object which falls in this transaction.
*
* @var boolean
*/
protected $alreadyInSave = false;
/**
* Flag to prevent endless validation loop, if this object is referenced
* by another object which falls in this transaction.
*
* @var boolean
*/
protected $alreadyInValidation = false;
/**
* Get the [store_id] column value.
*
* @return string
*/
public function getStoreId ()
{
return $this->store_id;
}
/**
* Get the [store_version] column value.
*
* @return int
*/
public function getStoreVersion ()
{
return $this->store_version;
}
/**
* Get the [store_location] column value.
*
* @return string
*/
public function getStoreLocation ()
{
return $this->store_location;
}
/**
* Get the [store_type] column value.
*
* @return string
*/
public function getStoreType ()
{
return $this->store_type;
}
/**
* Get the [optionally formatted] [store_last_updated] column value.
*
* @param string $format The date/time format string (either date()-style or strftime()-style).
* If format is NULL, then the integer unix timestamp will be returned.
* @return mixed Formatted date/time value as string or integer unix timestamp (if format is NULL).
* @throws PropelException - if unable to convert the date/time to timestamp.
*/
public function getStoreLastUpdated ($format = 'Y-m-d H:i:s')
{
if ($this->store_last_updated === null || $this->store_last_updated === '') {
return null;
} elseif (! is_int( $this->store_last_updated )) {
// a non-timestamp value was set externally, so we convert it
$ts = strtotime( $this->store_last_updated );
if ($ts === - 1 || $ts === false) {
// in PHP 5.1 return value changes to FALSE
throw new PropelException( "Unable to parse value of [store_last_updated] as date/time value: " . var_export( $this->store_last_updated, true ) );
}
} else {
$ts = $this->store_last_updated;
}
if ($format === null) {
return $ts;
} elseif (strpos( $format, '%' ) !== false) {
return strftime( $format, $ts );
} else {
return date( $format, $ts );
}
}
/**
* Set the value of [store_id] column.
*
* @param string $v new value
* @return void
*/
public function setStoreId ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->store_id !== $v) {
$this->store_id = $v;
$this->modifiedColumns[] = AddonsStorePeer::STORE_ID;
}
} // setStoreId()
/**
* Set the value of [store_version] column.
*
* @param int $v new value
* @return void
*/
public function setStoreVersion ($v)
{
// Since the native PHP type for this column is integer,
// we will cast the input value to an int (if it is not).
if ($v !== null && ! is_int( $v ) && is_numeric( $v )) {
$v = (int) $v;
}
if ($this->store_version !== $v) {
$this->store_version = $v;
$this->modifiedColumns[] = AddonsStorePeer::STORE_VERSION;
}
} // setStoreVersion()
/**
* Set the value of [store_location] column.
*
* @param string $v new value
* @return void
*/
public function setStoreLocation ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->store_location !== $v) {
$this->store_location = $v;
$this->modifiedColumns[] = AddonsStorePeer::STORE_LOCATION;
}
} // setStoreLocation()
/**
* Set the value of [store_type] column.
*
* @param string $v new value
* @return void
*/
public function setStoreType ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->store_type !== $v) {
$this->store_type = $v;
$this->modifiedColumns[] = AddonsStorePeer::STORE_TYPE;
}
} // setStoreType()
/**
* Set the value of [store_last_updated] column.
*
* @param int $v new value
* @return void
*/
public function setStoreLastUpdated ($v)
{
if ($v !== null && ! is_int( $v )) {
$ts = strtotime( $v );
if ($ts === - 1 || $ts === false) {
// in PHP 5.1 return value changes to FALSE
throw new PropelException( "Unable to parse date/time value for [store_last_updated] from input: " . var_export( $v, true ) );
}
} else {
$ts = $v;
}
if ($this->store_last_updated !== $ts) {
$this->store_last_updated = $ts;
$this->modifiedColumns[] = AddonsStorePeer::STORE_LAST_UPDATED;
}
} // setStoreLastUpdated()
/**
* Hydrates (populates) the object variables with values from the database resultset.
*
* An offset (1-based "start column") is specified so that objects can be hydrated
* with a subset of the columns in the resultset rows. This is needed, for example,
* for results of JOIN queries where the resultset row includes columns from two or
* more tables.
*
* @param ResultSet $rs The ResultSet class with cursor advanced to desired record pos.
* @param int $startcol 1-based offset column which indicates which restultset column to start with.
* @return int next starting column
* @throws PropelException - Any caught Exception will be rewrapped as a PropelException.
*/
public function hydrate (ResultSet $rs, $startcol = 1)
{
try {
$this->store_id = $rs->getString( $startcol + 0 );
$this->store_version = $rs->getInt( $startcol + 1 );
$this->store_location = $rs->getString( $startcol + 2 );
$this->store_type = $rs->getString( $startcol + 3 );
$this->store_last_updated = $rs->getTimestamp( $startcol + 4, null );
$this->resetModified();
$this->setNew( false );
// FIXME - using NUM_COLUMNS may be clearer.
return $startcol + 5; // 5 = AddonsStorePeer::NUM_COLUMNS - AddonsStorePeer::NUM_LAZY_LOAD_COLUMNS).
} catch (Exception $e) {
throw new PropelException( "Error populating AddonsStore object", $e );
}
}
/**
* Removes this object from datastore and sets delete attribute.
*
* @param Connection $con
* @return void
* @throws PropelException
* @see BaseObject::setDeleted()
* @see BaseObject::isDeleted()
*/
public function delete ($con = null)
{
if ($this->isDeleted()) {
throw new PropelException( "This object has already been deleted." );
}
if ($con === null) {
$con = Propel::getConnection( AddonsStorePeer::DATABASE_NAME );
}
try {
$con->begin();
AddonsStorePeer::doDelete( $this, $con );
$this->setDeleted( true );
$con->commit();
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Stores the object in the database.
* If the object is new,
* it inserts it; otherwise an update is performed. This method
* wraps the doSave() worker method in a transaction.
*
* @param Connection $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see doSave()
*/
public function save ($con = null)
{
if ($this->isDeleted()) {
throw new PropelException( "You cannot save an object that has been deleted." );
}
if ($con === null) {
$con = Propel::getConnection( AddonsStorePeer::DATABASE_NAME );
}
try {
$con->begin();
$affectedRows = $this->doSave( $con );
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Stores the object in the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All related objects are also updated in this method.
*
* @param Connection $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see save()
*/
protected function doSave ($con)
{
$affectedRows = 0; // initialize var to track total num of affected rows
if (! $this->alreadyInSave) {
$this->alreadyInSave = true;
// If this object has been modified, then save it to the database.
if ($this->isModified()) {
if ($this->isNew()) {
$pk = AddonsStorePeer::doInsert( $this, $con );
$affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which
// should always be true here (even though technically
// BasePeer::doInsert() can insert multiple rows).
$this->setNew( false );
} else {
$affectedRows += AddonsStorePeer::doUpdate( $this, $con );
}
$this->resetModified(); // [HL] After being saved an object is no longer 'modified'
}
$this->alreadyInSave = false;
}
return $affectedRows;
} // doSave()
/**
* Array of ValidationFailed objects.
*
* @var array ValidationFailed[]
*/
protected $validationFailures = array ();
/**
* Gets any ValidationFailed objects that resulted from last call to validate().
*
*
* @return array ValidationFailed[]
* @see validate()
*/
public function getValidationFailures ()
{
return $this->validationFailures;
}
/**
* Validates the objects modified field values and all objects related to this table.
*
* If $columns is either a column name or an array of column names
* only those columns are validated.
*
* @param mixed $columns Column name or an array of column names.
* @return boolean Whether all columns pass validation.
* @see doValidate()
* @see getValidationFailures()
*/
public function validate ($columns = null)
{
$res = $this->doValidate( $columns );
if ($res === true) {
$this->validationFailures = array ();
return true;
} else {
$this->validationFailures = $res;
return false;
}
}
/**
* This function performs the validation work for complex object models.
*
* In addition to checking the current object, all related objects will
* also be validated. If all pass then <code>true</code> is returned; otherwise
* an aggreagated array of ValidationFailed objects will be returned.
*
* @param array $columns Array of column names to validate.
* @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise.
*/
protected function doValidate ($columns = null)
{
if (! $this->alreadyInValidation) {
$this->alreadyInValidation = true;
$retval = null;
$failureMap = array ();
if (($retval = AddonsStorePeer::doValidate( $this, $columns )) !== true) {
$failureMap = array_merge( $failureMap, $retval );
}
$this->alreadyInValidation = false;
}
return (! empty( $failureMap ) ? $failureMap : true);
}
/**
* Retrieves a field from the object by name passed in as a string.
*
* @param string $name name
* @param string $type The type of fieldname the $name is of:
* one of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return mixed Value of field.
*/
public function getByName ($name, $type = BasePeer::TYPE_PHPNAME)
{
$pos = AddonsStorePeer::translateFieldName( $name, $type, BasePeer::TYPE_NUM );
return $this->getByPosition( $pos );
}
/**
* Retrieves a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @return mixed Value of field at $pos
*/
public function getByPosition ($pos)
{
switch ($pos) {
case 0:
return $this->getStoreId();
break;
case 1:
return $this->getStoreVersion();
break;
case 2:
return $this->getStoreLocation();
break;
case 3:
return $this->getStoreType();
break;
case 4:
return $this->getStoreLastUpdated();
break;
default:
return null;
break;
} // switch()
}
/**
* Exports the object as an array.
*
* You can specify the key type of the array by passing one of the class
* type constants.
*
* @param string $keyType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return an associative array containing the field names (as keys) and field values
*/
public function toArray ($keyType = BasePeer::TYPE_PHPNAME)
{
$keys = AddonsStorePeer::getFieldNames( $keyType );
$result = array (
$keys[0] => $this->getStoreId(),
$keys[1] => $this->getStoreVersion(),
$keys[2] => $this->getStoreLocation(),
$keys[3] => $this->getStoreType(),
$keys[4] => $this->getStoreLastUpdated()
);
return $result;
}
/**
* Sets a field from the object by name passed in as a string.
*
* @param string $name peer name
* @param mixed $value field value
* @param string $type The type of fieldname the $name is of:
* one of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return void
*/
public function setByName ($name, $value, $type = BasePeer::TYPE_PHPNAME)
{
$pos = AddonsStorePeer::translateFieldName( $name, $type, BasePeer::TYPE_NUM );
return $this->setByPosition( $pos, $value );
}
/**
* Sets a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @param mixed $value field value
* @return void
*/
public function setByPosition ($pos, $value)
{
switch ($pos) {
case 0:
$this->setStoreId( $value );
break;
case 1:
$this->setStoreVersion( $value );
break;
case 2:
$this->setStoreLocation( $value );
break;
case 3:
$this->setStoreType( $value );
break;
case 4:
$this->setStoreLastUpdated( $value );
break;
} // switch()
}
/**
* Populates the object using an array.
*
* This is particularly useful when populating an object from one of the
* request arrays (e.g. $_POST). This method goes through the column
* names, checking to see whether a matching key exists in populated
* array. If so the setByName() method is called for that column.
*
* You can specify the key type of the array by additionally passing one
* of the class type constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME,
* TYPE_NUM. The default key type is the column's phpname (e.g. 'authorId')
*
* @param array $arr An array to populate the object from.
* @param string $keyType The type of keys the array uses.
* @return void
*/
public function fromArray ($arr, $keyType = BasePeer::TYPE_PHPNAME)
{
$keys = AddonsStorePeer::getFieldNames( $keyType );
if (array_key_exists( $keys[0], $arr )) {
$this->setStoreId( $arr[$keys[0]] );
}
if (array_key_exists( $keys[1], $arr )) {
$this->setStoreVersion( $arr[$keys[1]] );
}
if (array_key_exists( $keys[2], $arr )) {
$this->setStoreLocation( $arr[$keys[2]] );
}
if (array_key_exists( $keys[3], $arr )) {
$this->setStoreType( $arr[$keys[3]] );
}
if (array_key_exists( $keys[4], $arr )) {
$this->setStoreLastUpdated( $arr[$keys[4]] );
}
}
/**
* Build a Criteria object containing the values of all modified columns in this object.
*
* @return Criteria The Criteria object containing all modified values.
*/
public function buildCriteria ()
{
$criteria = new Criteria( AddonsStorePeer::DATABASE_NAME );
if ($this->isColumnModified( AddonsStorePeer::STORE_ID )) {
$criteria->add( AddonsStorePeer::STORE_ID, $this->store_id );
}
if ($this->isColumnModified( AddonsStorePeer::STORE_VERSION )) {
$criteria->add( AddonsStorePeer::STORE_VERSION, $this->store_version );
}
if ($this->isColumnModified( AddonsStorePeer::STORE_LOCATION )) {
$criteria->add( AddonsStorePeer::STORE_LOCATION, $this->store_location );
}
if ($this->isColumnModified( AddonsStorePeer::STORE_TYPE )) {
$criteria->add( AddonsStorePeer::STORE_TYPE, $this->store_type );
}
if ($this->isColumnModified( AddonsStorePeer::STORE_LAST_UPDATED )) {
$criteria->add( AddonsStorePeer::STORE_LAST_UPDATED, $this->store_last_updated );
}
return $criteria;
}
/**
* Builds a Criteria object containing the primary key for this object.
*
* Unlike buildCriteria() this method includes the primary key values regardless
* of whether or not they have been modified.
*
* @return Criteria The Criteria object containing value(s) for primary key(s).
*/
public function buildPkeyCriteria ()
{
$criteria = new Criteria( AddonsStorePeer::DATABASE_NAME );
$criteria->add( AddonsStorePeer::STORE_ID, $this->store_id );
return $criteria;
}
/**
* Returns the primary key for this object (row).
*
* @return string
*/
public function getPrimaryKey ()
{
return $this->getStoreId();
}
/**
* Generic method to set the primary key (store_id column).
*
* @param string $key Primary key.
* @return void
*/
public function setPrimaryKey ($key)
{
$this->setStoreId( $key );
}
/**
* Sets contents of passed object to values from current object.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param object $copyObj An object of AddonsStore (or compatible) type.
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @throws PropelException
*/
public function copyInto ($copyObj, $deepCopy = false)
{
$copyObj->setStoreVersion( $this->store_version );
$copyObj->setStoreLocation( $this->store_location );
$copyObj->setStoreType( $this->store_type );
$copyObj->setStoreLastUpdated( $this->store_last_updated );
$copyObj->setNew( true );
$copyObj->setStoreId( null ); // this is a pkey column, so set to default value
}
/**
* Makes a copy of this object that will be inserted as a new row in table when saved.
* It creates a new object filling in the simple attributes, but skipping any primary
* keys that are defined for the table.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @return AddonsStore Clone of current object.
* @throws PropelException
*/
public function copy ($deepCopy = false)
{
// we use get_class(), because this might be a subclass
$clazz = get_class( $this );
$copyObj = new $clazz();
$this->copyInto( $copyObj, $deepCopy );
return $copyObj;
}
/**
* Returns a peer instance associated with this om.
*
* Since Peer classes are not to have any instance attributes, this method returns the
* same instance for all member of this class. The method could therefore
* be static, but this would prevent one from overriding the behavior.
*
* @return AddonsStorePeer
*/
public function getPeer ()
{
if (self::$peer === null) {
self::$peer = new AddonsStorePeer();
}
return self::$peer;
}
}

View File

@@ -0,0 +1,605 @@
<?php
require_once 'propel/util/BasePeer.php';
// The object class -- needed for instanceof checks in this class.
// actual class may be a subclass -- as returned by AddonsStorePeer::getOMClass()
include_once 'classes/model/AddonsStore.php';
/**
* Base static class for performing query and update operations on the 'ADDONS_STORE' table.
*
*
*
* @package workflow.classes.model.om
*/
abstract class BaseAddonsStorePeer
{
/**
* the default database name for this class
*/
const DATABASE_NAME = 'workflow';
/**
* the table name for this class
*/
const TABLE_NAME = 'ADDONS_STORE';
/**
* A class that can be returned by this peer.
*/
const CLASS_DEFAULT = 'classes.model.AddonsStore';
/**
* The total number of columns.
*/
const NUM_COLUMNS = 5;
/**
* The number of lazy-loaded columns.
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* the column name for the STORE_ID field
*/
const STORE_ID = 'ADDONS_STORE.STORE_ID';
/**
* the column name for the STORE_VERSION field
*/
const STORE_VERSION = 'ADDONS_STORE.STORE_VERSION';
/**
* the column name for the STORE_LOCATION field
*/
const STORE_LOCATION = 'ADDONS_STORE.STORE_LOCATION';
/**
* the column name for the STORE_TYPE field
*/
const STORE_TYPE = 'ADDONS_STORE.STORE_TYPE';
/**
* the column name for the STORE_LAST_UPDATED field
*/
const STORE_LAST_UPDATED = 'ADDONS_STORE.STORE_LAST_UPDATED';
/**
* The PHP to DB Name Mapping
*/
private static $phpNameMap = null;
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('StoreId','StoreVersion','StoreLocation','StoreType','StoreLastUpdated'),
BasePeer::TYPE_COLNAME => array (AddonsStorePeer::STORE_ID,AddonsStorePeer::STORE_VERSION,AddonsStorePeer::STORE_LOCATION,AddonsStorePeer::STORE_TYPE,AddonsStorePeer::STORE_LAST_UPDATED),
BasePeer::TYPE_FIELDNAME => array ('STORE_ID','STORE_VERSION','STORE_LOCATION','STORE_TYPE','STORE_LAST_UPDATED'),
BasePeer::TYPE_NUM => array (0,1,2,3,4)
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('StoreId' => 0,'StoreVersion' => 1,'StoreLocation' => 2,'StoreType' => 3,'StoreLastUpdated' => 4),
BasePeer::TYPE_COLNAME => array (AddonsStorePeer::STORE_ID => 0,AddonsStorePeer::STORE_VERSION => 1,AddonsStorePeer::STORE_LOCATION => 2,AddonsStorePeer::STORE_TYPE => 3,AddonsStorePeer::STORE_LAST_UPDATED => 4),
BasePeer::TYPE_FIELDNAME => array ('STORE_ID' => 0,'STORE_VERSION' => 1,'STORE_LOCATION' => 2,'STORE_TYPE' => 3,'STORE_LAST_UPDATED' => 4),
BasePeer::TYPE_NUM => array (0,1,2,3,4)
);
/**
*
* @return MapBuilder the map builder for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getMapBuilder ()
{
include_once 'classes/model/map/AddonsStoreMapBuilder.php';
return BasePeer::getMapBuilder( 'classes.model.map.AddonsStoreMapBuilder' );
}
/**
* Gets a map (hash) of PHP names to DB column names.
*
* @return array The PHP to DB name map for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @deprecated Use the getFieldNames() and translateFieldName() methods instead of this.
*/
public static function getPhpNameMap ()
{
if (self::$phpNameMap === null) {
$map = AddonsStorePeer::getTableMap();
$columns = $map->getColumns();
$nameMap = array ();
foreach ($columns as $column) {
$nameMap[$column->getPhpName()] = $column->getColumnName();
}
self::$phpNameMap = $nameMap;
}
return self::$phpNameMap;
}
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
*/
static public function translateFieldName ($name, $fromType, $toType)
{
$toNames = self::getFieldNames( $toType );
$key = isset( self::$fieldKeys[$fromType][$name] ) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException( "'$name' could not be found in the field names of type '$fromType'. These are: " . print_r( self::$fieldKeys[$fromType], true ) );
}
return $toNames[$key];
}
/**
* Returns an array of of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return array A list of field names
*/
static public function getFieldNames ($type = BasePeer::TYPE_PHPNAME)
{
if (! array_key_exists( $type, self::$fieldNames )) {
throw new PropelException( 'Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.' );
}
return self::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
*
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. AddonsStorePeer::COLUMN_NAME).
* @return string
*/
public static function alias ($alias, $column)
{
return str_replace( AddonsStorePeer::TABLE_NAME . '.', $alias . '.', $column );
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param criteria object containing the columns to add.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns (Criteria $criteria)
{
$criteria->addSelectColumn( AddonsStorePeer::STORE_ID );
$criteria->addSelectColumn( AddonsStorePeer::STORE_VERSION );
$criteria->addSelectColumn( AddonsStorePeer::STORE_LOCATION );
$criteria->addSelectColumn( AddonsStorePeer::STORE_TYPE );
$criteria->addSelectColumn( AddonsStorePeer::STORE_LAST_UPDATED );
}
const COUNT = 'COUNT(ADDONS_STORE.STORE_ID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT ADDONS_STORE.STORE_ID)';
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCount (Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array( Criteria::DISTINCT, $criteria->getSelectModifiers() )) {
$criteria->addSelectColumn( AddonsStorePeer::COUNT_DISTINCT );
} else {
$criteria->addSelectColumn( AddonsStorePeer::COUNT );
}
// just in case we're grouping: add those columns to the select statement
foreach ($criteria->getGroupByColumns() as $column) {
$criteria->addSelectColumn( $column );
}
$rs = AddonsStorePeer::doSelectRS( $criteria, $con );
if ($rs->next()) {
return $rs->getInt( 1 );
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Method to select one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param Connection $con
* @return AddonsStore
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne (Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit( 1 );
$objects = AddonsStorePeer::doSelect( $critcopy, $con );
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Method to do selects.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con
* @return array Array of selected Objects
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect (Criteria $criteria, $con = null)
{
return AddonsStorePeer::populateObjects( AddonsStorePeer::doSelectRS( $criteria, $con ) );
}
/**
* Prepares the Criteria object and uses the parent doSelect()
* method to get a ResultSet.
*
* Use this method directly if you want to just get the resultset
* (instead of an array of objects).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return ResultSet The resultset object with numerically-indexed fields.
* @see BasePeer::doSelect()
*/
public static function doSelectRS (Criteria $criteria, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
if (! $criteria->getSelectColumns()) {
$criteria = clone $criteria;
AddonsStorePeer::addSelectColumns( $criteria );
}
// Set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
// BasePeer returns a Creole ResultSet, set to return
// rows indexed numerically.
return BasePeer::doSelect( $criteria, $con );
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects (ResultSet $rs)
{
$results = array ();
// set the class once to avoid overhead in the loop
$cls = AddonsStorePeer::getOMClass();
$cls = Propel::import( $cls );
// populate the object(s)
while ($rs->next()) {
$obj = new $cls();
$obj->hydrate( $rs );
$results[] = $obj;
}
return $results;
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
*
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap ()
{
return Propel::getDatabaseMap( self::DATABASE_NAME )->getTable( self::TABLE_NAME );
}
/**
* The class that the Peer will make instances of.
*
* This uses a dot-path notation which is tranalted into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @return string path.to.ClassName
*/
public static function getOMClass ()
{
return AddonsStorePeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a AddonsStore or Criteria object.
*
* @param mixed $values Criteria or AddonsStore object containing data that is used to create the INSERT statement.
* @param Connection $con the connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert ($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from AddonsStore object
}
// Set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->begin();
$pk = BasePeer::doInsert( $criteria, $con );
$con->commit();
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
return $pk;
}
/**
* Method perform an UPDATE on the database, given a AddonsStore or Criteria object.
*
* @param mixed $values Criteria or AddonsStore object containing data that is used to create the UPDATE statement.
* @param Connection $con The connection to use (specify Connection object to exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate ($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$selectCriteria = new Criteria( self::DATABASE_NAME );
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison( AddonsStorePeer::STORE_ID );
$selectCriteria->add( AddonsStorePeer::STORE_ID, $criteria->remove( AddonsStorePeer::STORE_ID ), $comparison );
} else {
// $values is AddonsStore object
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
return BasePeer::doUpdate( $selectCriteria, $criteria, $con );
}
/**
* Method to DELETE all rows from the ADDONS_STORE table.
*
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll ($con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDeleteAll( AddonsStorePeer::TABLE_NAME, $con );
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a AddonsStore or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or AddonsStore object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param Connection $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete ($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( AddonsStorePeer::DATABASE_NAME );
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof AddonsStore) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria( self::DATABASE_NAME );
$criteria->add( AddonsStorePeer::STORE_ID, (array) $values, Criteria::IN );
}
// Set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDelete( $criteria, $con );
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Validates all modified columns of given AddonsStore object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param AddonsStore $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate (AddonsStore $obj, $cols = null)
{
$columns = array ();
if ($cols) {
$dbMap = Propel::getDatabaseMap( AddonsStorePeer::DATABASE_NAME );
$tableMap = $dbMap->getTable( AddonsStorePeer::TABLE_NAME );
if (! is_array( $cols )) {
$cols = array (
$cols);
}
foreach ($cols as $colName) {
if ($tableMap->containsColumn( $colName )) {
$get = 'get' . $tableMap->getColumn( $colName )->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
return BasePeer::doValidate( AddonsStorePeer::DATABASE_NAME, AddonsStorePeer::TABLE_NAME, $columns );
}
/**
* Retrieve a single object by pkey.
*
* @param mixed $pk the primary key.
* @param Connection $con the connection to use
* @return AddonsStore
*/
public static function retrieveByPK ($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$criteria = new Criteria( AddonsStorePeer::DATABASE_NAME );
$criteria->add( AddonsStorePeer::STORE_ID, $pk );
$v = AddonsStorePeer::doSelect( $criteria, $con );
return ! empty( $v ) > 0 ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function retrieveByPKs ($pks, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$objs = null;
if (empty( $pks )) {
$objs = array ();
} else {
$criteria = new Criteria();
$criteria->add( AddonsStorePeer::STORE_ID, $pks, Criteria::IN );
$objs = AddonsStorePeer::doSelect( $criteria, $con );
}
return $objs;
}
}
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
BaseAddonsStorePeer::getMapBuilder();
} catch (Exception $e) {
Propel::log( 'Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR );
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
require_once 'classes/model/map/AddonsStoreMapBuilder.php';
Propel::registerMapBuilder( 'classes.model.map.AddonsStoreMapBuilder' );
}

View File

@@ -0,0 +1,989 @@
<?php
require_once 'propel/om/BaseObject.php';
require_once 'propel/om/Persistent.php';
include_once 'propel/util/Criteria.php';
include_once 'classes/model/LicenseManagerPeer.php';
/**
* Base class that represents a row from the 'LICENSE_MANAGER' table.
*
*
* @package classes.model.om
*/
abstract class BaseLicenseManager extends BaseObject implements Persistent
{
/**
* The Peer class.
* Instance provides a convenient way of calling static methods on a class
* that calling code may not be able to identify.
*
* @var LicenseManagerPeer
*/
protected static $peer;
/**
* The value for the license_uid field.
*
* @var string
*/
protected $license_uid = '';
/**
* The value for the license_user field.
*
* @var string
*/
protected $license_user = '0';
/**
* The value for the license_start field.
*
* @var int
*/
protected $license_start = 0;
/**
* The value for the license_end field.
*
* @var int
*/
protected $license_end = 0;
/**
* The value for the license_span field.
*
* @var int
*/
protected $license_span = 0;
/**
* The value for the license_status field.
*
* @var string
*/
protected $license_status = '';
/**
* The value for the license_data field.
*
* @var string
*/
protected $license_data;
/**
* The value for the license_path field.
*
* @var string
*/
protected $license_path = '0';
/**
* The value for the license_workspace field.
*
* @var string
*/
protected $license_workspace = '0';
/**
* The value for the license_type field.
*
* @var string
*/
protected $license_type = '0';
/**
* Flag to prevent endless save loop, if this object is referenced
* by another object which falls in this transaction.
*
* @var boolean
*/
protected $alreadyInSave = false;
/**
* Flag to prevent endless validation loop, if this object is referenced
* by another object which falls in this transaction.
*
* @var boolean
*/
protected $alreadyInValidation = false;
/**
* Get the [license_uid] column value.
*
* @return string
*/
public function getLicenseUid ()
{
return $this->license_uid;
}
/**
* Get the [license_user] column value.
*
* @return string
*/
public function getLicenseUser ()
{
return $this->license_user;
}
/**
* Get the [license_start] column value.
*
* @return int
*/
public function getLicenseStart ()
{
return $this->license_start;
}
/**
* Get the [license_end] column value.
*
* @return int
*/
public function getLicenseEnd ()
{
return $this->license_end;
}
/**
* Get the [license_span] column value.
*
* @return int
*/
public function getLicenseSpan ()
{
return $this->license_span;
}
/**
* Get the [license_status] column value.
*
* @return string
*/
public function getLicenseStatus ()
{
return $this->license_status;
}
/**
* Get the [license_data] column value.
*
* @return string
*/
public function getLicenseData ()
{
return $this->license_data;
}
/**
* Get the [license_path] column value.
*
* @return string
*/
public function getLicensePath ()
{
return $this->license_path;
}
/**
* Get the [license_workspace] column value.
*
* @return string
*/
public function getLicenseWorkspace ()
{
return $this->license_workspace;
}
/**
* Get the [license_type] column value.
*
* @return string
*/
public function getLicenseType ()
{
return $this->license_type;
}
/**
* Set the value of [license_uid] column.
*
* @param string $v new value
* @return void
*/
public function setLicenseUid ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->license_uid !== $v || $v === '') {
$this->license_uid = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_UID;
}
} // setLicenseUid()
/**
* Set the value of [license_user] column.
*
* @param string $v new value
* @return void
*/
public function setLicenseUser ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->license_user !== $v || $v === '0') {
$this->license_user = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_USER;
}
} // setLicenseUser()
/**
* Set the value of [license_start] column.
*
* @param int $v new value
* @return void
*/
public function setLicenseStart ($v)
{
// Since the native PHP type for this column is integer,
// we will cast the input value to an int (if it is not).
if ($v !== null && ! is_int( $v ) && is_numeric( $v )) {
$v = (int) $v;
}
if ($this->license_start !== $v || $v === 0) {
$this->license_start = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_START;
}
} // setLicenseStart()
/**
* Set the value of [license_end] column.
*
* @param int $v new value
* @return void
*/
public function setLicenseEnd ($v)
{
// Since the native PHP type for this column is integer,
// we will cast the input value to an int (if it is not).
if ($v !== null && ! is_int( $v ) && is_numeric( $v )) {
$v = (int) $v;
}
if ($this->license_end !== $v || $v === 0) {
$this->license_end = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_END;
}
} // setLicenseEnd()
/**
* Set the value of [license_span] column.
*
* @param int $v new value
* @return void
*/
public function setLicenseSpan ($v)
{
// Since the native PHP type for this column is integer,
// we will cast the input value to an int (if it is not).
if ($v !== null && ! is_int( $v ) && is_numeric( $v )) {
$v = (int) $v;
}
if ($this->license_span !== $v || $v === 0) {
$this->license_span = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_SPAN;
}
} // setLicenseSpan()
/**
* Set the value of [license_status] column.
*
* @param string $v new value
* @return void
*/
public function setLicenseStatus ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->license_status !== $v || $v === '') {
$this->license_status = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_STATUS;
}
} // setLicenseStatus()
/**
* Set the value of [license_data] column.
*
* @param string $v new value
* @return void
*/
public function setLicenseData ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->license_data !== $v) {
$this->license_data = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_DATA;
}
} // setLicenseData()
/**
* Set the value of [license_path] column.
*
* @param string $v new value
* @return void
*/
public function setLicensePath ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->license_path !== $v || $v === '0') {
$this->license_path = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_PATH;
}
} // setLicensePath()
/**
* Set the value of [license_workspace] column.
*
* @param string $v new value
* @return void
*/
public function setLicenseWorkspace ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->license_workspace !== $v || $v === '0') {
$this->license_workspace = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_WORKSPACE;
}
} // setLicenseWorkspace()
/**
* Set the value of [license_type] column.
*
* @param string $v new value
* @return void
*/
public function setLicenseType ($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && ! is_string( $v )) {
$v = (string) $v;
}
if ($this->license_type !== $v || $v === '0') {
$this->license_type = $v;
$this->modifiedColumns[] = LicenseManagerPeer::LICENSE_TYPE;
}
} // setLicenseType()
/**
* Hydrates (populates) the object variables with values from the database resultset.
*
* An offset (1-based "start column") is specified so that objects can be hydrated
* with a subset of the columns in the resultset rows. This is needed, for example,
* for results of JOIN queries where the resultset row includes columns from two or
* more tables.
*
* @param ResultSet $rs The ResultSet class with cursor advanced to desired record pos.
* @param int $startcol 1-based offset column which indicates which restultset column to start with.
* @return int next starting column
* @throws PropelException - Any caught Exception will be rewrapped as a PropelException.
*/
public function hydrate (ResultSet $rs, $startcol = 1)
{
try {
$this->license_uid = $rs->getString( $startcol + 0 );
$this->license_user = $rs->getString( $startcol + 1 );
$this->license_start = $rs->getInt( $startcol + 2 );
$this->license_end = $rs->getInt( $startcol + 3 );
$this->license_span = $rs->getInt( $startcol + 4 );
$this->license_status = $rs->getString( $startcol + 5 );
$this->license_data = $rs->getString( $startcol + 6 );
$this->license_path = $rs->getString( $startcol + 7 );
$this->license_workspace = $rs->getString( $startcol + 8 );
$this->license_type = $rs->getString( $startcol + 9 );
$this->resetModified();
$this->setNew( false );
// FIXME - using NUM_COLUMNS may be clearer.
return $startcol + 10; // 10 = LicenseManagerPeer::NUM_COLUMNS - LicenseManagerPeer::NUM_LAZY_LOAD_COLUMNS).
} catch (Exception $e) {
throw new PropelException( "Error populating LicenseManager object", $e );
}
}
/**
* Removes this object from datastore and sets delete attribute.
*
* @param Connection $con
* @return void
* @throws PropelException
* @see BaseObject::setDeleted()
* @see BaseObject::isDeleted()
*/
public function delete ($con = null)
{
if ($this->isDeleted()) {
throw new PropelException( "This object has already been deleted." );
}
if ($con === null) {
$con = Propel::getConnection( LicenseManagerPeer::DATABASE_NAME );
}
try {
$con->begin();
LicenseManagerPeer::doDelete( $this, $con );
$this->setDeleted( true );
$con->commit();
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Stores the object in the database.
* If the object is new,
* it inserts it; otherwise an update is performed. This method
* wraps the doSave() worker method in a transaction.
*
* @param Connection $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see doSave()
*/
public function save ($con = null)
{
if ($this->isDeleted()) {
throw new PropelException( "You cannot save an object that has been deleted." );
}
if ($con === null) {
$con = Propel::getConnection( LicenseManagerPeer::DATABASE_NAME );
}
try {
$con->begin();
$affectedRows = $this->doSave( $con );
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Stores the object in the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All related objects are also updated in this method.
*
* @param Connection $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see save()
*/
protected function doSave ($con)
{
$affectedRows = 0; // initialize var to track total num of affected rows
if (! $this->alreadyInSave) {
$this->alreadyInSave = true;
// If this object has been modified, then save it to the database.
if ($this->isModified()) {
if ($this->isNew()) {
$pk = LicenseManagerPeer::doInsert( $this, $con );
$affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which
// should always be true here (even though technically
// BasePeer::doInsert() can insert multiple rows).
$this->setNew( false );
} else {
$affectedRows += LicenseManagerPeer::doUpdate( $this, $con );
}
$this->resetModified(); // [HL] After being saved an object is no longer 'modified'
}
$this->alreadyInSave = false;
}
return $affectedRows;
} // doSave()
/**
* Array of ValidationFailed objects.
*
* @var array ValidationFailed[]
*/
protected $validationFailures = array ();
/**
* Gets any ValidationFailed objects that resulted from last call to validate().
*
*
* @return array ValidationFailed[]
* @see validate()
*/
public function getValidationFailures ()
{
return $this->validationFailures;
}
/**
* Validates the objects modified field values and all objects related to this table.
*
* If $columns is either a column name or an array of column names
* only those columns are validated.
*
* @param mixed $columns Column name or an array of column names.
* @return boolean Whether all columns pass validation.
* @see doValidate()
* @see getValidationFailures()
*/
public function validate ($columns = null)
{
$res = $this->doValidate( $columns );
if ($res === true) {
$this->validationFailures = array ();
return true;
} else {
$this->validationFailures = $res;
return false;
}
}
/**
* This function performs the validation work for complex object models.
*
* In addition to checking the current object, all related objects will
* also be validated. If all pass then <code>true</code> is returned; otherwise
* an aggreagated array of ValidationFailed objects will be returned.
*
* @param array $columns Array of column names to validate.
* @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise.
*/
protected function doValidate ($columns = null)
{
if (! $this->alreadyInValidation) {
$this->alreadyInValidation = true;
$retval = null;
$failureMap = array ();
if (($retval = LicenseManagerPeer::doValidate( $this, $columns )) !== true) {
$failureMap = array_merge( $failureMap, $retval );
}
$this->alreadyInValidation = false;
}
return (! empty( $failureMap ) ? $failureMap : true);
}
/**
* Retrieves a field from the object by name passed in as a string.
*
* @param string $name name
* @param string $type The type of fieldname the $name is of:
* one of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return mixed Value of field.
*/
public function getByName ($name, $type = BasePeer::TYPE_PHPNAME)
{
$pos = LicenseManagerPeer::translateFieldName( $name, $type, BasePeer::TYPE_NUM );
return $this->getByPosition( $pos );
}
/**
* Retrieves a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @return mixed Value of field at $pos
*/
public function getByPosition ($pos)
{
switch ($pos) {
case 0:
return $this->getLicenseUid();
break;
case 1:
return $this->getLicenseUser();
break;
case 2:
return $this->getLicenseStart();
break;
case 3:
return $this->getLicenseEnd();
break;
case 4:
return $this->getLicenseSpan();
break;
case 5:
return $this->getLicenseStatus();
break;
case 6:
return $this->getLicenseData();
break;
case 7:
return $this->getLicensePath();
break;
case 8:
return $this->getLicenseWorkspace();
break;
case 9:
return $this->getLicenseType();
break;
default:
return null;
break;
}
}
/**
* Exports the object as an array.
*
* You can specify the key type of the array by passing one of the class
* type constants.
*
* @param string $keyType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return an associative array containing the field names (as keys) and field values
*/
public function toArray ($keyType = BasePeer::TYPE_PHPNAME)
{
$keys = LicenseManagerPeer::getFieldNames( $keyType );
$result = array (
$keys[0] => $this->getLicenseUid(),
$keys[1] => $this->getLicenseUser(),
$keys[2] => $this->getLicenseStart(),
$keys[3] => $this->getLicenseEnd(),
$keys[4] => $this->getLicenseSpan(),
$keys[5] => $this->getLicenseStatus(),
$keys[6] => $this->getLicenseData(),
$keys[7] => $this->getLicensePath(),
$keys[8] => $this->getLicenseWorkspace(),
$keys[9] => $this->getLicenseType()
);
return $result;
}
/**
* Sets a field from the object by name passed in as a string.
*
* @param string $name peer name
* @param mixed $value field value
* @param string $type The type of fieldname the $name is of:
* one of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return void
*/
public function setByName ($name, $value, $type = BasePeer::TYPE_PHPNAME)
{
$pos = LicenseManagerPeer::translateFieldName( $name, $type, BasePeer::TYPE_NUM );
return $this->setByPosition( $pos, $value );
}
/**
* Sets a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @param mixed $value field value
* @return void
*/
public function setByPosition ($pos, $value)
{
switch ($pos) {
case 0:
$this->setLicenseUid( $value );
break;
case 1:
$this->setLicenseUser( $value );
break;
case 2:
$this->setLicenseStart( $value );
break;
case 3:
$this->setLicenseEnd( $value );
break;
case 4:
$this->setLicenseSpan( $value );
break;
case 5:
$this->setLicenseStatus( $value );
break;
case 6:
$this->setLicenseData( $value );
break;
case 7:
$this->setLicensePath( $value );
break;
case 8:
$this->setLicenseWorkspace( $value );
break;
case 9:
$this->setLicenseType( $value );
break;
} // switch()
}
/**
* Populates the object using an array.
*
* This is particularly useful when populating an object from one of the
* request arrays (e.g. $_POST). This method goes through the column
* names, checking to see whether a matching key exists in populated
* array. If so the setByName() method is called for that column.
*
* You can specify the key type of the array by additionally passing one
* of the class type constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME,
* TYPE_NUM. The default key type is the column's phpname (e.g. 'authorId')
*
* @param array $arr An array to populate the object from.
* @param string $keyType The type of keys the array uses.
* @return void
*/
public function fromArray ($arr, $keyType = BasePeer::TYPE_PHPNAME)
{
$keys = LicenseManagerPeer::getFieldNames( $keyType );
if (array_key_exists( $keys[0], $arr )) {
$this->setLicenseUid( $arr[$keys[0]] );
}
if (array_key_exists( $keys[1], $arr )) {
$this->setLicenseUser( $arr[$keys[1]] );
}
if (array_key_exists( $keys[2], $arr )) {
$this->setLicenseStart( $arr[$keys[2]] );
}
if (array_key_exists( $keys[3], $arr )) {
$this->setLicenseEnd( $arr[$keys[3]] );
}
if (array_key_exists( $keys[4], $arr )) {
$this->setLicenseSpan( $arr[$keys[4]] );
}
if (array_key_exists( $keys[5], $arr )) {
$this->setLicenseStatus( $arr[$keys[5]] );
}
if (array_key_exists( $keys[6], $arr )) {
$this->setLicenseData( $arr[$keys[6]] );
}
if (array_key_exists( $keys[7], $arr )) {
$this->setLicensePath( $arr[$keys[7]] );
}
if (array_key_exists( $keys[8], $arr )) {
$this->setLicenseWorkspace( $arr[$keys[8]] );
}
if (array_key_exists( $keys[9], $arr )) {
$this->setLicenseType( $arr[$keys[9]] );
}
}
/**
* Build a Criteria object containing the values of all modified columns in this object.
*
* @return Criteria The Criteria object containing all modified values.
*/
public function buildCriteria ()
{
$criteria = new Criteria( LicenseManagerPeer::DATABASE_NAME );
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_UID )) {
$criteria->add( LicenseManagerPeer::LICENSE_UID, $this->license_uid );
}
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_USER )) {
$criteria->add( LicenseManagerPeer::LICENSE_USER, $this->license_user );
}
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_START )) {
$criteria->add( LicenseManagerPeer::LICENSE_START, $this->license_start );
}
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_END )) {
$criteria->add( LicenseManagerPeer::LICENSE_END, $this->license_end );
}
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_SPAN )) {
$criteria->add( LicenseManagerPeer::LICENSE_SPAN, $this->license_span );
}
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_STATUS )) {
$criteria->add( LicenseManagerPeer::LICENSE_STATUS, $this->license_status );
}
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_DATA )) {
$criteria->add( LicenseManagerPeer::LICENSE_DATA, $this->license_data );
}
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_PATH )) {
$criteria->add( LicenseManagerPeer::LICENSE_PATH, $this->license_path );
}
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_WORKSPACE )) {
$criteria->add( LicenseManagerPeer::LICENSE_WORKSPACE, $this->license_workspace );
}
if ($this->isColumnModified( LicenseManagerPeer::LICENSE_TYPE )) {
$criteria->add( LicenseManagerPeer::LICENSE_TYPE, $this->license_type );
}
return $criteria;
}
/**
* Builds a Criteria object containing the primary key for this object.
*
* Unlike buildCriteria() this method includes the primary key values regardless
* of whether or not they have been modified.
*
* @return Criteria The Criteria object containing value(s) for primary key(s).
*/
public function buildPkeyCriteria ()
{
$criteria = new Criteria( LicenseManagerPeer::DATABASE_NAME );
$criteria->add( LicenseManagerPeer::LICENSE_UID, $this->license_uid );
return $criteria;
}
/**
* Returns the primary key for this object (row).
*
* @return string
*/
public function getPrimaryKey ()
{
return $this->getLicenseUid();
}
/**
* Generic method to set the primary key (license_uid column).
*
* @param string $key Primary key.
* @return void
*/
public function setPrimaryKey ($key)
{
$this->setLicenseUid( $key );
}
/**
* Sets contents of passed object to values from current object.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param object $copyObj An object of LicenseManager (or compatible) type.
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @throws PropelException
*/
public function copyInto ($copyObj, $deepCopy = false)
{
$copyObj->setLicenseUser( $this->license_user );
$copyObj->setLicenseStart( $this->license_start );
$copyObj->setLicenseEnd( $this->license_end );
$copyObj->setLicenseSpan( $this->license_span );
$copyObj->setLicenseStatus( $this->license_status );
$copyObj->setLicenseData( $this->license_data );
$copyObj->setLicensePath( $this->license_path );
$copyObj->setLicenseWorkspace( $this->license_workspace );
$copyObj->setLicenseType( $this->license_type );
$copyObj->setNew( true );
$copyObj->setLicenseUid( '' ); // this is a pkey column, so set to default value
}
/**
* Makes a copy of this object that will be inserted as a new row in table when saved.
* It creates a new object filling in the simple attributes, but skipping any primary
* keys that are defined for the table.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @return LicenseManager Clone of current object.
* @throws PropelException
*/
public function copy ($deepCopy = false)
{
// we use get_class(), because this might be a subclass
$clazz = get_class( $this );
$copyObj = new $clazz();
$this->copyInto( $copyObj, $deepCopy );
return $copyObj;
}
/**
* Returns a peer instance associated with this om.
*
* Since Peer classes are not to have any instance attributes, this method returns the
* same instance for all member of this class. The method could therefore
* be static, but this would prevent one from overriding the behavior.
*
* @return LicenseManagerPeer
*/
public function getPeer ()
{
if (self::$peer === null) {
self::$peer = new LicenseManagerPeer();
}
return self::$peer;
}
}

View File

@@ -0,0 +1,647 @@
<?php
require_once 'propel/util/BasePeer.php';
// The object class -- needed for instanceof checks in this class.
// actual class may be a subclass -- as returned by LicenseManagerPeer::getOMClass()
include_once 'classes/model/LicenseManager.php';
/**
* Base static class for performing query and update operations on the 'LICENSE_MANAGER' table.
*
*
*
* @package classes.model.om
*/
abstract class BaseLicenseManagerPeer
{
/**
* the default database name for this class
*/
const DATABASE_NAME = 'workflow';
/**
* the table name for this class
*/
const TABLE_NAME = 'LICENSE_MANAGER';
/**
* A class that can be returned by this peer.
*/
const CLASS_DEFAULT = 'classes.model.LicenseManager';
/**
* The total number of columns.
*/
const NUM_COLUMNS = 10;
/**
* The number of lazy-loaded columns.
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* the column name for the LICENSE_UID field
*/
const LICENSE_UID = 'LICENSE_MANAGER.LICENSE_UID';
/**
* the column name for the LICENSE_USER field
*/
const LICENSE_USER = 'LICENSE_MANAGER.LICENSE_USER';
/**
* the column name for the LICENSE_START field
*/
const LICENSE_START = 'LICENSE_MANAGER.LICENSE_START';
/**
* the column name for the LICENSE_END field
*/
const LICENSE_END = 'LICENSE_MANAGER.LICENSE_END';
/**
* the column name for the LICENSE_SPAN field
*/
const LICENSE_SPAN = 'LICENSE_MANAGER.LICENSE_SPAN';
/**
* the column name for the LICENSE_STATUS field
*/
const LICENSE_STATUS = 'LICENSE_MANAGER.LICENSE_STATUS';
/**
* the column name for the LICENSE_DATA field
*/
const LICENSE_DATA = 'LICENSE_MANAGER.LICENSE_DATA';
/**
* the column name for the LICENSE_PATH field
*/
const LICENSE_PATH = 'LICENSE_MANAGER.LICENSE_PATH';
/**
* the column name for the LICENSE_WORKSPACE field
*/
const LICENSE_WORKSPACE = 'LICENSE_MANAGER.LICENSE_WORKSPACE';
/**
* the column name for the LICENSE_TYPE field
*/
const LICENSE_TYPE = 'LICENSE_MANAGER.LICENSE_TYPE';
/**
* The PHP to DB Name Mapping
*/
private static $phpNameMap = null;
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('LicenseUid','LicenseUser','LicenseStart','LicenseEnd','LicenseSpan','LicenseStatus','LicenseData','LicensePath','LicenseWorkspace','LicenseType'),
BasePeer::TYPE_COLNAME => array (LicenseManagerPeer::LICENSE_UID,LicenseManagerPeer::LICENSE_USER,LicenseManagerPeer::LICENSE_START,LicenseManagerPeer::LICENSE_END,LicenseManagerPeer::LICENSE_SPAN,LicenseManagerPeer::LICENSE_STATUS,LicenseManagerPeer::LICENSE_DATA,LicenseManagerPeer::LICENSE_PATH,LicenseManagerPeer::LICENSE_WORKSPACE,LicenseManagerPeer::LICENSE_TYPE),
BasePeer::TYPE_FIELDNAME => array ('LICENSE_UID','LICENSE_USER','LICENSE_START','LICENSE_END','LICENSE_SPAN','LICENSE_STATUS','LICENSE_DATA','LICENSE_PATH','LICENSE_WORKSPACE','LICENSE_TYPE'),
BasePeer::TYPE_NUM => array (0,1,2,3,4,5,6,7,8,9)
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('LicenseUid' => 0,'LicenseUser' => 1,'LicenseStart' => 2,'LicenseEnd' => 3,'LicenseSpan' => 4,'LicenseStatus' => 5,'LicenseData' => 6,'LicensePath' => 7,'LicenseWorkspace' => 8,'LicenseType' => 9),
BasePeer::TYPE_COLNAME => array (LicenseManagerPeer::LICENSE_UID => 0,LicenseManagerPeer::LICENSE_USER => 1,LicenseManagerPeer::LICENSE_START => 2,LicenseManagerPeer::LICENSE_END => 3,LicenseManagerPeer::LICENSE_SPAN => 4,LicenseManagerPeer::LICENSE_STATUS => 5,LicenseManagerPeer::LICENSE_DATA => 6,LicenseManagerPeer::LICENSE_PATH => 7,LicenseManagerPeer::LICENSE_WORKSPACE => 8,LicenseManagerPeer::LICENSE_TYPE => 9),
BasePeer::TYPE_FIELDNAME => array ('LICENSE_UID' => 0,'LICENSE_USER' => 1,'LICENSE_START' => 2,'LICENSE_END' => 3,'LICENSE_SPAN' => 4,'LICENSE_STATUS' => 5,'LICENSE_DATA' => 6,'LICENSE_PATH' => 7,'LICENSE_WORKSPACE' => 8,'LICENSE_TYPE' => 9),
BasePeer::TYPE_NUM => array (0,1,2,3,4,5,6,7,8,9)
);
/**
*
* @return MapBuilder the map builder for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getMapBuilder ()
{
include_once 'classes/model/map/LicenseManagerMapBuilder.php';
return BasePeer::getMapBuilder( 'classes.model.map.LicenseManagerMapBuilder' );
}
/**
* Gets a map (hash) of PHP names to DB column names.
*
* @return array The PHP to DB name map for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @deprecated Use the getFieldNames() and translateFieldName() methods instead of this.
*/
public static function getPhpNameMap ()
{
if (self::$phpNameMap === null) {
$map = LicenseManagerPeer::getTableMap();
$columns = $map->getColumns();
$nameMap = array ();
foreach ($columns as $column) {
$nameMap[$column->getPhpName()] = $column->getColumnName();
}
self::$phpNameMap = $nameMap;
}
return self::$phpNameMap;
}
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
*/
static public function translateFieldName ($name, $fromType, $toType)
{
$toNames = self::getFieldNames( $toType );
$key = isset( self::$fieldKeys[$fromType][$name] ) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException( "'$name' could not be found in the field names of type '$fromType'. These are: " . print_r( self::$fieldKeys[$fromType], true ) );
}
return $toNames[$key];
}
/**
* Returns an array of of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return array A list of field names
*/
static public function getFieldNames ($type = BasePeer::TYPE_PHPNAME)
{
if (! array_key_exists( $type, self::$fieldNames )) {
throw new PropelException( 'Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.' );
}
return self::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
*
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. LicenseManagerPeer::COLUMN_NAME).
* @return string
*/
public static function alias ($alias, $column)
{
return str_replace( LicenseManagerPeer::TABLE_NAME . '.', $alias . '.', $column );
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param criteria object containing the columns to add.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns (Criteria $criteria)
{
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_UID );
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_USER );
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_START );
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_END );
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_SPAN );
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_STATUS );
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_DATA );
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_PATH );
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_WORKSPACE );
$criteria->addSelectColumn( LicenseManagerPeer::LICENSE_TYPE );
}
const COUNT = 'COUNT(LICENSE_MANAGER.LICENSE_UID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT LICENSE_MANAGER.LICENSE_UID)';
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCount (Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array( Criteria::DISTINCT, $criteria->getSelectModifiers() )) {
$criteria->addSelectColumn( LicenseManagerPeer::COUNT_DISTINCT );
} else {
$criteria->addSelectColumn( LicenseManagerPeer::COUNT );
}
// just in case we're grouping: add those columns to the select statement
foreach ($criteria->getGroupByColumns() as $column) {
$criteria->addSelectColumn( $column );
}
$rs = LicenseManagerPeer::doSelectRS( $criteria, $con );
if ($rs->next()) {
return $rs->getInt( 1 );
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Method to select one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param Connection $con
* @return LicenseManager
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne (Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit( 1 );
$objects = LicenseManagerPeer::doSelect( $critcopy, $con );
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Method to do selects.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con
* @return array Array of selected Objects
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect (Criteria $criteria, $con = null)
{
return LicenseManagerPeer::populateObjects( LicenseManagerPeer::doSelectRS( $criteria, $con ) );
}
/**
* Prepares the Criteria object and uses the parent doSelect()
* method to get a ResultSet.
*
* Use this method directly if you want to just get the resultset
* (instead of an array of objects).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return ResultSet The resultset object with numerically-indexed fields.
* @see BasePeer::doSelect()
*/
public static function doSelectRS (Criteria $criteria, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
if (! $criteria->getSelectColumns()) {
$criteria = clone $criteria;
LicenseManagerPeer::addSelectColumns( $criteria );
}
// Set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
// BasePeer returns a Creole ResultSet, set to return
// rows indexed numerically.
return BasePeer::doSelect( $criteria, $con );
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects (ResultSet $rs)
{
$results = array ();
// set the class once to avoid overhead in the loop
$cls = LicenseManagerPeer::getOMClass();
$cls = Propel::import( $cls );
// populate the object(s)
while ($rs->next()) {
$obj = new $cls();
$obj->hydrate( $rs );
$results[] = $obj;
}
return $results;
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
*
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap ()
{
return Propel::getDatabaseMap( self::DATABASE_NAME )->getTable( self::TABLE_NAME );
}
/**
* The class that the Peer will make instances of.
*
* This uses a dot-path notation which is tranalted into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @return string path.to.ClassName
*/
public static function getOMClass ()
{
return LicenseManagerPeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a LicenseManager or Criteria object.
*
* @param mixed $values Criteria or LicenseManager object containing data that is used to create the INSERT statement.
* @param Connection $con the connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert ($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from LicenseManager object
}
// Set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->begin();
$pk = BasePeer::doInsert( $criteria, $con );
$con->commit();
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
return $pk;
}
/**
* Method perform an UPDATE on the database, given a LicenseManager or Criteria object.
*
* @param mixed $values Criteria or LicenseManager object containing data that is used to create the UPDATE statement.
* @param Connection $con The connection to use (specify Connection object to exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate ($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$selectCriteria = new Criteria( self::DATABASE_NAME );
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison( LicenseManagerPeer::LICENSE_UID );
$selectCriteria->add( LicenseManagerPeer::LICENSE_UID, $criteria->remove( LicenseManagerPeer::LICENSE_UID ), $comparison );
} else {
// $values is LicenseManager object
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
return BasePeer::doUpdate( $selectCriteria, $criteria, $con );
}
/**
* Method to DELETE all rows from the LICENSE_MANAGER table.
*
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll ($con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDeleteAll( LicenseManagerPeer::TABLE_NAME, $con );
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a LicenseManager or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or LicenseManager object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param Connection $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete ($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( LicenseManagerPeer::DATABASE_NAME );
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof LicenseManager) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria( self::DATABASE_NAME );
$criteria->add( LicenseManagerPeer::LICENSE_UID, (array) $values, Criteria::IN );
}
// Set the correct dbName
$criteria->setDbName( self::DATABASE_NAME );
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDelete( $criteria, $con );
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Validates all modified columns of given LicenseManager object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param LicenseManager $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate (LicenseManager $obj, $cols = null)
{
$columns = array ();
if ($cols) {
$dbMap = Propel::getDatabaseMap( LicenseManagerPeer::DATABASE_NAME );
$tableMap = $dbMap->getTable( LicenseManagerPeer::TABLE_NAME );
if (! is_array( $cols )) {
$cols = array (
$cols
);
}
foreach ($cols as $colName) {
if ($tableMap->containsColumn( $colName )) {
$get = 'get' . $tableMap->getColumn( $colName )->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
return BasePeer::doValidate( LicenseManagerPeer::DATABASE_NAME, LicenseManagerPeer::TABLE_NAME, $columns );
}
/**
* Retrieve a single object by pkey.
*
* @param mixed $pk the primary key.
* @param Connection $con the connection to use
* @return LicenseManager
*/
public static function retrieveByPK ($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$criteria = new Criteria( LicenseManagerPeer::DATABASE_NAME );
$criteria->add( LicenseManagerPeer::LICENSE_UID, $pk );
$v = LicenseManagerPeer::doSelect( $criteria, $con );
return ! empty( $v ) > 0 ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function retrieveByPKs ($pks, $con = null)
{
if ($con === null) {
$con = Propel::getConnection( self::DATABASE_NAME );
}
$objs = null;
if (empty( $pks )) {
$objs = array ();
} else {
$criteria = new Criteria();
$criteria->add( LicenseManagerPeer::LICENSE_UID, $pks, Criteria::IN );
$objs = LicenseManagerPeer::doSelect( $criteria, $con );
}
return $objs;
}
}
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
BaseLicenseManagerPeer::getMapBuilder();
} catch (Exception $e) {
Propel::log( 'Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR );
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
require_once 'classes/model/map/LicenseManagerMapBuilder.php';
Propel::registerMapBuilder( 'classes.model.map.LicenseManagerMapBuilder' );
}

View File

@@ -3811,9 +3811,51 @@
</table>
<table name="APP_TIMEOUT_ACTION_EXECUTED">
<column name="APP_UID" type="VARCHAR" size="32" required="true" default="" primaryKey="true" />
<column name="DEL_INDEX" type="INTEGER" required="true" default="0"/>
<column name="EXECUTION_DATE" type="TIMESTAMP" required="false"/>
<column name="APP_UID" type="VARCHAR" size="32" required="true" default="" primaryKey="true" />
<column name="DEL_INDEX" type="INTEGER" required="true" default="0"/>
<column name="EXECUTION_DATE" type="TIMESTAMP" required="false"/>
</table>
<table name="ADDONS_STORE">
<column name="STORE_ID" type="VARCHAR" size="32" primaryKey="true" />
<column name="STORE_VERSION" type="INTEGER" />
<column name="STORE_LOCATION" type="VARCHAR" size="2048" required="true" />
<column name="STORE_TYPE" type="VARCHAR" size="255" required="true" />
<column name="STORE_LAST_UPDATED" type="TIMESTAMP" />
</table>
<table name="ADDONS_MANAGER">
<column name="ADDON_ID" type="VARCHAR" size="255" required="true" primaryKey="true" />
<column name="STORE_ID" type="VARCHAR" size="32" required="true" primaryKey="true" />
<column name="ADDON_NAME" type="VARCHAR" size="255" required="true" />
<column name="ADDON_NICK" type="VARCHAR" size="255" required="true" />
<column name="ADDON_DOWNLOAD_FILENAME" type="VARCHAR" size="1024" required="false" />
<column name="ADDON_DESCRIPTION" type="VARCHAR" size="2048" required="false" />
<column name="ADDON_STATE" type="VARCHAR" size="255" required="true" />
<column name="ADDON_STATE_CHANGED" type="TIMESTAMP" required="false" />
<column name="ADDON_STATUS" type="VARCHAR" size="255" required="true" />
<column name="ADDON_VERSION" type="VARCHAR" size="255" required="true" />
<column name="ADDON_TYPE" type="VARCHAR" size="255" required="true" />
<column name="ADDON_PUBLISHER" type="VARCHAR" size="255" required="false" />
<column name="ADDON_RELEASE_DATE" type="TIMESTAMP" required="false" />
<column name="ADDON_RELEASE_TYPE" type="VARCHAR" size="255" required="false" />
<column name="ADDON_RELEASE_NOTES" type="VARCHAR" size="255" required="false" />
<column name="ADDON_DOWNLOAD_URL" type="VARCHAR" size="2048" required="false" />
<column name="ADDON_DOWNLOAD_PROGRESS" type="FLOAT" required="false" />
<column name="ADDON_DOWNLOAD_MD5" type="VARCHAR" size="32" required="false" />
</table>
<table name="LICENSE_MANAGER">
<column name="LICENSE_UID" type="VARCHAR" size="32" primaryKey="true" />
<column name="LICENSE_USER" type="VARCHAR" size="150" required="true" default="0"/>
<column name="LICENSE_START" type="INTEGER" required="true" default="0"/>
<column name="LICENSE_END" type="INTEGER" required="true" default="0"/>
<column name="LICENSE_SPAN" type="INTEGER" required="true" default="0"/>
<column name="LICENSE_STATUS" type="VARCHAR" size="100" required="true" default=""/>
<column name="LICENSE_DATA" type="LONGVARCHAR" required="true" />
<column name="LICENSE_PATH" type="VARCHAR" size="255" required="true" default="0"/>
<column name="LICENSE_WORKSPACE" type="VARCHAR" size="32" required="true" default="0"/>
<column name="LICENSE_TYPE" type="VARCHAR" size="32" required="true" default="0"/>
</table>
</database>

View File

@@ -101,4 +101,16 @@ if ($RBAC->userCanAccess("PM_SETUP") == 1) {
$G_TMP_MENU->AddIdRawOption("PM_REQUIREMENTS", "../setup/systemInfo", G::LoadTranslation("ID_PROCESSMAKER_REQUIREMENTS_CHECK"), "", "", "settings");
$G_TMP_MENU->AddIdRawOption("PHP_INFO", "../setup/systemInfo?option=php", G::LoadTranslation("ID_PHP_INFO"), "", "", "settings");
//$G_TMP_MENU->AddIdRawOption("PHP_MAINTENANCE", "../admin/maintenance", 'Maintenance', "", "", "settings");
}
}
require_once PATH_CORE . 'methods' . PATH_SEP . 'enterprise' . PATH_SEP . 'enterprise.php';
$enterprise = new enterprisePlugin('enterprise');
if (!file_exists(PATH_DATA_SITE . "plugin.singleton")) {
$enterprise->enable();
}
$enterprise->setup();

View File

@@ -0,0 +1,82 @@
<?php
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php';
require_once PATH_CORE . "classes" . PATH_SEP . "model" . PATH_SEP . "AddonsStore.php";
require_once PATH_CORE . "classes" . PATH_SEP . "class.enterpriseUtils.php";
AddonsStore::checkLicenseStore();
$licenseManager = &pmLicenseManager::getSingleton();
$oHeadPublisher = &headPublisher::getSingleton();
if (isset($licenseManager->date) && is_array($licenseManager->date)) {
G::LoadClass( "configuration" );
$conf = new Configurations();
if ( defined('SYS_SYS') && $conf->exists("ENVIRONMENT_SETTINGS")) {
$licenseManager->date['START'] = date("Y-m-d H:i:s", strtotime($licenseManager->date['HUMAN']['START']));
$licenseManager->date['END'] = date("Y-m-d H:i:s", strtotime($licenseManager->date['HUMAN']['END']));
$licenseManager->date['START'] = $conf->getSystemDate($licenseManager->date['START']);
$licenseManager->date['END'] = $conf->getSystemDate($licenseManager->date['END']);
} else {
$licenseManager->date['START'] = date("Y-m-d H:i:s", strtotime($licenseManager->date['HUMAN']['START']));
$licenseManager->date['END'] = date("Y-m-d H:i:s", strtotime($licenseManager->date['HUMAN']['END']));
$licenseManager->date['START'] = G::getformatedDate($licenseManager->date['START'], 'M d, yyyy', SYS_LANG);
$licenseManager->date['END'] = G::getformatedDate($licenseManager->date['END'], 'M d, yyyy', SYS_LANG);
}
}
if (isset($licenseManager->result) && $licenseManager->result == "OK") {
$oHeadPublisher->assign("license_start_date",$licenseManager->date["START"]);
$oHeadPublisher->assign("license_end_date", $licenseManager->expireIn!="NEVER" ? $licenseManager->date["END"]:"NA" );
$oHeadPublisher->assign("license_user", $licenseManager->info["FIRST_NAME"] . " " . $licenseManager->info["LAST_NAME"] . " (" . $licenseManager->info["DOMAIN_WORKSPACE"] . ")");
$oHeadPublisher->assign("license_span", $licenseManager->expireIn != "NEVER" ? ceil($licenseManager->date["SPAN"]/60/60/24) : "~");
$oHeadPublisher->assign("license_name", $licenseManager->type);
$oHeadPublisher->assign("license_server", $licenseManager->server);
$oHeadPublisher->assign("license_expires", $licenseManager->expireIn);
$oHeadPublisher->assign("license_message", $licenseManager->status["message"]);
$oHeadPublisher->assign("licensed", true);
}
elseif (isset($licenseManager->info)) {
$oHeadPublisher->assign("license_start_date", $licenseManager->date["START"]);
$oHeadPublisher->assign("license_end_date", $licenseManager->date["END"]);
$oHeadPublisher->assign("license_span", $licenseManager->expireIn != "NEVER" ? ceil($licenseManager->date["SPAN"]/60/60/24) : "~");
$oHeadPublisher->assign("license_user", $licenseManager->info["FIRST_NAME"] . " " . $licenseManager->info["LAST_NAME"] . " (" . $licenseManager->info["DOMAIN_WORKSPACE"] . ")");
$oHeadPublisher->assign("license_name", $licenseManager->type);
$oHeadPublisher->assign("license_server", $licenseManager->server);
$oHeadPublisher->assign("license_expires", $licenseManager->expireIn);
$oHeadPublisher->assign("license_message", $licenseManager->status["message"]);
$oHeadPublisher->assign("licensed", false);
} else {
$oHeadPublisher->assign("license_user", "");
$oHeadPublisher->assign("license_name", "<b>Unlicensed</b>");
$oHeadPublisher->assign("license_server", "<b>no server</b>");
$oHeadPublisher->assign("license_expires", "");
$currentLicenseStatus = $licenseManager->getCurrentLicenseStatus();
$oHeadPublisher->assign("license_message", $currentLicenseStatus["message"]);
$oHeadPublisher->assign("license_start_date", "");
$oHeadPublisher->assign("license_end_date", "");
$oHeadPublisher->assign("license_span", "");
$oHeadPublisher->assign("licensed", false);
}
$oHeadPublisher->assign("license_serial", (isset($licenseManager->licenseSerial))? $licenseManager->licenseSerial : '');
$oHeadPublisher->assign("SUPPORT_FLAG", ((isset($licenseManager->supportStartDate) && $licenseManager->supportStartDate == '') || !isset($licenseManager->supportStartDate)) ? true : false );
$oHeadPublisher->assign("supportStartDate", (isset($licenseManager->supportStartDate))? $licenseManager->supportStartDate : '');
$oHeadPublisher->assign("supportEndDate", (isset($licenseManager->supportEndDate))? $licenseManager->supportEndDate : '');
G::LoadClass("system");
$oHeadPublisher->assign("PROCESSMAKER_VERSION", System::getVersion());
$oHeadPublisher->assign("PROCESSMAKER_URL", "/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN );
$oHeadPublisher->assign("SYS_SKIN", SYS_SKIN);
$oHeadPublisher->assign("URL_PART_LOGIN", ((substr(SYS_SKIN, 0, 2) == "ux" && SYS_SKIN != "uxs")? "main/login" : "login/login"));
$oHeadPublisher->assign("URL_PART_SETUP", EnterpriseUtils::getUrlPartSetup());
$oHeadPublisher->assign("PATH_PLUGINS_WRITABLE", ((is_writable(PATH_PLUGINS))? 1 : 0));
$oHeadPublisher->assign("PATH_PLUGINS_WRITABLE_MESSAGE", "The directory " . PATH_PLUGINS . " have not writable.");
$oHeadPublisher->assign("SKIN_IS_UX", EnterpriseUtils::skinIsUx());
$oHeadPublisher->assign("INTERNET_CONNECTION", EnterpriseUtils::getInternetConnection());
$oHeadPublisher->addExtJsScript("enterprise/addonsStore", true);
G::RenderPage("publish", "extJs");

View File

@@ -0,0 +1,363 @@
<?php
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.enterpriseUtils.php';
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php';
require_once PATH_CORE . 'methods' . PATH_SEP . 'enterprise' . PATH_SEP . 'enterprise.php';
require_once PATH_CORE . 'classes' . PATH_SEP . 'model' . PATH_SEP . 'AddonsManagerPeer.php';
function runBgProcessmaker($task, $log)
{
require_once (PATH_CORE . "bin/tasks/cliAddons.php");
//require_once PATH_CORE . 'classes' . PATH_SEP . 'class.enterpriseUtils.php';
/*
$pmosFilename = PATH_TRUNK . "processmaker";
$cmd = "php -f \"$pmosFilename\" $task";
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $cmd, "r"));
}
else {
$str = system("$cmd 1> \"$log.log\" 2> \"$log.err\" < /dev/null &", $retval);
}
*/
$task = str_replace("\"", null, $task);
$data = explode(" ", $task);
$elem = array_shift($data); //delete first element
run_addon_install($data);
}
try {
if (isset($_REQUEST["action"])) {
$action = $_REQUEST["action"];
} else {
throw (new Exception("Action undefined"));
}
if (isset($_REQUEST['addon']) && isset($_REQUEST['store'])) {
require_once (PATH_CORE . 'classes/model/AddonsManagerPeer.php');
$addon = AddonsManagerPeer::retrieveByPK($_REQUEST['addon'], $_REQUEST['store']);
$addonId = $_REQUEST['addon'];
$storeId = $_REQUEST['store'];
if ($addon === null) {
throw (new Exception("Unable to find addon (id: '{$_REQUEST['addon']}', store: '{$_REQUEST['store']}')"));
}
} else {
$addon = null;
}
$result = array();
switch (strtolower($action)) {
case "importlicense":
if (sizeof($_FILES) > 0) {
$aInfoLoadFile = $_FILES["upLicense"];
$aExtentionFile = explode(".", $aInfoLoadFile["name"]);
//validating the extention before to upload it
if (trim($aExtentionFile[sizeof($aExtentionFile) - 1]) != "dat") {
//G::SendTemporalMessage("ID_ISNT_LICENSE", "tmp-info", "labels");
$result["errors"] = "Filename does not end with .dat";
$result["success"] = false;
} else {
$dir = PATH_DATA_SITE;
G::uploadFile($aInfoLoadFile["tmp_name"], $dir, $aInfoLoadFile["name"]);
//reading the file that was uploaded
$oPmLicenseManager = &pmLicenseManager::getSingleton();
$response = $oPmLicenseManager->installLicense($dir . $aInfoLoadFile["name"]);
///////
//This command also find the following file "AddonsStore.php"
$licenseManager = &pmLicenseManager::getSingleton();
preg_match("/^license_(.*).dat$/", $licenseManager->file, $matches);
$realId = urlencode($matches[1]);
$addonLocation = "http://{$licenseManager->server}/syspmLicenseSrv/en/green/services/addonsStore?action=getInfo&licId=$realId";
///////
$cnn = Propel::getConnection("workflow");
$oCriteriaSelect = new Criteria("workflow");
$oCriteriaSelect->add(AddonsStorePeer::STORE_ID, $licenseManager->id);
$oCriteriaUpdate = new Criteria("workflow");
$oCriteriaUpdate->add(AddonsStorePeer::STORE_ID, $licenseManager->id);
$oCriteriaUpdate->add(AddonsStorePeer::STORE_LOCATION, $addonLocation);
BasePeer::doUpdate($oCriteriaSelect, $oCriteriaUpdate, $cnn);
///////
//$licenseManager = &pmLicenseManager::getSingleton();
//plugin.singleton //are all the plugins that are enabled in the SYS_SYS
$pluginRegistry = &PMPluginRegistry::getSingleton();
$arrayAddon = array();
//ee //all plugins enterprise installed in /processmaker/workflow/engine/plugins (no matter if they are enabled/disabled)
if (file_exists(PATH_DATA_SITE . "ee")) {
$arrayAddon = unserialize(trim(file_get_contents(PATH_DATA_SITE . "ee")));
}
foreach ($arrayAddon as $addon) {
$sFileName = substr($addon["sFilename"], 0, strpos($addon["sFilename"], "-"));
if (file_exists(PATH_PLUGINS . $sFileName . ".php")) {
$addonDetails = $pluginRegistry->getPluginDetails($sFileName . ".php");
$enabled = 0;
if ($addonDetails) {
$enabled = ($addonDetails->enabled)? 1 : 0;
}
if ($enabled == 1 && !in_array($sFileName, $licenseManager->features)) {
require_once (PATH_PLUGINS . $sFileName . ".php");
$pluginRegistry->disablePlugin($sFileName);
}
}
}
file_put_contents(PATH_DATA_SITE . "plugin.singleton", $pluginRegistry->serializeInstance());
///////
$message = "A license has been correctly installed. Please login again to apply the changes";
G::SendMessageText($message, "INFO");
$_SESSION["___PMEE_INSTALLED_LIC___"] = $message;
//G::header("location: ../enterprise/pluginsList"); //ok
//exit(0);
}
}
break;
case "cancel":
if ($addon === null) {
throw new Exception("No addon specified to $action");
}
if ($addon->getAddonState() == "download") {
$addon->setState("cancel");
}
break;
case "uninstall":
$status = 1;
try {
if ($addon === null) {
throw new Exception("No addon specified to $action");
}
$r = $addon->uninstall();
$result["status"] = "OK";
} catch (Exception $e) {
$result["message"] = $e->getMessage();
$status = 0;
}
if ($status == 0) {
$result["status"] = "ERROR";
}
break;
case "finish":
if ($addon === null) {
throw new Exception("No addon specified to $action");
}
$addon->setState();
break;
case "disable":
case "enable":
if ($addon === null) {
throw new Exception("No addon specified to $action");
}
$result["success"] = $addon->setEnabled(($action == "enable"));
break;
case "install":
$status = 1;
try {
if (EnterpriseUtils::getInternetConnection() == 0) {
throw (new Exception("Enterprise Plugins Manager no connected to internet."));
}
///////
$aux = explode("?", $addon->getAddonDownloadUrl());
$url = $aux[0];
if (EnterpriseUtils::checkConnectivity($url) == false) {
throw (new Exception("Server $url not available."));
}
if ($addon === null) {
throw new Exception("No addon specified to $action");
}
///////
$workspace = SYS_SYS;
$dbAdapter = DB_ADAPTER;
$addon->setAddonState("download-start");
$addon->save();
$log = $addon->getDownloadDirectory() . "/download";
runBgProcessmaker("addon-install \"$workspace\" \"$storeId\" \"$addonId\" \"$dbAdapter\"", $log);
//Check if the background process started successfully.
$failed = false;
$max_retries = 15;
$retries = 0;
while (true) {
sleep(1);
$addon->refresh();
if ($addon->getAddonState() != "download-start") {
break;
}
//$logContents = file_get_contents("$log.log", false, NULL, 0, 10);
//if (!empty($logContents))
// break;
$retries += 1;
if ($retries > $max_retries) {
$failed = true;
break;
}
}
//if ($failed) {
// //$addon->clearState(); //clearState no found
// $result["success"] = false;
//}
$result["status"] = "OK";
} catch (Exception $e) {
$result["message"] = $e->getMessage();
$status = 0;
}
if ($status == 0) {
$result["status"] = "ERROR";
}
break;
case "available":
$addonId = $_POST["addonId"];
$response = array();
$status = 1;
try {
if (EnterpriseUtils::getInternetConnection() == 0) {
throw (new Exception("Enterprise Plugins Manager no connected to internet."));
}
///////
$licenseManager = &pmLicenseManager::getSingleton();
$server = $licenseManager->server;
$url = "http://$server/syspmLicenseSrv/en/green/services/rest";
if (EnterpriseUtils::checkConnectivity($url) == false) {
throw (new Exception("Server \"$server\" not available."));
}
///////
$boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
$data = null;
$data = $data . "--$boundary\n";
$data = $data . "Content-Disposition: form-data; name=\"action\"\n\n" . "requestToSales" . "\n";
$data = $data . "--$boundary\n";
$data = $data . "Content-Disposition: form-data; name=\"OBJ_NAME\"\n\n" . $addonId . "\n";
$data = $data . "--$boundary\n";
///////
//$licenseManager = &pmLicenseManager::getSingleton();
$activeLicense = $licenseManager->getActiveLicense();
$data = $data . "Content-Disposition: form-data; name=\"licenseFile\"; filename=\"" . $licenseManager->file . "\"\n";
$data = $data . "Content-Type: text/plain\n";
$data = $data . "Content-Transfer-Encoding: binary\n\n";
$data = $data . file_get_contents($activeLicense["LICENSE_PATH"]) . "\n";
$data = $data . "--$boundary\n";
///////
$option = array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: multipart/form-data; boundary=" . $boundary,
"content" => $data
)
);
// Proxy settings
$sysConf = System::getSystemConfiguration();
if ($sysConf['proxy_host'] != '') {
if (!is_array($option['http'])) {
$option['http'] = array();
}
$option['http']['request_fulluri'] = true;
$option['http']['proxy'] = 'tcp://' . $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '');
if ($sysConf['proxy_user'] != '') {
if (!isset($option['http']['header'])) {
$option['http']['header'] = '';
}
$option['http']['header'] .= 'Proxy-Authorization: Basic ' . base64_encode($sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
}
}
$context = stream_context_create($option);
///////
$fileData = file_get_contents($url, false, $context);
//////////
$r = G::json_decode($fileData);
if ($r->status == "OK") {
$response["status"] = $r->status; //OK
} else {
throw (new Exception($r->message));
}
} catch (Exception $e) {
$response["message"] = $e->getMessage();
$status = 0;
}
if ($status == 0) {
$response["status"] = "ERROR";
}
echo G::json_encode($response);
exit(0);
break;
case "addonslist":
$result = AddonsStore::addonList();
break;
default:
throw (new Exception("Action \"$action\" is not valid"));
}
if (!isset($result["success"])) {
$result["success"] = true;
}
if (isset($result["addons"])) {
$result["addons"] = array_values($result["addons"]);
} else {
$result["addons"] = array();
}
echo G::json_encode($result);
} catch (Exception $e) {
echo G::json_encode(array("success" => false, "errors" => $e->getMessage()));
}

View File

@@ -0,0 +1,364 @@
<?php
require_once ("classes/model/Configuration.php");
G::LoadClass("plugin");
if (!defined("PATH_PM_ENTERPRISE")) {
define("PATH_PM_ENTERPRISE", PATH_CORE . "enterprise/");
}
if (!defined("PATH_DATA_SITE")) {
define("PATH_DATA_SITE", PATH_DATA . "sites/" . SYS_SYS . "/");
}
set_include_path(PATH_PM_ENTERPRISE . PATH_SEPARATOR . get_include_path());
class enterprisePlugin extends PMPlugin
{
public function enterprisePlugin($sNamespace, $sFilename = null)
{
$pathPluginTrunk = PATH_CORE . "enterprise";
$VERSION = System::getVersion();
$res = parent::PMPlugin($sNamespace, $sFilename);
$this->sFriendlyName = "ProcessMaker Enterprise Edition";
$this->sDescription = "ProcessMaker Enterprise Edition $VERSION";
$this->sPluginFolder = "enterprise";
$this->sSetupPage = "../enterprise/pluginsList.php";
$this->iVersion = $VERSION;
$this->iPMVersion = "2.0.31";
$this->aDependences = null;
$this->aWorkspaces = null;
$this->database = "workflow";
$this->table = array("ADDONS_STORE", "ADDONS_MANAGER", "LICENSE_MANAGER");
if (!isset($_SESSION["__EE_INSTALLATION__"])) {
$_SESSION["__EE_INSTALLATION__"] = 0;
}
if (!isset($_SESSION["__EE_SW_PMLICENSEMANAGER__"])) {
$_SESSION["__EE_SW_PMLICENSEMANAGER__"] = 1;
}
$sw = 1;
$msgf = null;
$msgd = null;
if (file_exists(PATH_CORE . "plugins" . PATH_SEP . "pmLicenseManager.php")) {
$_SESSION["__EE_INSTALLATION__"] = 1;
$_SESSION["__EE_SW_PMLICENSEMANAGER__"] = 0;
$plugin = "pmLicenseManager";
$this->pluginUninstall($plugin);
if (file_exists(PATH_CORE . "plugins" . PATH_SEP . $plugin . ".php") || file_exists(PATH_CORE . "plugins" . PATH_SEP . $plugin)) {
$msgf = $msgf . (($msgf != null)? ", " : null) . $plugin . ".php";
$msgd = $msgd . (($msgd != null)? ", " : null) . $plugin;
$sw = 0;
}
$plugin = "enterprise";
$this->pluginUninstall($plugin);
if (file_exists(PATH_CORE . "plugins" . PATH_SEP . $plugin . ".php") || file_exists(PATH_CORE . "plugins" . PATH_SEP . $plugin)) {
$msgf = $msgf . (($msgf != null)? ", " : null) . $plugin . ".php";
$msgd = $msgd . (($msgd != null)? ", " : null) . $plugin;
$sw = 0;
}
$this->uninstall();
} else {
$_SESSION["__EE_INSTALLATION__"] = $_SESSION["__EE_INSTALLATION__"] + 1;
}
if ($sw == 0) {
unset($_SESSION["__EE_INSTALLATION__"]);
unset($_SESSION["__EE_SW_PMLICENSEMANAGER__"]);
///////
$js = "window.open(\"/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN . "/setup/main?s=PLUGINS\", \"_top\", \"\");";
if (substr(SYS_SKIN, 0, 2) == "ux" && SYS_SKIN != "uxs") {
//$js = "parent.window.location.href = \"/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN . "/setup/main_init?s=PLUGINS\";";
//$js = "window.location.href = \"/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN . "/setup/pluginsImport\";";
$js = "window.open(\"/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN . "/main\", \"_top\", \"\");";
}
///////
G::SendMessageText("ProcessMaker Enterprise plug-in can't delete the files \"$msgf\" and directories \"$msgd\" of \"" . (PATH_CORE . "plugins") . "\". Before proceeding with the installation of the plug-in must remove them.", "INFO");
echo "<script type=\"text/javascript\">" . $js . "</script>";
exit(0);
}
if ($_SESSION["__EE_SW_PMLICENSEMANAGER__"] == 0 && $_SESSION["__EE_INSTALLATION__"] == 2) {
unset($_SESSION["__EE_INSTALLATION__"]);
unset($_SESSION["__EE_SW_PMLICENSEMANAGER__"]);
$this->install();
}
///////
return $res;
}
public function install()
{
}
public function uninstall()
{
}
public function setup()
{
$urlPart = substr(SYS_SKIN, 0, 2) == 'ux' && SYS_SKIN != 'uxs' ? 'main/login' : 'login/login';
$this->registerMenu("setup", "menuEnterprise.php");
//including the file inside the enterprise folder
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php';
$this->registerTrigger(PM_LOGIN, "enterpriseSystemUpdate");
$licenseManager = &pmLicenseManager::getSingleton();
$oHeadPublisher = &headPublisher::getSingleton();
}
public function enable()
{
$this->setConfiguration();
$pluginRegistry = &PMPluginRegistry::getSingleton();
file_put_contents(PATH_DATA_SITE . "plugin.singleton", $pluginRegistry->serializeInstance());
require_once (PATH_CORE . 'classes/model/AddonsStore.php');
AddonsStore::checkLicenseStore();
$licenseManager = &pmLicenseManager::getSingleton();
AddonsStore::updateAll(false);
}
public function disable()
{
}
public function setConfiguration()
{
$confEeUid = "enterpriseConfiguration";
$criteria = new Criteria("workflow");
$criteria->addSelectColumn(ConfigurationPeer::CFG_VALUE);
$criteria->add(ConfigurationPeer::CFG_UID, "EE");
$criteria->add(ConfigurationPeer::OBJ_UID, $confEeUid);
$rsCriteria = ConfigurationPeer::doSelectRS($criteria);
if (!$rsCriteria->next()) {
$conf = new Configuration();
$data = array("internetConnection" => 1);
$conf->create(
array(
"CFG_UID" => "EE",
"OBJ_UID" => $confEeUid,
"CFG_VALUE" => serialize($data),
"PRO_UID" => "",
"USR_UID" => "",
"APP_UID" => ""
)
);
}
}
public function pluginUninstall($pluginName)
{
//define("PATH_PLUGINS", PATH_CORE . "plugins" . PATH_SEP);
if (file_exists(PATH_CORE . "plugins" . PATH_SEP . $pluginName . ".php")) {
require_once (PATH_CORE . "plugins" . PATH_SEP . $pluginName . ".php");
$pluginRegistry = &PMPluginRegistry::getSingleton();
$pluginDetail = $pluginRegistry->getPluginDetails($pluginName . ".php");
if ($pluginDetail) {
$pluginRegistry->enablePlugin($pluginDetail->sNamespace);
$pluginRegistry->disablePlugin($pluginDetail->sNamespace);
///////
$plugin = new $pluginDetail->sClassName($pluginDetail->sNamespace, $pluginDetail->sFilename);
//$this->_aPlugins[$pluginDetail->sNamespace] = $plugin;
if (method_exists($plugin, "uninstall")) {
$plugin->uninstall();
}
///////
file_put_contents(PATH_DATA_SITE . "plugin.singleton", $pluginRegistry->serializeInstance());
}
///////
unlink(PATH_CORE . "plugins" . PATH_SEP . $pluginName . ".php");
if (file_exists(PATH_CORE . "plugins" . PATH_SEP . $pluginName)) {
G::rm_dir(PATH_CORE . "plugins" . PATH_SEP . $pluginName);
}
}
}
public function registerEE($pluginFile, $pluginVersion)
{
if (file_exists(PATH_DATA_SITE . "ee")) {
$this->systemAvailable = unserialize(trim(file_get_contents(PATH_DATA_SITE . "ee")));
}
$this->systemAvailable[$pluginFile]["sFilename"] = $pluginFile . "-" . $pluginVersion . ".tar";
file_put_contents(PATH_DATA_SITE . "ee", serialize($this->systemAvailable));
return true;
}
public function checkDependencies()
{
}
public function tableBackup($tableBackup, $backupPrefix = "_", $backupSuffix = "_TEMP")
{
//Database Connections
$cnn = Propel::getConnection($this->database);
$stmt = $cnn->createStatement();
foreach ($tableBackup as $key => $table) {
$tablebak = $backupPrefix . $table . $backupSuffix;
//First Search if the Table exists
$sqlTable = "SHOW TABLES LIKE '$table'";
$rsTable = $stmt->executeQuery($sqlTable, ResultSet::FETCHMODE_ASSOC);
if ($rsTable->getRecordCount() > 0) {
//Table $table exists, so we can Backup
//If there are records in $table Backup
$sqlSelectTable = "SELECT * FROM $table";
$rsSelectTable = $stmt->executeQuery($sqlSelectTable, ResultSet::FETCHMODE_ASSOC);
if ($rsSelectTable->getRecordCount() > 0) {
//There are records in $table!! Backup!
//Delete a previous Backup if exists
$sql = "DROP TABLE IF EXISTS $tablebak;";
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
//Create a COPY of $table in $tablebak :: Backup
$sql = "CREATE TABLE $tablebak SELECT * FROM $table";
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
//Delete a previous $table if exists
$sql = "DROP TABLE IF EXISTS $table;";
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
}
}
}
}
public function tableBackupRestore($tableBackup, $backupPrefix = "_", $backupSuffix = "_TEMP")
{
//Database Connections
$cnn = Propel::getConnection($this->database);
$stmt = $cnn->createStatement();
foreach ($tableBackup as $key => $table) {
$tablebak = $backupPrefix . $table . $backupSuffix;
//First Search if the $tablebak exists
$sqlTablebak = "SHOW TABLES LIKE '$tablebak'";
$rsTablebak = $stmt->executeQuery($sqlTablebak, ResultSet::FETCHMODE_ASSOC);
if ($rsTablebak->getRecordCount() > 0) {
//Table $tablebak exists, so we can Restore
$sqlSelectTablebak = "SELECT * FROM $tablebak";
$rsSelectTablebak = $stmt->executeQuery($sqlSelectTablebak, ResultSet::FETCHMODE_ASSOC);
if ($rsSelectTablebak->getRecordCount() > 0) {
$strTable = str_replace("_", " ", strtolower($table));
$strTable = str_replace(" ", null, ucwords($strTable));
require_once (PATH_PLUGINS . "enterprise" . PATH_SEP . "classes" . PATH_SEP . "model" . PATH_SEP . "$strTable.php");
while ($rsSelectTablebak->next()) {
$row = $rsSelectTablebak->getRow();
//INSERT INTO TABLEN(FIELD1, FIELD2) VALUES('VALUE1', 'VALUE2')
$oTable = new $strTable();
$oTable->fromArray($row, BasePeer::TYPE_FIELDNAME); //Fill an object from of the array //Fill attributes
$oTable->save();
}
}
//Delete Backup
$sql = "DROP TABLE IF EXISTS $tablebak;";
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
}
}
}
/*
public function tableIsInstalled()
{
G::LoadSystem("database_" . DB_ADAPTER);
$database = new database(DB_ADAPTER, DB_HOST, DB_USER, DB_PASS, DB_NAME);
$cnn = Propel::getConnection($this->database);
$stmt = $cnn->createStatement();
$sw = true;
foreach ($this->table as $key => $table) {
$rs = $stmt->executeQuery($database->generateShowTablesLikeSQL($table), ResultSet::FETCHMODE_ASSOC);
if ($rs->getRecordCount() == 0) {
$sw = false;
}
}
return ($sw);
}
*/
public function sqlExecute($sqlFile)
{
$file = fopen($sqlFile, "r");
if ($file) {
$line = null;
while (!feof($file)) {
$buffer = trim(fgets($file, 4096)); //Read a line.
if (strlen($buffer) > 0 && $buffer[0] != "#") {
//Check for valid lines
$line = $line . $buffer;
if ($buffer[strlen($buffer) - 1] == ";") {
$cnn = Propel::getConnection($this->database);
$stmt = $cnn->createStatement();
$rs = $stmt->executeQuery($line, ResultSet::FETCHMODE_NUM);
$line = null;
}
}
}
fclose($file);
}
}
}
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$oPluginRegistry->registerPlugin('enterprise', __FILE__); //<- enterprise string must be in single quote, otherwise generate error
//since we are placing pmLicenseManager and EE together.. after register EE, we need to require_once the pmLicenseManager
//if( !defined("PATH_PM_LICENSE_MANAGER") ) {
// define("PATH_PM_LICENSE_MANAGER", PATH_CORE . "/plugins/pmLicenseManager/");
//}
//set_include_path(
// PATH_PM_LICENSE_MANAGER.PATH_SEPARATOR.
// get_include_path()
//);

View File

@@ -0,0 +1,70 @@
<?php
require_once ("classes/model/Configuration.php");
$option = (isset($_POST["option"]))? $_POST["option"] : null;
$response = array();
switch ($option) {
case "SETUP":
$swInternetConnection = intval($_POST["internetConnection"]);
$status = 1;
try {
$confEeUid = "enterpriseConfiguration";
$criteria = new Criteria("workflow");
$criteria->addSelectColumn(ConfigurationPeer::CFG_VALUE);
$criteria->add(ConfigurationPeer::CFG_UID, "EE");
$criteria->add(ConfigurationPeer::OBJ_UID, $confEeUid);
$rsCriteria = ConfigurationPeer::doSelectRS($criteria);
if ($rsCriteria->next()) {
$row = $rsCriteria->getRow();
$data = unserialize($row[0]);
$data["internetConnection"] = $swInternetConnection;
//Update values
$criteria1 = new Criteria("workflow");
$criteria1->add(ConfigurationPeer::CFG_UID, "EE");
$criteria1->add(ConfigurationPeer::OBJ_UID, $confEeUid);
//Update set
$criteria2 = new Criteria("workflow");
$criteria2->add(ConfigurationPeer::CFG_VALUE, serialize($data));
BasePeer::doUpdate($criteria1, $criteria2, Propel::getConnection("workflow"));
} else {
$conf = new Configuration();
$data = array("internetConnection" => $swInternetConnection);
$conf->create(
array(
"CFG_UID" => "EE",
"OBJ_UID" => $confEeUid,
"CFG_VALUE" => serialize($data),
"PRO_UID" => "",
"USR_UID" => "",
"APP_UID" => ""
)
);
}
$response["status"] = "OK";
} catch (Exception $e) {
$response["message"] = $e->getMessage();
$status = 0;
}
if ($status == 0) {
$response["status"] = "ERROR";
}
break;
}
echo G::json_encode($response);

View File

@@ -0,0 +1,31 @@
<?php
global $G_TMP_MENU;
if (class_exists("pmLicenseManager")) {
$pmLicenseManagerO = &pmLicenseManager::getSingleton();
$licenseStatusInfo = $pmLicenseManagerO->getCurrentLicenseStatus();
$licStatusMsg = null;
if ((isset($pmLicenseManagerO->plan)) && ($pmLicenseManagerO->plan != "")) {
$lines = explode(" - ", $pmLicenseManagerO->plan);
if (isset($lines[0])) {
$licStatusMsg .= "<br><i><small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $lines[0] . "</small></i>";
}
if ((isset($lines[1])) && ($lines[1] != $lines[0])) {
$licStatusMsg .= "<br><i><small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $lines[1] . "</small></i>";
}
}
if ($licenseStatusInfo["message"] != "") {
$licStatusMsg = "&nbsp;<font color=\"red\">(" . $licenseStatusInfo["message"] . ")</font>";
}
$G_TMP_MENU->AddIdRawOption("PMENTERPRISE", "../enterprise/addonsStore", "Enterprise Plugins Manager" . $licStatusMsg, "", "", "plugins");
if (isset($pmLicenseManagerO->result) && ($pmLicenseManagerO->result == "OK")) {
if (file_exists(PATH_HOME . "engine" . PATH_SEP . "methods" . PATH_SEP . "cases" . PATH_SEP . "casesListExtJs.php")) {
$G_TMP_MENU->AddIdRawOption("CASES_LIST_SETUP", "../enterprise/advancedTools/casesListSetup", "Cases Lists", "", "", "settings");
}
}
}

View File

@@ -0,0 +1,183 @@
<?php
/**
* processes_ImportFile.php
*
* ProcessMaker Open Source Edition
* Copyright (C) 2004 - 2008 Colosa Inc.23
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
* Coral Gables, FL, 33134, USA, or email info@colosa.com.
*
*/
global $RBAC;
$RBAC->requirePermissions("PM_SETUP_ADVANCE");
require_once PATH_CORE . 'methods' . PATH_SEP . 'enterprise' . PATH_SEP . 'enterprise.php';
$response = array();
$status = 1;
try {
//Load the variables
G::LoadClass("plugin");
if (!isset($_FILES["form"]["error"]["PLUGIN_FILENAME"]) || $_FILES["form"]["error"]["PLUGIN_FILENAME"] == 1) {
$str = "There was an error uploading the file, probably the file size if greater than upload_max_filesize parameter in php.ini, please check this parameter and try again.";
throw (new Exception($str));
}
//save the file
if ($_FILES["form"]["error"]["PLUGIN_FILENAME"] == 0) {
$filename = $_FILES["form"]["name"]["PLUGIN_FILENAME"];
$path = PATH_DOCUMENT . "input" . PATH_SEP ;
$tempName = $_FILES["form"]["tmp_name"]["PLUGIN_FILENAME"];
G::uploadFile($tempName, $path, $filename );
}
if (!$_FILES["form"]["type"]["PLUGIN_FILENAME"] == "application/octet-stream") {
$str = "the uploaded files are invalid, expected \"application/octect-stream\" mime type file (". $_FILES["form"]["type"]["PLUGIN_FILENAME"] . ")";
throw (new Exception($str));
}
G::LoadThirdParty("pear/Archive","Tar");
$tar = new Archive_Tar($path. $filename);
$sFileName = substr($filename, 0, strrpos($filename, "."));
$sClassName = substr($filename, 0, strpos($filename, "-"));
$aFiles = $tar->listContent();
$bMainFile = false;
$bClassFile = false;
if (is_array($aFiles)) {
foreach ($aFiles as $key => $val) {
if ($val["filename"] == $sClassName . ".php") {
$bMainFile = true;
}
if ($val["filename"] == $sClassName . PATH_SEP . "class." . $sClassName . ".php") {
$bClassFile = true;
}
}
} else {
$str = "Failed to import the file default by doesn't a plugin or invalid file.";
throw (new Exception($str));
}
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$pluginFile = $sClassName . '.php';
if ($bMainFile && $bClassFile) {
$sAux = $sClassName . 'Plugin';
$fVersionOld = 0.0;
if (file_exists(PATH_PLUGINS . $pluginFile)) {
if (!class_exists($sAux) && !class_exists($sClassName . 'plugin')) {
include PATH_PLUGINS . $pluginFile;
}
if (!class_exists($sAux)) {
$sAux = $sClassName . 'plugin';
}
$oClass = new $sAux($sClassName);
$fVersionOld = $oClass->iVersion;
unset($oClass);
}
$res = $tar->extract($path);
$sContent = file_get_contents($path . $pluginFile);
$sContent = str_ireplace($sAux, $sAux . '_', $sContent);
$sContent = str_ireplace('PATH_PLUGINS', "'".$path."'", $sContent);
$sContent = preg_replace("/\\\$oPluginRegistry\s*=\s*&\s*PMPluginRegistry::getSingleton\s*\(\s*\)\s*;/i", null, $sContent);
$sContent = preg_replace("/\\\$oPluginRegistry->registerPlugin\s*\(\s*[\"\']" . $sClassName . "[\"\']\s*,\s*__FILE__\s*\)\s*;/i", null, $sContent);
//header('Content-Type: text/plain');var_dump($sClassName, $sContent);die;
file_put_contents($path . $pluginFile, $sContent);
$sAux = $sAux . '_';
include ($path . $pluginFile);
$oClass = new $sAux($sClassName);
$fVersionNew = $oClass->iVersion;
if (!isset($oClass->iPMVersion)) {
$oClass->iPMVersion = 0;
}
//if ($oClass->iPMVersion > 0) {
// G::LoadClass("system");
// if (System::getVersion() > 0) {
// if ($oClass->iPMVersion > System::getVersion()) {
// //throw new Exception('This plugin needs version ' . $oClass->iPMVersion . ' or higher of ProcessMaker');
// }
// }
//}
/*
if (!isset($oClass->aDependences)) {
$oClass->aDependences = null;
}
if (!empty($oClass->aDependences)) {
foreach ($oClass->aDependences as $aDependence) {
if (file_exists(PATH_PLUGINS . $aDependence['sClassName'] . '.php')) {
require_once PATH_PLUGINS . $aDependence['sClassName'] . '.php';
if (!$oPluginRegistry->getPluginDetails($aDependence['sClassName'] . '.php')) {
throw new Exception('This plugin needs "' . $aDependence['sClassName'] . '" plugin');
}
} else {
throw new Exception('This plugin needs "' . $aDependence['sClassName'] . '" plugin');
}
}
}
unset($oClass);
if ($fVersionOld > $fVersionNew) {
throw new Exception('A recent version of this plugin was already installed.');
}
*/
$res = $tar->extract(PATH_PLUGINS);
} else {
$str = "The file $filename doesn't contain class: $sClassName ";
throw (new Exception($str));
}
if (! file_exists(PATH_PLUGINS . $sClassName . '.php')) {
$str = "File '$pluginFile' doesn't exists ";
throw (new Exception($str));
}
require_once (PATH_PLUGINS . $pluginFile);
$oPluginRegistry->registerPlugin($sClassName, PATH_PLUGINS . $sClassName . ".php");
$details = $oPluginRegistry->getPluginDetails($pluginFile);
$oPluginRegistry->installPlugin($details->sNamespace);
$oPluginRegistry->setupPlugins(); //get and setup enabled plugins
$size = file_put_contents(PATH_DATA_SITE . "plugin.singleton", $oPluginRegistry->serializeInstance());
//G::header("Location: pluginsList");
//die;
$response["success"] = true;
} catch (Exception $e) {
$response["message"] = $e->getMessage();
$status = 0;
}
if ($status == 0) {
$response["success"] = false;
}
echo G::json_encode($response);

View File

@@ -0,0 +1,369 @@
<?php
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php';
require_once PATH_CORE . 'classes' . PATH_SEP . 'class.enterpriseUtils.php';
ini_set("max_execution_time", 0);
if (!defined("PM_VERSION")) {
if (file_exists(PATH_METHODS . "login/version-pmos.php")) {
include (PATH_METHODS . "login/version-pmos.php");
} else {
define("PM_VERSION", "2.0.0");
}
}
if (!defined("BUFSIZE")) {
define("BUFSIZE", 16384);
}
function install($file)
{
G::LoadThirdParty("pear/Archive", "Tar");
$result = array();
$status = 1;
try {
//Extract
$tar = new Archive_Tar($file);
$swTar = $tar->extract(PATH_OUTTRUNK); //true on success, false on error. //directory for extract
//$swTar = $tar->extract(PATH_PLUGINS);
if (!$swTar) {
throw (new Exception("Could not extract file."));
}
//Upgrade
$option = array(
"http" => array(
"method" => "POST"
)
);
// Proxy settings
$sysConf = System::getSystemConfiguration();
if (isset($sysConf['proxy_host'])) {
if ($sysConf['proxy_host'] != '') {
if (!is_array($option['http'])) {
$option['http'] = array();
}
$option['http']['request_fulluri'] = true;
$option['http']['proxy'] = 'tcp://' . $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '');
if ($sysConf['proxy_user'] != '') {
if (!isset($option['http']['header'])) {
$option['http']['header'] = '';
}
$option['http']['header'] .= 'Proxy-Authorization: Basic ' . base64_encode($sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
}
}
}
$context = stream_context_create($option);
///////
$fileData = @fopen(EnterpriseUtils::getUrlServerName() . "/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN . "/enterprise/services/processMakerUpgrade", "rb", false, $context);
if ($fileData === false) {
throw (new Exception("Could not open services url."));
}
$resultAux = G::json_decode(stream_get_contents($fileData));
if ($resultAux->status == "OK") {
$result["status"] = $resultAux->status; //OK
$result["message"] = $resultAux->message;
} else {
throw (new Exception($resultAux->message));
}
} catch (Exception $e) {
$result["message"] = $e->getMessage();
$status = 0;
}
if ($status == 0) {
$result["status"] = "ERROR";
}
return $result;
}
$option = (isset($_POST["option"]))? $_POST["option"] : null;
switch ($option) {
case "install":
$uid = $_POST["uid"];
$version = $_POST["version"];
$versionName = $_POST["versionName"];
$processMakerVersion = $_POST["processMakerVersion"];
$response = array();
$status = 1;
try {
if (EnterpriseUtils::getInternetConnection() == 0) {
throw (new Exception("Enterprise Plugins Manager no connected to internet."));
}
///////
$versionName = EnterpriseUtils::pmVersion($versionName);
$processMakerVersion = EnterpriseUtils::pmVersion($processMakerVersion);
if (!version_compare($processMakerVersion . "", $versionName . "", "<")) {
throw (new Exception("The system can't be upgraded to a previous version."));
}
///////
$licenseManager = &pmLicenseManager::getSingleton();
$server = isset($licenseManager->server) ? $licenseManager->server : '';
$url = "http://$server/syspmLicenseSrv/en/green/services/rest";
if (EnterpriseUtils::checkConnectivity($url) == false) {
throw (new Exception("Server '$server' not available."));
}
///////
$boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
$data = null;
$data = $data . "--$boundary\n";
$data = $data . "Content-Disposition: form-data; name=\"action\"\n\n" . "getPM" . "\n";
$data = $data . "--$boundary\n";
$data = $data . "Content-Disposition: form-data; name=\"OBJ_UID\"\n\n" . $uid . "\n";
$data = $data . "--$boundary\n";
$data = $data . "Content-Disposition: form-data; name=\"OBJ_VERSION\"\n\n" . $version . "\n";
$data = $data . "--$boundary\n";
$option = array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: multipart/form-data; boundary=" . $boundary,
"content" => $data
)
);
// Proxy settings
$sysConf = System::getSystemConfiguration();
if (isset($sysConf['proxy_host'])) {
if ($sysConf['proxy_host'] != '') {
if (!is_array($option['http'])) {
$option['http'] = array();
}
$option['http']['request_fulluri'] = true;
$option['http']['proxy'] = 'tcp://' . $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '');
if ($sysConf['proxy_user'] != '') {
if (!isset($option['http']['header'])) {
$option['http']['header'] = '';
}
$option['http']['header'] .= 'Proxy-Authorization: Basic ' . base64_encode($sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
}
}
}
$context = stream_context_create($option);
///////
$fileData = @fopen($url, "rb", false, $context);
if ($fileData === false) {
throw (new Exception("Could not open download url."));
}
//Try to get the download size and filename (ok if it fails)
$meta = stream_get_meta_data($fileData);
$fileName = null;
$fileContentType = null;
$fileLength = 0;
if ($meta["wrapper_type"] == "http") {
foreach ($meta["wrapper_data"] as $info) {
$info = explode(":", $info);
$infoVariable = (isset($info[0]))? trim($info[0]) : null;
$infoValue = (isset($info[1]))? trim($info[1]) : null;
if (preg_match("/^.*Content-Type.*$/", $infoVariable)) {
$fileContentType = $infoValue;
}
if (strcasecmp($infoVariable, "Content-Length") == 0) {
$fileLength = intval($infoValue);
}
if (strcasecmp($infoVariable, "Content-Disposition") == 0) {
foreach (explode(";", $infoValue) as $params) {
$params = explode("=", $params);
if (count($params) <= 1) {
continue;
}
if (strcasecmp(trim($params[0]), "filename") == 0) {
$fileName = trim($params[1], "\" ");
}
}
}
}
}
if (preg_match("/^.*json.*$/i", $fileContentType)) {
$r = G::json_decode(stream_get_contents($fileData));
if ($r->status == "ERROR") {
throw (new Exception($r->message));
}
}
///////
$dir = PATH_DATA . "upgrade" . PATH_SEP . "processmaker";
G::rm_dir($dir);
G::mk_dir($dir);
if (!file_exists($dir)) {
throw (new Exception("Could not create destination directory."));
}
///////
$fileName = $dir . PATH_SEP . $fileName;
$file = @fopen($fileName, "wb");
if ($file === false) {
throw (new Exception("Could not open destination file."));
}
while (!feof($fileData)) {
$data = fread($fileData, BUFSIZE);
//Just to be safe, check all error conditions
if ($data === "" || $data === false) {
break;
}
if (fwrite($file, $data) === false) {
break;
}
}
fclose($file);
fclose($fileData);
///////
$path = PATH_TRUNK;
//$path = PATH_OUTTRUNK;
if (EnterpriseUtils::checkFolderPermissions($path, true) == false) {
$str = $path . " " . "directory, its sub-directories or file is not writable. Read the wiki for <a href=\"http://wiki.processmaker.com/index.php/Upgrading_ProcessMaker\" onclick=\"window.open(this.href, \'_blank\'); return (false);\">Upgrading ProcessMaker</a>.<br /> The file is downloaded in " . $fileName . "<br />";
throw (new Exception($str));
}
///////
$result = install($fileName);
if ($result["status"] == "OK") {
$response["status"] = $result["status"]; //OK
$response["message"] = $result["message"];
} else {
throw (new Exception($result["message"]));
}
} catch (Exception $e) {
$response["message"] = $e->getMessage();
$status = 0;
}
if ($status == 0) {
$response["status"] = "ERROR";
}
echo G::json_encode($response);
break;
case "list":
$status = 1;
try {
if (EnterpriseUtils::getInternetConnection() == 0) {
throw (new Exception("Enterprise Plugins Manager no connected to internet."));
}
///////
$licenseManager = &pmLicenseManager::getSingleton();
$server = (isset($licenseManager->server)) ? $licenseManager->server : '';
$url = "http://$server/syspmLicenseSrv/en/green/services/rest";
if (EnterpriseUtils::checkConnectivity($url) == false) {
throw (new Exception("Server '$server' not available."));
}
///////
$option = array(
"http" => array(
"method" => "POST",
"header" => "Content-type: application/x-www-form-urlencoded\r\n",
"content" => http_build_query(
array(
"action" => "getPMList"
)
)
)
);
// Proxy settings
$sysConf = System::getSystemConfiguration();
if (isset($sysConf['proxy_host'])) {
if ($sysConf['proxy_host'] != '') {
if (!is_array($option['http'])) {
$option['http'] = array();
}
$option['http']['request_fulluri'] = true;
$option['http']['proxy'] = 'tcp://' . $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '');
if ($sysConf['proxy_user'] != '') {
if (!isset($option['http']['header'])) {
$option['http']['header'] = '';
}
$option['http']['header'] .= 'Proxy-Authorization: Basic ' . base64_encode($sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
}
}
}
$context = stream_context_create($option);
$results = file_get_contents($url, false, $context);
$results = G::json_decode($results);
$results = $results[0];
$pmVersion = EnterpriseUtils::pmVersion(PM_VERSION);
$versions = array();
foreach ($results as $key => $result) {
$version = EnterpriseUtils::pmVersion($result->OBJ_VERSION_NAME);
if (version_compare($pmVersion . "", $version . "", "<")) {
$versions[] = $result;
}
}
if (isset($results[0])) {
$results[0]->OBJ_VERSION_NAME .= " (Stable)";
}
$response->status = "OK";
$response->results = $versions;
} catch (Exception $e) {
$response->message = $e->getMessage();
$status = 0;
}
if ($status == 0) {
$response->status = "ERROR";
}
echo G::json_encode($response);
break;
}

View File

@@ -1679,3 +1679,104 @@ padding:3px 3px 3px 5px;
white-space:normal;
}
/**
* Cases Interface styles
*/
.ICON_PMENTERPRISE {
background-image: url(/images/icon-pmlogo-15x15.png) !important;
}
.ICON_ADDONSSTORE {
background-image: url(/images/enterprise/store-medium.png) !important;
}
.msg .x-box-mc {
font-size:14px;
}
#msg-div {
position:absolute;
left:35%;
top:10px;
width:250px;
z-index:20000;
}
.x-form-display-field {
padding: 3px !important;
}
.download-start {
background-color: #fff !important;
}
.download {
background-color: #333333 !important;
/*padding-left: 17px !important;*/
background-image: url(/images/enterprise/loader-black.gif);
background-repeat: no-repeat;
background-position: 2px center;
}
.install {
background-color: #333333 !important;
/*padding-left: 17px !important;*/
background-image: url(/images/enterprise/loader-black.gif);
background-repeat: no-repeat;
background-position: 2px center;
}
.installed {
background-color: #959595 !important;
/*background-image: url(tick-circle-frame.png);*/
background-repeat: no-repeat;
background-position: 2px center;
}
.disabled {
background-color: #959595 !important;
/* background-image: url(minus-circle-frame.png);*/
background-repeat: no-repeat;
background-position: 2px center;
}
.upgrade {
background-color: #1da001 !important;
/* background-image: url(wooden-box--exclamation.png);*/
background-repeat: no-repeat;
background-position: 2px center;
}
.ready {
background-color: #1da001 !important;
/* background-image: url(wooden-box--plus.png);*/
background-repeat: no-repeat;
background-position: 2px center;
}
.available {
background-color: #ee2a0d !important;
/* background-image: url(store--plus.png);*/
background-repeat: no-repeat;
background-position: 2px center;
}
.roundedCorners{
width: 100px;
padding: 2px;
/*border:1px solid #DDEEF6;*/
background-color: #fffb00;
text-align: center;
text-shadow: 0 1px 0 #444444;
color: #FFFFFF !important;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
vertical-align: middle;
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 774 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 886 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 886 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 729 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 728 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 539 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 734 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 734 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 756 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 651 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 691 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 741 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 619 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 622 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 703 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 734 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 508 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 689 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 847 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 756 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 849 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 655 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 889 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 711 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 624 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 774 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 717 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 905 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 724 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 744 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 415 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 687 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 613 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 559 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 B