initial commit from rev. 632

This commit is contained in:
Erik Amaru Ortiz
2010-12-02 23:34:41 +00:00
commit 0525681d79
5410 changed files with 864427 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
<?php
/**
* commands.php
*
* ProcessMaker Open Source Edition
* Copyright (C) 2010 Colosa Inc.
*
* 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.
*
*/
/* Windows supports both / and \ as path separators, so use the Unix separator
* for maximum compatibility.
*/
define('PATH_SEP', '/');
define('PATH_HOME', WORKFLOW_PATH );
define('PATH_TRUNK', PROCESSMAKER_PATH );
define('PATH_OUTTRUNK', realpath(PROCESSMAKER_PATH.'/..') );
/* Most definitions (including the G class) is done in paths.php
* This mostly simulates a sysGeneric.php call.
*/
if (file_exists(PATH_HOME . 'engine/config/paths_installed.php'))
require_once(PATH_HOME . 'engine/config/paths_installed.php');
require_once ( PATH_HOME . 'engine/config/paths.php' );
require_once( PATH_THIRDPARTY . 'pake/pakeFunction.php');
require_once( PATH_THIRDPARTY . 'pake/pakeGetopt.class.php');
require_once( PATH_CORE . 'config/environments.php');
// register tasks
$dir = PATH_HOME . 'engine/bin/commands';
$tasks = pakeFinder::type('file')->name( 'cmd*.php' )->in($dir);
foreach ($tasks as $task) {
include_once($task);
}
// run task
pakeApp::get_instance()->run(null, null, false);
exit(0);
?>

View File

@@ -0,0 +1,90 @@
<?php
pake_task('drafts-clean');
function delete_app_from_table($con, $tableName, $appUid, $col="APP_UID") {
$stmt = $con->createStatement();
$sql = "DELETE FROM " . $tableName . " WHERE " . $col . "='" . $appUid . "'";
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_NUM);
}
function run_drafts_clean($task, $args)
{
echo "Cleaning drafts\n";
if (count($args) < 1)
throw new Exception ("Please specify a workspace name");
$workspace = $args[0];
if (!file_exists(PATH_DB . $workspace . '/db.php')) {
throw new Exception('Could not find workspace ' . $workspace);
}
$allDrafts = false;
if (count($args) < 2) {
echo "Cases older them this much days will be deleted (ENTER for all): ";
$days = rtrim( fgets( STDIN ), "\n" );
if ($days == "") {
$allDrafts = true;
}
} else {
$days = $args[1];
if (strcmp($days, "all") == 0) {
$allDrafts = true;
}
}
if (!$allDrafts && (!is_numeric($days) || intval($days) <= 0)) {
throw new Exception("Days value is not valid: " . $days);
}
if ($allDrafts)
echo "Removing all drafts\n";
else
echo "Removing drafts older than " . $days . " days\n";
/* Load the configuration from the workspace */
require_once( PATH_DB . $workspace . '/db.php' );
require_once( PATH_THIRDPARTY . 'propel/Propel.php');
PROPEL::Init ( PATH_METHODS.'dbConnections/rootDbConnections.php' );
$con = Propel::getConnection("root");
$stmt = $con->createStatement();
if (!$allDrafts)
$dateSql = "AND DATE_SUB(CURDATE(),INTERVAL " . $days . " DAY) >= APP_CREATE_DATE";
else
$dateSql = "";
/* Search for all the draft cases */
$sql = "SELECT APP_UID FROM APPLICATION WHERE APP_STATUS='DRAFT'" . $dateSql;
$appRows = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
/* Tables to remove the cases from */
$tables = array(
"APPLICATION",
"APP_DELEGATION",
"APP_CACHE_VIEW",
"APP_THREAD",
"APP_DOCUMENT",
"APP_EVENT",
"APP_HISTORY",
"APP_MESSAGE"
);
echo "Found " . $appRows->getRecordCount() . " cases to remove";
foreach ($appRows as $row) {
echo ".";
$appUid = $row['APP_UID'];
foreach ($tables as $table) {
delete_app_from_table($con, $table, $appUid);
}
delete_app_from_table($con, "CONTENT", $appUid, "CON_ID");
if (file_exists(PATH_DB . $workspace . '/files/'. $appUid)) {
echo "\nRemoving files from " . $appUid . "\n";
G::rm_dir(PATH_DB . $workspace . '/files/'. $appUid);
}
}
echo "\n";
}
?>

View File

@@ -0,0 +1,49 @@
<?php
pake_task('schema-check');
pake_task('schema-fix');
G::LoadClass( "wsTools" );
function schemaCommand($command, $args) {
if (count($args) < 1) {
$workspaces = workspaceTools::listWorkspaces();
} else {
$workspaces = array(new workspaceTools($args[0]));
}
$checkOnly = (strcmp($command, "check") == 0);
foreach ($workspaces as $workspace) {
if ($checkOnly)
print_r("Checking ".$workspace->workspaceName."\n");
else
print_r("Fixing ".$workspace->workspaceName."\n");
try {
$changes = $workspace->repairSchema($checkOnly);
if ($changes != false) {
if ($checkOnly) {
echo "> Schema has changed, run fix to repair\n";
echo " Tables to add: " . count($changes['tablesToAdd'])."\n";
echo " Tables to alter: " . count($changes['tablesToAlter'])."\n";
echo " Indexes to add: " . count($changes['tablesWithNewIndex'])."\n";
echo " Indexes to alter: " . count($changes['tablesToAlterIndex'])."\n";
} else {
echo "> Schema fixed\n";
}
} else {
echo "> Schema is OK\n";
}
} catch (Exception $e) {
echo "Could not ". $command ." ". $workspace->workspaceName .": ".$e->getMessage() . "\n";
}
}
}
function run_schema_fix($task, $args) {
schemaCommand("fix", $args);
}
function run_schema_check($task, $args) {
schemaCommand("check", $args);
}
?>

81
workflow/engine/bin/cron.php Executable file
View File

@@ -0,0 +1,81 @@
<?php
ini_set('memory_limit', '300M'); // nore: this may need to be higher for many projects
$mem_limit = (int) ini_get('memory_limit');
if ( !defined('PATH_SEP') ) {
define('PATH_SEP', ( substr(PHP_OS, 0, 3) == 'WIN' ) ? '\\' : '/');
}
$docuroot = explode(PATH_SEP, str_replace('engine' . PATH_SEP . 'methods' . PATH_SEP . 'services', '', dirname(__FILE__)));
array_pop($docuroot);
array_pop($docuroot);
$pathhome = implode(PATH_SEP, $docuroot) . PATH_SEP;
//try to find automatically the trunk directory where are placed the RBAC and Gulliver directories
//in a normal installation you don't need to change it.
array_pop($docuroot);
$pathTrunk = implode(PATH_SEP, $docuroot) . PATH_SEP ;
array_pop($docuroot);
$pathOutTrunk = implode( PATH_SEP, $docuroot) . PATH_SEP ;
// to do: check previous algorith for Windows $pathTrunk = "c:/home/";
define('PATH_HOME', $pathhome);
define('PATH_TRUNK', $pathTrunk);
define('PATH_OUTTRUNK', $pathOutTrunk);
require_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths.php');
//default values
$bCronIsRunning = false;
$sLastExecution = '';
if ( file_exists(PATH_DATA . 'cron') ) {
$aAux = unserialize( trim( @file_get_contents(PATH_DATA . 'cron')) );
$bCronIsRunning = (boolean)$aAux['bCronIsRunning'];
$sLastExecution = $aAux['sLastExecution'];
}
else {
//if not exists the file, just create a new one with current date
@file_put_contents(PATH_DATA . 'cron', serialize(array('bCronIsRunning' => '1', 'sLastExecution' => date('Y-m-d H:i:s'))));
}
$WS = '';
$argsx = '';
$sDate = '';
for($i=1; $i<count($argv); $i++){
if( strpos($argv[$i], '+d') !== false){
$sDate = substr($argv[$i],2);
} else if( strpos($argv[$i], '+w') !== false){
$WS = substr($argv[$i],2);
} else {
$argsx .= ' '.$argv[$i];
}
}
//if $sDate is not set, so take the system time
if($sDate!=''){
eprintln("[Applying date filter: $sDate]");
} else {
$sDate = date('Y-m-d H:i:s');
}
if( $WS=='' ){
$oDirectory = dir(PATH_DB);
$cws = 0;
while($sObject = $oDirectory->read()) {
if (($sObject != '.') && ($sObject != '..')) {
if (is_dir(PATH_DB . $sObject)) {
if (file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php')) {
$cws++;
system("php -f ".dirname(__FILE__).PATH_SEP."cron_single.php $sObject \"$sDate\" $argsx", $retval);
}
}
}
}
} else {
$cws = 1;
system("php -f ".dirname(__FILE__).PATH_SEP."cron_single.php $WS \"$sDate\" $argsx", $retval);
}
eprintln("Finished $cws workspaces processed.");

View File

@@ -0,0 +1,362 @@
<?php
ini_set('memory_limit', '128M');
if (!defined('SYS_LANG')) {
define('SYS_LANG', 'en');
}
if (!defined('PATH_HOME')) {
if ( !defined('PATH_SEP') ) {
define('PATH_SEP', ( substr(PHP_OS, 0, 3) == 'WIN' ) ? '\\' : '/');
}
$docuroot = explode(PATH_SEP, str_replace('engine' . PATH_SEP . 'methods' . PATH_SEP . 'services', '', dirname(__FILE__)));
array_pop($docuroot);
array_pop($docuroot);
$pathhome = implode(PATH_SEP, $docuroot) . PATH_SEP;
//try to find automatically the trunk directory where are placed the RBAC and Gulliver directories
//in a normal installation you don't need to change it.
array_pop($docuroot);
$pathTrunk = implode(PATH_SEP, $docuroot) . PATH_SEP ;
array_pop($docuroot);
$pathOutTrunk = implode( PATH_SEP, $docuroot) . PATH_SEP ;
// to do: check previous algorith for Windows $pathTrunk = "c:/home/";
define('PATH_HOME', $pathhome);
define('PATH_TRUNK', $pathTrunk);
define('PATH_OUTTRUNK', $pathOutTrunk);
require_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths.php');
G::LoadThirdParty('pear/json','class.json');
G::LoadThirdParty('smarty/libs','Smarty.class');
G::LoadSystem('error');
G::LoadSystem('dbconnection');
G::LoadSystem('dbsession');
G::LoadSystem('dbrecordset');
G::LoadSystem('dbtable');
G::LoadSystem('rbac' );
G::LoadSystem('publisher');
G::LoadSystem('templatePower');
G::LoadSystem('xmlDocument');
G::LoadSystem('xmlform');
G::LoadSystem('xmlformExtension');
G::LoadSystem('form');
G::LoadSystem('menu');
G::LoadSystem("xmlMenu");
G::LoadSystem('dvEditor');
G::LoadSystem('table');
G::LoadSystem('pagedTable');
require_once ( "propel/Propel.php" );
require_once ( "creole/Creole.php" );
}
require_once 'classes/model/AppDelegation.php';
require_once 'classes/model/Event.php';
require_once 'classes/model/AppEvent.php';
require_once 'classes/model/CaseScheduler.php';
//G::loadClass('pmScript');
//default values
$bCronIsRunning = false;
$sLastExecution = '';
if ( file_exists(PATH_DATA . 'cron') ) {
$aAux = unserialize( trim( @file_get_contents(PATH_DATA . 'cron')) );
$bCronIsRunning = (boolean)$aAux['bCronIsRunning'];
$sLastExecution = $aAux['sLastExecution'];
}
else {
//if not exists the file, just create a new one with current date
@file_put_contents(PATH_DATA . 'cron', serialize(array('bCronIsRunning' => '1', 'sLastExecution' => date('Y-m-d H:i:s'))));
}
if (!defined('SYS_SYS')) {
$sObject = $argv[1];
$sNow = $argv[2];
$sFilter = '';
for($i=3; $i<count($argv); $i++){
$sFilter .= ' '.$argv[$i];
}
$oDirectory = dir(PATH_DB);
if (is_dir(PATH_DB . $sObject)) {
saveLog ( 'main', 'action', "checking folder " . PATH_DB . $sObject );
if (file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php')) {
define('SYS_SYS', $sObject);
include_once(PATH_HOME.'engine'.PATH_SEP.'config'.PATH_SEP.'paths_installed.php');
include_once(PATH_HOME.'engine'.PATH_SEP.'config'.PATH_SEP.'paths.php');
//***************** PM Paths DATA **************************
define( 'PATH_DATA_SITE', PATH_DATA . 'sites/' . SYS_SYS . '/');
define( 'PATH_DOCUMENT', PATH_DATA_SITE . 'files/' );
define( 'PATH_DATA_MAILTEMPLATES', PATH_DATA_SITE . 'mailTemplates/' );
define( 'PATH_DATA_PUBLIC', PATH_DATA_SITE . 'public/' );
define( 'PATH_DATA_REPORTS', PATH_DATA_SITE . 'reports/' );
define( 'PATH_DYNAFORM', PATH_DATA_SITE . 'xmlForms/' );
define( 'PATH_IMAGES_ENVIRONMENT_FILES', PATH_DATA_SITE . 'usersFiles'.PATH_SEP);
define( 'PATH_IMAGES_ENVIRONMENT_USERS', PATH_DATA_SITE . 'usersPhotographies'.PATH_SEP);
if(is_file(PATH_DATA_SITE.PATH_SEP.'.server_info')){
$SERVER_INFO = file_get_contents(PATH_DATA_SITE.PATH_SEP.'.server_info');
$SERVER_INFO = unserialize($SERVER_INFO);
//print_r($SERVER_INFO);
define( 'SERVER_NAME', $SERVER_INFO ['SERVER_NAME']);
define( 'SERVER_PORT', $SERVER_INFO ['SERVER_PORT']);
} else {
eprintln("WARNING! No server info found!", 'red');
}
$sContent = file_get_contents(PATH_DB . $sObject . PATH_SEP . 'db.php');
$sContent = str_replace('<?php', '', $sContent);
$sContent = str_replace('<?', '', $sContent);
$sContent = str_replace('?>', '', $sContent);
$sContent = str_replace('define', '', $sContent);
$sContent = str_replace("('", "$", $sContent);
$sContent = str_replace("',", '=', $sContent);
$sContent = str_replace(");", ';', $sContent);
eval($sContent);
$dsn = $DB_ADAPTER . '://' . $DB_USER . ':' . $DB_PASS . '@' . $DB_HOST . '/' . $DB_NAME;
$dsnRbac = $DB_ADAPTER . '://' . $DB_RBAC_USER . ':' . $DB_RBAC_PASS . '@' . $DB_RBAC_HOST . '/' . $DB_RBAC_NAME;
$dsnRp = $DB_ADAPTER . '://' . $DB_REPORT_USER . ':' . $DB_REPORT_PASS . '@' . $DB_REPORT_HOST . '/' . $DB_REPORT_NAME;
switch ($DB_ADAPTER) {
case 'mysql':
$dsn .= '?encoding=utf8';
$dsnRbac .= '?encoding=utf8';
break;
case 'mssql':
//$dsn .= '?sendStringAsUnicode=false';
//$dsnRbac .= '?sendStringAsUnicode=false';
break;
default:
break;
}
$pro['datasources']['workflow']['connection'] = $dsn;
$pro['datasources']['workflow']['adapter'] = $DB_ADAPTER;
$pro['datasources']['rbac']['connection'] = $dsnRbac;
$pro['datasources']['rbac']['adapter'] = $DB_ADAPTER;
$pro['datasources']['rp']['connection'] = $dsnRp;
$pro['datasources']['rp']['adapter'] = $DB_ADAPTER;
//$pro['datasources']['dbarray']['connection'] = 'dbarray://user:pass@localhost/pm_os';
//$pro['datasources']['dbarray']['adapter'] = 'dbarray';
$oFile = fopen(PATH_CORE . 'config/_databases_.php', 'w');
fwrite($oFile, '<?php global $pro;return $pro; ?>');
fclose($oFile);
Propel::init(PATH_CORE . 'config/_databases_.php');
//Creole::registerDriver('dbarray', 'creole.contrib.DBArrayConnection');
eprintln("Processing workspace: " . $sObject, 'green');
try{
processWorkspace();
}catch(Exception $e){
echo $e->getMessage();
eprintln("Probelm in workspace: " . $sObject.' it was omitted.', 'red');
}
eprintln();
}
}
unlink(PATH_CORE . 'config/_databases_.php');
}
else {
processWorkspace();
}
//finally update the file
@file_put_contents(PATH_DATA . 'cron', serialize(array('bCronIsRunning' => '0', 'sLastExecution' => date('Y-m-d H:i:s'))));
function processWorkspace() {
global $sLastExecution;
try {
resendEmails();
unpauseApplications();
calculateDuration();
executePlugins();
executeEvents($sLastExecution);
executeScheduledCases();
}
catch (Exception $oError) {
saveLog ("main", "error", "Error processing workspace : " . $oError->getMessage() . "\n" );
}
}
function resendEmails() {
global $sFilter;
if($sFilter!='' && strpos($sFilter, 'emails') === false) return false;
setExecutionMessage("Resending emails");
try {
G::LoadClass('spool');
$oSpool = new spoolRun();
$oSpool->resendEmails();
saveLog('resendEmails', 'action', 'Resending Emails', "c");
$aSpoolWarnings = $oSpool->getWarnings();
if( $aSpoolWarnings !== false ) {
foreach($aSpoolWarnings as $sWarning){
print('MAIL SPOOL WARNING: ' . $sWarning."\n");
saveLog('resendEmails', 'warning', 'MAIL SPOOL WARNING: ' . $sWarning);
}
}
setExecutionResultMessage('DONE');
}
catch (Exception $oError) {
setExecutionResultMessage('WITH ERRORS', 'error');
eprintln(" '-".$oError->getMessage(), 'red');
saveLog('resendEmails', 'error', 'Error Resending Emails: ' . $oError->getMessage());
}
}
function unpauseApplications() {
global $sFilter;
if($sFilter!='' && strpos($sFilter, 'unpause') === false) return false;
setExecutionMessage("Unpausing applications");
try {
G::LoadClass('case');
$oCases = new Cases();
$oCases->ThrowUnpauseDaemon();
setExecutionResultMessage('DONE');
saveLog('unpauseApplications', 'action', 'Unpausing Applications');
}
catch (Exception $oError) {
setExecutionResultMessage('WITH ERRORS', 'error');
eprintln(" '-".$oError->getMessage(), 'red');
saveLog('unpauseApplications', 'error', 'Error Unpausing Applications: ' . $oError->getMessage());
}
}
function executePlugins(){
global $sFilter;
if($sFilter!='' && strpos($sFilter, 'plugins') === false) return false;
$pathCronPlugins = PATH_CORE.'bin'.PATH_SEP.'plugins'.PATH_SEP;
if ($handle = opendir( $pathCronPlugins )) {
while ( false !== ($file = readdir($handle))) {
if ( strpos($file, '.php',1) && is_file($pathCronPlugins . $file) ) {
$filename = str_replace('.php' , '', $file) ;
$className = $filename . 'ClassCron';
include_once ( $pathCronPlugins . $file ); //$filename. ".php"
$oPlugin =& new $className();
if (method_exists($oPlugin, 'executeCron')) {
$oPlugin->executeCron();
setExecutionMessage("Executing Pentaho Reports Plugin");
setExecutionResultMessage('DONE');
}
}
}
}
}
function calculateDuration() {
global $sFilter;
if($sFilter!='' && strpos($sFilter, 'calculate') === false) return false;
setExecutionMessage("Calculating Duration");
try {
$oAppDelegation = new AppDelegation();
$oAppDelegation->calculateDuration();
setExecutionResultMessage('DONE');
saveLog('calculateDuration', 'action', 'Calculating Duration');
}
catch (Exception $oError) {
setExecutionResultMessage('WITH ERRORS', 'error');
eprintln(" '-".$oError->getMessage(), 'red');
saveLog('calculateDuration', 'error', 'Error Calculating Duration: ' . $oError->getMessage());
}
}
function executeEvents($sLastExecution, $sNow=null) {
global $sFilter;
global $sNow;
if($sFilter!='' && strpos($sFilter, 'events') === false) return false;
setExecutionMessage("Executing events");
setExecutionResultMessage('PROCESSING');
try {
$oAppEvent = new AppEvent();
saveLog('executeEvents', 'action', "Executing Events $sLastExecution, $sNow ");
$n = $oAppEvent->executeEvents($sNow);
setExecutionMessage("|- End Execution events");
setExecutionResultMessage("Processed $n");
//saveLog('executeEvents', 'action', $res );
}
catch (Exception $oError) {
setExecutionResultMessage('WITH ERRORS', 'error');
eprintln(" '-".$oError->getMessage(), 'red');
saveLog('calculateAlertsDueDate', 'Error', 'Error Executing Events: ' . $oError->getMessage());
}
}
function executeScheduledCases($sNow=null){
try{
global $sFilter;
global $sNow;
if($sFilter!='' && strpos($sFilter, 'scheduler') === false) return false;
setExecutionMessage("Executing the scheduled starting cases");
setExecutionResultMessage('PROCESSING');
$sNow = isset($sNow)? $sNow: date('Y-m-d H:i:s');
$oCaseScheduler = new CaseScheduler;
$oCaseScheduler->caseSchedulerCron($sNow);
setExecutionResultMessage('DONE');
} catch(Exception $oError){
setExecutionResultMessage('WITH ERRORS', 'error');
eprintln(" '-".$oError->getMessage(), 'red');
}
}
function saveLog($sSource, $sType, $sDescription) {
try {
global $isDebug;
if ( $isDebug )
print date('H:i:s') ." ($sSource) $sType $sDescription <br>\n";
@fwrite($oFile, date('Y-m-d H:i:s') . '(' . $sSource . ') ' . $sDescription . "\n");
G::verifyPath(PATH_DATA . 'log' . PATH_SEP, true);
if ($sType == 'action') {
$oFile = @fopen(PATH_DATA . 'log' . PATH_SEP . 'cron.log', 'a+');
}
else {
$oFile = @fopen(PATH_DATA . 'log' . PATH_SEP . 'cronError.log', 'a+');
}
@fwrite($oFile, date('Y-m-d H:i:s') . '(' . $sSource . ') ' . $sDescription . "\n");
@fclose($oFile);
}
catch (Exception $oError) {
//CONTINUE
}
}
function setExecutionMessage($m){
$len = strlen($m);
$linesize = 60;
$rOffset = $linesize - $len;
eprint("* $m");
for($i=0; $i<$rOffset; $i++) eprint('.');
}
function setExecutionResultMessage($m, $t=''){
$c='green';
if($t=='error') $c = 'red';
if($t=='info') $c = 'yellow';
eprintln("[$m]", $c);
}

View File

@@ -0,0 +1,830 @@
<?php
/**
* class.ArrayPeer.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.
*
*/
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 ApplicationPeer::getOMClass()
include_once 'classes/model/Application.php';
/**
* Base static class for performing query and update operations on the 'APPLICATION' table.
*
* @package classes.model.om
*/
abstract class ArrayBasePeer {
/** The default database name for this class */
const DATABASE_NAME = 'dbarray';
/** The table name for this class */
//const TABLE_NAME = 'APPLICATION';
/** A class that can be returned by this peer. */
const CLASS_DEFAULT = 'classes.model.Application';
/** The total number of columns. */
const NUM_COLUMNS = 15;
/** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0;
/** The column name for the APP_UID field */
const APP_UID = 'APPLICATION.APP_UID';
/** The column name for the APP_NUMBER field */
const APP_NUMBER = 'APPLICATION.APP_NUMBER';
/** The column name for the APP_PARENT field */
const APP_PARENT = 'APPLICATION.APP_PARENT';
/** The column name for the APP_STATUS field */
const APP_STATUS = 'APPLICATION.APP_STATUS';
/** The column name for the PRO_UID field */
const PRO_UID = 'APPLICATION.PRO_UID';
/** The column name for the APP_PROC_STATUS field */
const APP_PROC_STATUS = 'APPLICATION.APP_PROC_STATUS';
/** The column name for the APP_PROC_CODE field */
const APP_PROC_CODE = 'APPLICATION.APP_PROC_CODE';
/** The column name for the APP_PARALLEL field */
const APP_PARALLEL = 'APPLICATION.APP_PARALLEL';
/** The column name for the APP_INIT_USER field */
const APP_INIT_USER = 'APPLICATION.APP_INIT_USER';
/** The column name for the APP_CUR_USER field */
const APP_CUR_USER = 'APPLICATION.APP_CUR_USER';
/** The column name for the APP_CREATE_DATE field */
const APP_CREATE_DATE = 'APPLICATION.APP_CREATE_DATE';
/** The column name for the APP_INIT_DATE field */
const APP_INIT_DATE = 'APPLICATION.APP_INIT_DATE';
/** The column name for the APP_FINISH_DATE field */
const APP_FINISH_DATE = 'APPLICATION.APP_FINISH_DATE';
/** The column name for the APP_UPDATE_DATE field */
const APP_UPDATE_DATE = 'APPLICATION.APP_UPDATE_DATE';
/** The column name for the APP_DATA field */
const APP_DATA = 'APPLICATION.APP_DATA';
/** 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 ('AppUid', 'AppNumber', 'AppParent', 'AppStatus', 'ProUid', 'AppProcStatus', 'AppProcCode', 'AppParallel', 'AppInitUser', 'AppCurUser', 'AppCreateDate', 'AppInitDate', 'AppFinishDate', 'AppUpdateDate', 'AppData', ),
BasePeer::TYPE_COLNAME => array (ApplicationPeer::APP_UID, ApplicationPeer::APP_NUMBER, ApplicationPeer::APP_PARENT, ApplicationPeer::APP_STATUS, ApplicationPeer::PRO_UID, ApplicationPeer::APP_PROC_STATUS, ApplicationPeer::APP_PROC_CODE, ApplicationPeer::APP_PARALLEL, ApplicationPeer::APP_INIT_USER, ApplicationPeer::APP_CUR_USER, ApplicationPeer::APP_CREATE_DATE, ApplicationPeer::APP_INIT_DATE, ApplicationPeer::APP_FINISH_DATE, ApplicationPeer::APP_UPDATE_DATE, ApplicationPeer::APP_DATA, ),
BasePeer::TYPE_FIELDNAME => array ('APP_UID', 'APP_NUMBER', 'APP_PARENT', 'APP_STATUS', 'PRO_UID', 'APP_PROC_STATUS', 'APP_PROC_CODE', 'APP_PARALLEL', 'APP_INIT_USER', 'APP_CUR_USER', 'APP_CREATE_DATE', 'APP_INIT_DATE', 'APP_FINISH_DATE', 'APP_UPDATE_DATE', 'APP_DATA', ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, )
);
/**
* 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 ('AppUid' => 0, 'AppNumber' => 1, 'AppParent' => 2, 'AppStatus' => 3, 'ProUid' => 4, 'AppProcStatus' => 5, 'AppProcCode' => 6, 'AppParallel' => 7, 'AppInitUser' => 8, 'AppCurUser' => 9, 'AppCreateDate' => 10, 'AppInitDate' => 11, 'AppFinishDate' => 12, 'AppUpdateDate' => 13, 'AppData' => 14, ),
BasePeer::TYPE_COLNAME => array (ApplicationPeer::APP_UID => 0, ApplicationPeer::APP_NUMBER => 1, ApplicationPeer::APP_PARENT => 2, ApplicationPeer::APP_STATUS => 3, ApplicationPeer::PRO_UID => 4, ApplicationPeer::APP_PROC_STATUS => 5, ApplicationPeer::APP_PROC_CODE => 6, ApplicationPeer::APP_PARALLEL => 7, ApplicationPeer::APP_INIT_USER => 8, ApplicationPeer::APP_CUR_USER => 9, ApplicationPeer::APP_CREATE_DATE => 10, ApplicationPeer::APP_INIT_DATE => 11, ApplicationPeer::APP_FINISH_DATE => 12, ApplicationPeer::APP_UPDATE_DATE => 13, ApplicationPeer::APP_DATA => 14, ),
BasePeer::TYPE_FIELDNAME => array ('APP_UID' => 0, 'APP_NUMBER' => 1, 'APP_PARENT' => 2, 'APP_STATUS' => 3, 'PRO_UID' => 4, 'APP_PROC_STATUS' => 5, 'APP_PROC_CODE' => 6, 'APP_PARALLEL' => 7, 'APP_INIT_USER' => 8, 'APP_CUR_USER' => 9, 'APP_CREATE_DATE' => 10, 'APP_INIT_DATE' => 11, 'APP_FINISH_DATE' => 12, 'APP_UPDATE_DATE' => 13, 'APP_DATA' => 14, ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, )
);
/**
* @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/ApplicationMapBuilder.php';
return BasePeer::getMapBuilder('classes.model.map.ApplicationMapBuilder');
}
/**
* 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 = ApplicationPeer::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. ApplicationPeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(ApplicationPeer::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 $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)
{
}
const COUNT = 'COUNT(APPLICATION.APP_UID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT APPLICATION.APP_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.
* @todo Review declarated constant d'not used COUNT, COUNT_DISTINCT
*/
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();
/*
krumo ( ApplicationPeer::COUNT_DISTINCT );
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(ApplicationPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(ApplicationPeer::COUNT);
}
*/
$criteria->addSelectColumn( 'COUNT(*)');
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column) {
$criteria->addSelectColumn($column);
}
$rs = ArrayBasePeer::doSelectRS($criteria, $con);
if ($rs->next()) {
$row = $rs->getRow();
return $row[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 Application
* @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 = ApplicationPeer::doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Method to create select SQL.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param String $tableName
* @param Array &$params
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
private function createSelectSql($criteria, $tableName, &$params)
{
$db = Propel::getDB($criteria->getDbName());
// redundant definition $selectModifiers = array();
$selectClause = array();
$fromClause = array();
$joinClause = array();
$joinTables = array();
$whereClause = array();
$orderByClause = array();
$groupByClause = array();
$orderBy = $criteria->getOrderByColumns();
$groupBy = $criteria->getGroupByColumns();
$ignoreCase = $criteria->isIgnoreCase();
$select = $criteria->getSelectColumns();
$aliases = $criteria->getAsColumns();
$fromClause[] = $criteria->getDBArrayTable();
// simple copy
$selectModifiers = $criteria->getSelectModifiers();
// get selected columns
foreach($select as $columnName) {
$tableName = null;
$selectClause[] = $columnName; // the full column name: e.g. MAX(books.price)
$parenPos = strpos($columnName, '(');
$dotPos = strpos($columnName, '.');
// [HL] I think we really only want to worry about adding stuff to
// the fromClause if this function has a TABLE.COLUMN in it at all.
// e.g. COUNT(*) should not need this treatment -- or there needs to
// be special treatment for '*'
if ($dotPos !== false) {
if ($parenPos === false) { // table.column
$tableName = substr($columnName, 0, $dotPos);
} else { // FUNC(table.column)
$tableName = substr($columnName, $parenPos + 1, $dotPos - ($parenPos + 1));
// functions may contain qualifiers so only take the last
// word as the table name.
// COUNT(DISTINCT books.price)
$lastSpace = strpos($tableName, ' ');
if ($lastSpace !== false) { // COUNT(DISTINCT books.price)
$tableName = substr($tableName, $lastSpace + 1);
}
}
$tableName2 = $criteria->getTableForAlias($tableName);
if ($tableName2 !== null) {
$fromClause[] = $tableName2 . ' ' . $tableName;
} else {
$fromClause[] = $tableName;
}
} // if $dotPost !== null
}
// set the aliases
foreach($aliases as $alias => $col) {
$selectClause[] = $col . " AS " . $alias;
}
// add the criteria to WHERE clause
foreach($criteria->keys() as $key) {
$criterion = $criteria->getCriterion($key);
$someCriteria = $criterion->getAttachedCriterion();
$someCriteriaLength = count($someCriteria);
$table = null;
for ($i=0; $i < $someCriteriaLength; $i++) {
$tableName = $someCriteria[$i]->getTable();
$table = $criteria->getTableForAlias($tableName);
if ($table !== null) {
$fromClause[] = $table . ' ' . $tableName;
} else {
$fromClause[] = $tableName;
$table = $tableName;
}
$ignoreCase =
(($criteria->isIgnoreCase()
|| $someCriteria[$i]->isIgnoreCase())
&& ($dbMap->getTable($table)->getColumn($someCriteria[$i]->getColumn())->getType() == "string" )
);
$someCriteria[$i]->setIgnoreCase($ignoreCase);
}
$criterion->setDB($db);
$cri['table'] = $criterion->table;
$cri['field'] = $criterion->column;
$cri['comparison'] = $criterion->comparison == '=' ? '==' : $criterion->comparison;
$cri['value'] = $criterion->getValue();
$sb = "";
$sb .= "\$row['" . $cri['field'] . "'] " . $cri['comparison'] . "'" . $cri['value'] . "'";
$params[] = $cri;
//$criterion->appendPsTo($sb, $params);
$whereClause[] = $sb;
}
// Unique from clause elements
$fromClause = array_unique( $fromClause );
if (!empty($orderBy)) {
foreach($orderBy as $orderByColumn) {
// Add function expression as-is.
if (strpos($orderByColumn, '(') !== false) {
$orderByClause[] = $orderByColumn;
continue;
}
// Split orderByColumn (i.e. "table.column DESC")
$dotPos = strpos($orderByColumn, '.');
if ($dotPos !== false) {
$tableName = substr($orderByColumn, 0, $dotPos);
$columnName = substr($orderByColumn, $dotPos+1);
}
else {
$tableName = '';
$columnName = $orderByColumn;
}
$spacePos = strpos($columnName, ' ');
if ($spacePos !== false) {
$direction = substr($columnName, $spacePos);
$columnName = substr($columnName, 0, $spacePos);
}
else {
$direction = '';
}
$orderByClause[] = array ( 'columnName' => $columnName, 'direction' => $direction );
}
}
// Build the SQL from the arrays we compiled
$sql = "SELECT "
.($selectModifiers ? implode(" ", $selectModifiers) . " " : "")
.implode(", ", $selectClause)
." FROM ". $fromClause[0]
.($whereClause ? " WHERE ".implode(" AND ", $whereClause) : "")
.($groupByClause ? " GROUP BY ".implode(",", $groupByClause) : "");
$dataSql['selectClause'] = $selectClause;
$dataSql['fromClause'] = $fromClause;
$dataSql['whereClause'] = $whereClause;
$dataSql['orderByClause']= $orderByClause;
$dataSql['sql'] = $sql;
return $dataSql;
}
/**
* 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, $tableName, $con = null)
{
$dbMap = Propel::getDatabaseMap($criteria->getDbName());
$stmt = null;
try {
$params = array();
$sql = self::createSelectSql($criteria, $tableName, $params);
$sql['params'] = $params;
$stmt = $con->prepareStatement( $sql);
//$stmt->setLimit($criteria->getLimit());
$sql['limit']=$criteria->getLimit();
//$stmt->setOffset($criteria->getOffset());
$sql['offset']=$criteria->getOffset();
//$rs = $stmt->executeQuery(ResultSet::FETCHMODE_NUM);
$rs = $con->executeQuery($sql, ResultSet::FETCHMODE_NUM);
} catch (Exception $e) {
if ($stmt) $stmt->close();
throw new PropelException($e);
}
return $rs;
}
/**
* 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)
{
global $_DBArray;
if ( !isset ($_DBArray) ) {
$_DBArray = $_SESSION['_DBArray'];
}
$tableName = $criteria->getDBArrayTable();
if ( !isset ( $_DBArray[$tableName] ) ) {
throw new Exception ( "Error: the table '$tableName' doesn't exist in DBArray " );
}
$arrayTable = $_DBArray[$tableName];
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if (!$criteria->getSelectColumns()) {
foreach ( array_keys ( $_DBArray[$tableName][0] ) as $key => $val )
$criteria->addSelectColumn( $tableName.'.'.$val );
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
// BasePeer returns a Creole ResultSet, set to return
// rows indexed numerically.
return ArrayBasePeer::doSelect($criteria,$tableName, $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 = ApplicationPeer::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 ApplicationPeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a Application or Criteria object.
*
* @param mixed $values Criteria or Application 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 Application 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 Application or Criteria object.
*
* @param mixed $values Criteria or Application 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(ApplicationPeer::APP_UID);
$selectCriteria->add(ApplicationPeer::APP_UID, $criteria->remove(ApplicationPeer::APP_UID), $comparison);
} else { // $values is Application 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 APPLICATION table.
* @param Connection $con The connection to use
* @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(ApplicationPeer::TABLE_NAME, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a Application or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or Application 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(ApplicationPeer::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
if ($values instanceof Application) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(ApplicationPeer::APP_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 Application 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 Application $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(Application $obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(ApplicationPeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(ApplicationPeer::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 {
if ($obj->isNew() || $obj->isColumnModified(ApplicationPeer::APP_STATUS))
$columns[ApplicationPeer::APP_STATUS] = $obj->getAppStatus();
}
return BasePeer::doValidate(ApplicationPeer::DATABASE_NAME, ApplicationPeer::TABLE_NAME, $columns);
}
/**
* Retrieve a single object by pkey.
*
* @param mixed $pk the primary key.
* @param Connection $con the connection to use
* @return Application
*/
public static function retrieveByPK($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria(ApplicationPeer::DATABASE_NAME);
$criteria->add(ApplicationPeer::APP_UID, $pk);
$v = ApplicationPeer::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(ApplicationPeer::APP_UID, $pks, Criteria::IN);
$objs = ApplicationPeer::doSelect($criteria, $con);
}
return $objs;
}
} // BaseApplicationPeer
// 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 {
BaseApplicationPeer::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/ApplicationMapBuilder.php';
Propel::registerMapBuilder('classes.model.map.ApplicationMapBuilder');
}

View File

@@ -0,0 +1,667 @@
<?php
/**
* class.BasePeer.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.
*
*/
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 ApplicationPeer::getOMClass()
include_once 'classes/model/Application.php';
/**
* Base static class for performing query and update operations on the 'APPLICATION' table.
*
*
*
* @package classes.model.om
*/
abstract class GulliverBasePeer {
/** the default database name for this class */
const DATABASE_NAME = 'workflow';
/** the table name for this class */
const TABLE_NAME = 'APPLICATION';
/** A class that can be returned by this peer. */
const CLASS_DEFAULT = 'classes.model.Application';
/** The total number of columns. */
const NUM_COLUMNS = 15;
/** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0;
/** the column name for the APP_UID field */
const APP_UID = 'APPLICATION.APP_UID';
/** the column name for the APP_NUMBER field */
const APP_NUMBER = 'APPLICATION.APP_NUMBER';
/** the column name for the APP_PARENT field */
const APP_PARENT = 'APPLICATION.APP_PARENT';
/** the column name for the APP_STATUS field */
const APP_STATUS = 'APPLICATION.APP_STATUS';
/** the column name for the PRO_UID field */
const PRO_UID = 'APPLICATION.PRO_UID';
/** the column name for the APP_PROC_STATUS field */
const APP_PROC_STATUS = 'APPLICATION.APP_PROC_STATUS';
/** the column name for the APP_PROC_CODE field */
const APP_PROC_CODE = 'APPLICATION.APP_PROC_CODE';
/** the column name for the APP_PARALLEL field */
const APP_PARALLEL = 'APPLICATION.APP_PARALLEL';
/** the column name for the APP_INIT_USER field */
const APP_INIT_USER = 'APPLICATION.APP_INIT_USER';
/** the column name for the APP_CUR_USER field */
const APP_CUR_USER = 'APPLICATION.APP_CUR_USER';
/** the column name for the APP_CREATE_DATE field */
const APP_CREATE_DATE = 'APPLICATION.APP_CREATE_DATE';
/** the column name for the APP_INIT_DATE field */
const APP_INIT_DATE = 'APPLICATION.APP_INIT_DATE';
/** the column name for the APP_FINISH_DATE field */
const APP_FINISH_DATE = 'APPLICATION.APP_FINISH_DATE';
/** the column name for the APP_UPDATE_DATE field */
const APP_UPDATE_DATE = 'APPLICATION.APP_UPDATE_DATE';
/** the column name for the APP_DATA field */
const APP_DATA = 'APPLICATION.APP_DATA';
/** 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 ('AppUid', 'AppNumber', 'AppParent', 'AppStatus', 'ProUid', 'AppProcStatus', 'AppProcCode', 'AppParallel', 'AppInitUser', 'AppCurUser', 'AppCreateDate', 'AppInitDate', 'AppFinishDate', 'AppUpdateDate', 'AppData', ),
BasePeer::TYPE_COLNAME => array (ApplicationPeer::APP_UID, ApplicationPeer::APP_NUMBER, ApplicationPeer::APP_PARENT, ApplicationPeer::APP_STATUS, ApplicationPeer::PRO_UID, ApplicationPeer::APP_PROC_STATUS, ApplicationPeer::APP_PROC_CODE, ApplicationPeer::APP_PARALLEL, ApplicationPeer::APP_INIT_USER, ApplicationPeer::APP_CUR_USER, ApplicationPeer::APP_CREATE_DATE, ApplicationPeer::APP_INIT_DATE, ApplicationPeer::APP_FINISH_DATE, ApplicationPeer::APP_UPDATE_DATE, ApplicationPeer::APP_DATA, ),
BasePeer::TYPE_FIELDNAME => array ('APP_UID', 'APP_NUMBER', 'APP_PARENT', 'APP_STATUS', 'PRO_UID', 'APP_PROC_STATUS', 'APP_PROC_CODE', 'APP_PARALLEL', 'APP_INIT_USER', 'APP_CUR_USER', 'APP_CREATE_DATE', 'APP_INIT_DATE', 'APP_FINISH_DATE', 'APP_UPDATE_DATE', 'APP_DATA', ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, )
);
/**
* 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 ('AppUid' => 0, 'AppNumber' => 1, 'AppParent' => 2, 'AppStatus' => 3, 'ProUid' => 4, 'AppProcStatus' => 5, 'AppProcCode' => 6, 'AppParallel' => 7, 'AppInitUser' => 8, 'AppCurUser' => 9, 'AppCreateDate' => 10, 'AppInitDate' => 11, 'AppFinishDate' => 12, 'AppUpdateDate' => 13, 'AppData' => 14, ),
BasePeer::TYPE_COLNAME => array (ApplicationPeer::APP_UID => 0, ApplicationPeer::APP_NUMBER => 1, ApplicationPeer::APP_PARENT => 2, ApplicationPeer::APP_STATUS => 3, ApplicationPeer::PRO_UID => 4, ApplicationPeer::APP_PROC_STATUS => 5, ApplicationPeer::APP_PROC_CODE => 6, ApplicationPeer::APP_PARALLEL => 7, ApplicationPeer::APP_INIT_USER => 8, ApplicationPeer::APP_CUR_USER => 9, ApplicationPeer::APP_CREATE_DATE => 10, ApplicationPeer::APP_INIT_DATE => 11, ApplicationPeer::APP_FINISH_DATE => 12, ApplicationPeer::APP_UPDATE_DATE => 13, ApplicationPeer::APP_DATA => 14, ),
BasePeer::TYPE_FIELDNAME => array ('APP_UID' => 0, 'APP_NUMBER' => 1, 'APP_PARENT' => 2, 'APP_STATUS' => 3, 'PRO_UID' => 4, 'APP_PROC_STATUS' => 5, 'APP_PROC_CODE' => 6, 'APP_PARALLEL' => 7, 'APP_INIT_USER' => 8, 'APP_CUR_USER' => 9, 'APP_CREATE_DATE' => 10, 'APP_INIT_DATE' => 11, 'APP_FINISH_DATE' => 12, 'APP_UPDATE_DATE' => 13, 'APP_DATA' => 14, ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, )
);
/**
* @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/ApplicationMapBuilder.php';
return BasePeer::getMapBuilder('classes.model.map.ApplicationMapBuilder');
}
/**
* 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 = ApplicationPeer::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. ApplicationPeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(ApplicationPeer::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(ApplicationPeer::APP_UID);
$criteria->addSelectColumn(ApplicationPeer::APP_NUMBER);
$criteria->addSelectColumn(ApplicationPeer::APP_PARENT);
$criteria->addSelectColumn(ApplicationPeer::APP_STATUS);
$criteria->addSelectColumn(ApplicationPeer::PRO_UID);
$criteria->addSelectColumn(ApplicationPeer::APP_PROC_STATUS);
$criteria->addSelectColumn(ApplicationPeer::APP_PROC_CODE);
$criteria->addSelectColumn(ApplicationPeer::APP_PARALLEL);
$criteria->addSelectColumn(ApplicationPeer::APP_INIT_USER);
$criteria->addSelectColumn(ApplicationPeer::APP_CUR_USER);
$criteria->addSelectColumn(ApplicationPeer::APP_CREATE_DATE);
$criteria->addSelectColumn(ApplicationPeer::APP_INIT_DATE);
$criteria->addSelectColumn(ApplicationPeer::APP_FINISH_DATE);
$criteria->addSelectColumn(ApplicationPeer::APP_UPDATE_DATE);
$criteria->addSelectColumn(ApplicationPeer::APP_DATA);
}
const COUNT = 'COUNT(APPLICATION.APP_UID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT APPLICATION.APP_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();
/*
krumo ( ApplicationPeer::COUNT_DISTINCT );
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(ApplicationPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(ApplicationPeer::COUNT);
}
*/
$criteria->addSelectColumn( 'COUNT(*)');
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$rs = GulliverBasePeer::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 Application
* @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 = ApplicationPeer::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 ApplicationPeer::populateObjects(GulliverBasePeer::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);
$con = Propel::getConnection($criteria->getDbName());
}
if (!$criteria->getSelectColumns()) {
$criteria = clone $criteria;
//ApplicationPeer::addSelectColumns($criteria);
}
// Set the correct dbName
//$criteria->setDbName(self::DATABASE_NAME);
$criteria->setDbName($criteria->getDbName());
// 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 = ApplicationPeer::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 ApplicationPeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a Application or Criteria object.
*
* @param mixed $values Criteria or Application 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 Application 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 Application or Criteria object.
*
* @param mixed $values Criteria or Application 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(ApplicationPeer::APP_UID);
$selectCriteria->add(ApplicationPeer::APP_UID, $criteria->remove(ApplicationPeer::APP_UID), $comparison);
} else { // $values is Application 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 APPLICATION 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(ApplicationPeer::TABLE_NAME, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a Application or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or Application 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(ApplicationPeer::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof Application) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(ApplicationPeer::APP_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 Application 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 Application $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(Application $obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(ApplicationPeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(ApplicationPeer::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 {
if ($obj->isNew() || $obj->isColumnModified(ApplicationPeer::APP_STATUS))
$columns[ApplicationPeer::APP_STATUS] = $obj->getAppStatus();
}
return BasePeer::doValidate(ApplicationPeer::DATABASE_NAME, ApplicationPeer::TABLE_NAME, $columns);
}
/**
* Retrieve a single object by pkey.
*
* @param mixed $pk the primary key.
* @param Connection $con the connection to use
* @return Application
*/
public static function retrieveByPK($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria(ApplicationPeer::DATABASE_NAME);
$criteria->add(ApplicationPeer::APP_UID, $pk);
$v = ApplicationPeer::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(ApplicationPeer::APP_UID, $pks, Criteria::IN);
$objs = ApplicationPeer::doSelect($criteria, $con);
}
return $objs;
}
} // BaseApplicationPeer
// 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 {
BaseApplicationPeer::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/ApplicationMapBuilder.php';
Propel::registerMapBuilder('classes.model.map.ApplicationMapBuilder');
}

View File

@@ -0,0 +1,577 @@
<?php
/**
* class.Installer.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.
*
*/
//
// It works with the table CONFIGURATION in a WF dataBase
//
// Copyright (C) 2007 COLOSA
//
// License: LGPL, see LICENSE
////////////////////////////////////////////////////
/**
* Processmaker Installer
* @package ProcessMaker
* @author maborak
* @copyright 2008 COLOSA
*/
class Installer
{
public $options = Array();
public $result = Array();
public $error = Array();
public $report = Array();
private $connection_database;
/**
* construct of insert
*
* @param string $pPRO_UID
* @return void
*/
function __construct()
{
}
/**
* create_site
*
* @param array $config
* @param boolean $confirmed
* @return void
*/
public function create_site($config = Array(), $confirmed = false)
{
$this->options=G::array_concat(Array(
'isset'=>false,
'password' =>G::generate_password(12),
'path_data' =>@PATH_DATA,
'path_compiled' =>@PATH_C,
'name'=>$config['name'],
'database'=>Array(),
'admin'=>Array('username'=>'admin','password'=>'admin'),
'advanced'=>Array(
'ao_db_wf'=>'wf_'.$config['name'],
'ao_db_rb'=>'rb_'.$config['name'],
'ao_db_rp'=>'rp_'.$config['name'],
'ao_db_drop'=>false
)
),$config);
$a = @explode(SYSTEM_HASH,G::decrypt(HASH_INSTALLATION,SYSTEM_HASH));
$this->options['database']=G::array_concat(Array(
'username'=>@$a[1],
'password'=>@$a[2],
'hostname'=>@$a[0]
),$this->options['database']);
return ($confirmed===true)?$this->make_site():$this->create_site_test();
}
/**
* isset_site
*
* @param string $name Default value "workflow"
* @return string file_exists(PATH_DATA."sites/".$name);
*/
public function isset_site($name = "workflow")
{
return file_exists(PATH_DATA."sites/".$name);
}
/**
* create_site_test
*
* @return void
*/
private function create_site_test()
{
$name = (preg_match('/^[\w]+$/i',trim($this->options['name'])))?true:false;
$result=Array(
'path_data' =>$this->is_dir_writable($this->options['path_data']),
'path_compiled' =>$this->is_dir_writable($this->options['path_compiled']),
'database' =>$this->check_connection(),
'access_level'=>$this->cc_status,
'isset'=>($this->options['isset']==true)?$this->isset_site($this->options['name']):false,
'microtime'=>microtime(),
'workspace'=>$this->options['name'],
'name'=>array(
'status'=>$name,
'message'=>($name)?'PASSED':'Workspace name invalid'
),
'admin'=>array(
'username'=>(preg_match('/^[\w@\.-]+$/i',trim($this->options['admin']['username'])))?true:false,
'password'=>((trim($this->options['admin']['password'])=='')?false:true)
)
);
$result['name']['message'] = ($result['isset'])?'Workspace already exists':$result['name']['message'];
$result['name']['status'] = ($result['isset'])?false:$result['name']['status'];
//print_r($result);
return Array(
'created'=>G::var_compare(
true,
$result['path_data'],
$result['database']['connection'],
$result['name']['status'],
$result['database']['version'],
$result['database']['ao']['ao_db_wf']['status'],
$result['database']['ao']['ao_db_rb']['status'],
$result['database']['ao']['ao_db_rp']['status'],
$result['admin']['username'],
(($result['isset'])?false:true),
$result['admin']['password']),
'result'=>$result
);
}
/**
* make_site
*
* @return array $test
*/
private function make_site()
{
$test = $this->create_site_test();
if($test['created']===true)
{
/* Check if the hostname is local (localhost or 127.0.0.1) */
$islocal = (strcmp(substr($this->options['database']['hostname'], 0, strlen('localhost')),'localhost')===0) ||
(strcmp(substr($this->options['database']['hostname'], 0, strlen('127.0.0.1')),'127.0.0.1')===0);
$this->wf_site_name = $wf = $this->options['advanced']['ao_db_wf'];
$this->rbac_site_name = $rb = $this->options['advanced']['ao_db_rb'];
$this->report_site_name = $rp = $this->options['advanced']['ao_db_rp'];
$schema = "schema.sql";
$values = "insert.sql";
if($this->options['advanced']['ao_db_drop']===true) {
/* Drop databases */
$q = "DROP DATABASE IF EXISTS ".$wf;
$ac = @mysql_query($q,$this->connection_database);
$this->log($q.": => ".((!$ac)?mysql_error():"OK")."\n");
$q = "DROP DATABASE IF EXISTS ".$rb;
$ac = @mysql_query($q,$this->connection_database);
$this->log($q.": => ".((!$ac)?mysql_error():"OK")."\n");
$q = "DROP DATABASE IF EXISTS ".$rp;
$ac = @mysql_query($q,$this->connection_database);
$this->log($q.": => ".((!$ac)?mysql_error():"OK")."\n");
}
$q = "CREATE DATABASE IF NOT EXISTS ".$wf." DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
$ac = @mysql_query($q,$this->connection_database);
$this->log($q.": => ".((!$ac)?mysql_error():"OK")."\n");
$q = "CREATE DATABASE IF NOT EXISTS ".$rb." DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
$ac = @mysql_query($q,$this->connection_database);
$this->log($q.": => ".((!$ac)?mysql_error():"OK")."\n");
/* report DB begin */
$q = "CREATE DATABASE IF NOT EXISTS ".$rp." DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
$ac = @mysql_query($q,$this->connection_database);
$this->log($q.": => ".((!$ac)?mysql_error():"OK")."\n");
/* report DB end */
if($this->cc_status==1) {
if($islocal) {
$priv_wf = "GRANT ALL PRIVILEGES ON `".$wf."`.* TO ".$wf."@'localhost' IDENTIFIED BY '".$this->options['password']."' WITH GRANT OPTION";
}
else {
$priv_wf = "GRANT ALL PRIVILEGES ON `".$wf."`.* TO ".$wf."@'%' IDENTIFIED BY '".$this->options['password']."' WITH GRANT OPTION";
}
$ac = @mysql_query($priv_wf,$this->connection_database);
$this->log($priv_wf.": => ".((!$ac)?mysql_error():"OK")."\n");
if($islocal) {
$priv_rb = "GRANT ALL PRIVILEGES ON `".$rb."`.* TO ".$rb."@'localhost' IDENTIFIED BY '".$this->options['password']."' WITH GRANT OPTION";
}
else {
$priv_rb = "GRANT ALL PRIVILEGES ON `".$rb."`.* TO ".$rb."@'%' IDENTIFIED BY '".$this->options['password']."' WITH GRANT OPTION";
}
$ac = @mysql_query($priv_rb,$this->connection_database);
$this->log($priv_rb.": => ".((!$ac)?mysql_error():"OK")."\n");
/* report DB begin */
if($islocal) {
$priv_rp = "GRANT ALL PRIVILEGES ON `".$rp."`.* TO ".$rp."@'localhost' IDENTIFIED BY '".$this->options['password']."' WITH GRANT OPTION";
}
else {
$priv_rp = "GRANT ALL PRIVILEGES ON `".$rp."`.* TO ".$rp."@'%' IDENTIFIED BY '".$this->options['password']."' WITH GRANT OPTION";
}
$ac = @mysql_query($priv_rp,$this->connection_database);
$this->log($priv_rp.": => ".((!$ac)?mysql_error():"OK")."\n");
/* report DB end */
}
/* Dump schema workflow && data */
$this->log("Importing database schema\n");
$myPortA = explode(":",$this->options['database']['hostname']);
if(count($myPortA)<2) {
$myPortA[1]="3306";
}
$myPort = $myPortA[1];
$this->options['database']['hostname'] = $myPortA[0];
mysql_select_db($wf,$this->connection_database);
$pws = PATH_WORKFLOW_MYSQL_DATA.$schema;
$qws = $this->query_sql_file(PATH_WORKFLOW_MYSQL_DATA.$schema,$this->connection_database);
$this->log($qws);
$qwv = $this->query_sql_file(PATH_WORKFLOW_MYSQL_DATA.$values,$this->connection_database);
$this->log($qwv);
/* Dump schema rbac && data */
$pws = PATH_RBAC_MYSQL_DATA.$schema;
mysql_select_db($rb,$this->connection_database);
$qrs = $this->query_sql_file(PATH_RBAC_MYSQL_DATA.$schema,$this->connection_database);
$this->log($qrs);
$qrv = $this->query_sql_file(PATH_RBAC_MYSQL_DATA.$values,$this->connection_database);
$this->log($qrv);
$path_site = $this->options['path_data']."/sites/".$this->options['name']."/";
$db_file = $path_site."db.php";
@mkdir($path_site,0777,true);
@mkdir($path_site."files/",0777,true);
@mkdir($path_site."mailTemplates/",0777,true);
@mkdir($path_site."public/",0777,true);
@mkdir($path_site."reports/",0777,true);
@mkdir($path_site."xmlForms",0777,true);
$db_text = "<?php\n" .
"// Processmaker configuration\n" .
"define ('DB_ADAPTER', 'mysql' );\n" .
"define ('DB_HOST', '" . $this->options['database']['hostname'] . ":".$myPort."' );\n" .
"define ('DB_NAME', '" . $wf. "' );\n" .
"define ('DB_USER', '" . (($this->cc_status==1)?$wf:$this->options['database']['username']). "' );\n" .
"define ('DB_PASS', '" . (($this->cc_status==1)?$this->options['password']:$this->options['database']['password']). "' );\n" .
"define ('DB_RBAC_HOST', '". $this->options['database']['hostname'] .":".$myPort."' );\n" .
"define ('DB_RBAC_NAME', '". $rb . "' );\n" .
"define ('DB_RBAC_USER', '".(($this->cc_status==1)?$rb:$this->options['database']['username']) . "' );\n" .
"define ('DB_RBAC_PASS', '". (($this->cc_status==1)?$this->options['password']:$this->options['database']['password']) . "' );\n" .
"define ('DB_REPORT_HOST', '". $this->options['database']['hostname'] .":".$myPort."' );\n" .
"define ('DB_REPORT_NAME', '". $rp . "' );\n" .
"define ('DB_REPORT_USER', '".(($this->cc_status==1)?$rp:$this->options['database']['username']) . "' );\n" .
"define ('DB_REPORT_PASS', '". (($this->cc_status==1)?$this->options['password']:$this->options['database']['password']) . "' );\n" .
"?>";
$fp = @fopen($db_file, "w");
$this->log("Creating: ".$db_file." => ".((!$fp)?$fp:"OK")."\n");
$ff = @fputs( $fp, $db_text, strlen($db_text));
$this->log("Write: ".$db_file." => ".((!$ff)?$ff:"OK")."\n");
fclose( $fp );
$this->set_admin();
}
return $test;
}
/**
* set_admin
*
* @return void
*/
public function set_admin()
{
mysql_select_db($this->wf_site_name,$this->connection_database);
$q = 'UPDATE USERS SET USR_USERNAME = \''.mysql_escape_string($this->options['admin']['username']).'\', `USR_PASSWORD` = \''.md5($this->options['admin']['password']).'\' WHERE `USR_UID` = \'00000000000000000000000000000001\' LIMIT 1';
$ac = @mysql_query($q,$this->connection_database);
$this->log("Set workflow USERNAME:PASSWORD => ".((!$ac)?mysql_error():"OK")."\n");
mysql_select_db($this->rbac_site_name,$this->connection_database);
$q = 'UPDATE USERS SET USR_USERNAME = \''.mysql_escape_string($this->options['admin']['username']).'\', `USR_PASSWORD` = \''.md5($this->options['admin']['password']).'\' WHERE `USR_UID` = \'00000000000000000000000000000001\' LIMIT 1';
$ac = @mysql_query($q,$this->connection_database);
$this->log("Set rbac USERNAME:PASSWORD => ".((!$ac)?mysql_error():"OK")."\n");
}
/**
* query_sql_file
*
* @param string $file
* @param string $connection
* @return array $report
*/
public function query_sql_file($file, $connection)
{
$report = array(
'SQL_FILE' => $file,
'errors' => array(),
'queries' => 0
);
if( !is_file($file) ) {
$report['errors']="Error reading SQL";
return $report;
}
$content = file_get_contents($file);
$ret = explode(';', $content);
/* Count successful queries only */
$report['queries'] = 0;
@mysql_query("SET NAMES 'utf8';");
foreach($ret as $i => $qr) {
/* Make sure we have a query to execute, then execute it */
if (trim($qr) != "") {
if(!@mysql_query($qr, $connection)) {
$report['errors'][] = "Error in query ".$i.": ".mysql_error();
} else {
$report['queries'] += 1;
}
}
}
return $report;
}
/**
* check_path
*
* @return void
* @todo Empty function
*/
private function check_path()
{
}
/**
* function find_root_path
*
* @param string $path
* @return string $path
*/
private function find_root_path($path)
{
$i = 0; //prevent loop inifinity
while(!is_dir($path) && ($path = dirname($path)) && ((strlen($path)>1) && $i<10)) {
$i++;
}
return $path;
}
/**
* file_permisions
*
* @param string $file
* @param integer $def default value 777
* @return integer $def
*/
public function file_permisions($file, $def = 777)
{
if ( PHP_OS == 'WINNT' )
return $def;
else
return (int)substr(sprintf('%o',@fileperms($file)),-4);
}
/**
* is_dir_writable
*
* @param string $dir default value empty
* @return string $path
*/
public function is_dir_writable($dir = '')
{
if (PHP_OS=='WINNT') {
$dir = $this->find_root_path($dir);
return file_exists ( $dir );
}
else {
$dir = $this->find_root_path($dir);
return (is_writable($dir) && is_readable($dir));
}
}
/**
* getDirectoryFiles
*
* @param string $dir default value empty
* @return string $path
*/
public function getDirectoryFiles($dir,$extension){
$filesArray=array();
if (file_exists($dir)) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
$fileParts=explode(".",$file);
if($fileParts[count($fileParts)-1]==$extension) {
$filesArray[]=$file;
}
}
closedir($handle);
}
}
return $filesArray;
}
/**
* check_db_empty
*
* @param string $dbName
* @return boolean true or false
*/
public function check_db_empty($dbName)
{
$a = @mysql_select_db($dbName,$this->connection_database);
if(!$a) {
return true;
}
$q = @mysql_query('SHOW TABLES',$this->connection_database);
return (@mysql_num_rows($q)>0)?false:true;
}
/**
* check_db
*
* @param string $dbName
* @return Array Array('status' => true or false,'message' => string)
*/
public function check_db($dbName)
{
if(!$this->connection_database) {
return Array('status' => false, 'message' => mysql_error());
}
else {
if(!mysql_select_db($dbName,$this->connection_database) && $this->cc_status!=1) {
return Array('status' => false, 'message' => mysql_error());
}
else {
/* var_dump($this->options['advanced']['ao_db_drop'],$this->cc_status,$this->check_db_empty($dbName));
if(($this->options['advanced']['ao_db_drop']===false && $this->cc_status!=1 && !$this->check_db_empty($dbName)) )
{
return Array('status'=>false,'message'=>'Database is not empty');
}
else
{
return Array('status'=>true,'message'=>'OK');
}*/
if($this->options['advanced']['ao_db_drop']===true || $this->check_db_empty($dbName)) {
return Array('status' => true, 'message' => 'PASSED');
}
else {
return Array('status' => false, 'message' => 'Database is not empty');
}
}
}
}
/**
* check_connection
*
* @return Array $rt
*/
private function check_connection()
{
if(!function_exists("mysql_connect")) {
$this->cc_status = 0;
$rt = Array(
'connection' => false,
'grant' => 0,
'version' => false,
'message' => "php-mysql is Not Installed",
'ao'=>Array(
'ao_db_wf' => false,
'ao_db_rb' => false,
'ao_db_rp' => false
)
);
}
else {
$this->connection_database = @mysql_connect($this->options['database']['hostname'],$this->options['database']['username'],$this->options['database']['password']);
$rt = Array(
'version' => false,
'ao'=>Array(
'ao_db_wf' => false,
'ao_db_rb' => false,
'ao_db_rp' => false
)
);
if(!$this->connection_database) {
$this->cc_status = 0;
$rt['connection'] = false;
$rt['grant'] = 0;
$rt['message'] = "Mysql error: ".mysql_error();
}
else {
preg_match('@[0-9]+\.[0-9]+\.[0-9]+@',mysql_get_server_info($this->connection_database),$version);
$rt['version'] = version_compare(@$version[0],"4.1.0",">=");
$rt['connection'] = true;
$dbNameTest = "PROCESSMAKERTESTDC";
$db = @mysql_query("CREATE DATABASE ".$dbNameTest,$this->connection_database);
if(!$db) {
$this->cc_status = 3;
$rt['grant'] = 3;
//$rt['message'] = "Db GRANTS error: ".mysql_error();
$rt['message'] = "Successful connection";
}
else {
//@mysql_drop_db("processmaker_testGA");
$usrTest = "wfrbtest";
$chkG = "GRANT ALL PRIVILEGES ON `".$dbNameTest."`.* TO ".$usrTest."@'%' IDENTIFIED BY 'sample' WITH GRANT OPTION";
$ch = @mysql_query($chkG,$this->connection_database);
if(!$ch) {
$this->cc_status = 2;
$rt['grant'] = 2;
//$rt['message'] = "USER PRIVILEGES ERROR";
$rt['message'] = "Successful connection";
}
else {
$this->cc_status = 1;
@mysql_query("DROP USER ".$usrTest."@'%'",$this->connection_database);
$rt['grant'] = 1;
$rt['message'] = "Successful connection";
}
@mysql_query("DROP DATABASE ".$dbNameTest,$this->connection_database);
}
// var_dump($wf,$rb,$rp);
}
}
$rt['ao']['ao_db_wf'] = $this->check_db($this->options['advanced']['ao_db_wf']);
$rt['ao']['ao_db_rb'] = $this->check_db($this->options['advanced']['ao_db_rb']);
$rt['ao']['ao_db_rp'] = $this->check_db($this->options['advanced']['ao_db_rp']);
return $rt;
}
/**
* log
*
* @param string $text
* @return void
*/
public function log($text)
{
array_push($this->report,$text);
}
}
?>

View File

@@ -0,0 +1,713 @@
<?php
/*--------------------------------------------------
| TAR/GZIP/BZIP2/ZIP ARCHIVE CLASSES 2.1
| By Devin Doucette
| Copyright (c) 2005 Devin Doucette
| Email: darksnoopy@shaw.ca
+--------------------------------------------------
| Email bugs/suggestions to darksnoopy@shaw.ca
+--------------------------------------------------
| This script has been created and released under
| the GNU GPL and is free to use and redistribute
| only if this copyright statement is not removed
+--------------------------------------------------*/
class archive
{
/**
* This function is the constructor of the class archive
* @param string $name
* @return void
*/
function archive($name)
{
$this->options = array (
'basedir' => ".",
'name' => $name,
'prepend' => "",
'inmemory' => 0,
'overwrite' => 0,
'recurse' => 1,
'storepaths' => 1,
'followlinks' => 0,
'level' => 3,
'method' => 1,
'sfx' => "",
'type' => "",
'comment' => ""
);
$this->files = array ();
$this->exclude = array ();
$this->storeonly = array ();
$this->error = array ();
}
/**
* This function gives options to a archive
* @param array $options
* @return void
*/
function set_options($options)
{
foreach ($options as $key => $value)
$this->options[$key] = $value;
if (!empty ($this->options['basedir'])){
$this->options['basedir'] = str_replace("\\", "/", $this->options['basedir']);
$this->options['basedir'] = preg_replace("/\/+/", "/", $this->options['basedir']);
$this->options['basedir'] = preg_replace("/\/$/", "", $this->options['basedir']);
}
if (!empty ($this->options['name'])){
$this->options['name'] = str_replace("\\", "/", $this->options['name']);
$this->options['name'] = preg_replace("/\/+/", "/", $this->options['name']);
}
if (!empty ($this->options['prepend'])){
$this->options['prepend'] = str_replace("\\", "/", $this->options['prepend']);
$this->options['prepend'] = preg_replace("/^(\.*\/+)+/", "", $this->options['prepend']);
$this->options['prepend'] = preg_replace("/\/+/", "/", $this->options['prepend']);
$this->options['prepend'] = preg_replace("/\/$/", "", $this->options['prepend']) . "/";
}
}
/**
* This function is used to create a archive.
* @return boolean
*/
function create_archive()
{
$this->make_list();
if ($this->options['inmemory'] == 0){
$pwd = getcwd();
chdir($this->options['basedir']);
if ($this->options['overwrite'] == 0 && file_exists($this->options['name'] . ($this->options['type'] == "gzip" || $this->options['type'] == "bzip" ? ".tmp" : ""))){
$this->error[] = "File {$this->options['name']} already exists.";
chdir($pwd);
return 0;
}
else if ($this->archive = @fopen($this->options['name'] . ($this->options['type'] == "gzip" || $this->options['type'] == "bzip" ? ".tmp" : ""), "wb+"))
chdir($pwd);
else{
$this->error[] = "Could not open {$this->options['name']} for writing.";
chdir($pwd);
return 0;
}
}
else
$this->archive = "";
switch ($this->options['type']){
case "zip":
if (!$this->create_zip()){
$this->error[] = "Could not create zip file.";
return 0;
}
break;
case "bzip":
if (!$this->create_tar()){
$this->error[] = "Could not create tar file.";
return 0;
}
if (!$this->create_bzip()){
$this->error[] = "Could not create bzip2 file.";
return 0;
}
break;
case "gzip":
if (!$this->create_tar()){
$this->error[] = "Could not create tar file.";
return 0;
}
if (!$this->create_gzip()){
$this->error[] = "Could not create gzip file.";
return 0;
}
break;
case "tar":
if (!$this->create_tar()){
$this->error[] = "Could not create tar file.";
return 0;
}
}
if ($this->options['inmemory'] == 0){
fclose($this->archive);
if ($this->options['type'] == "gzip" || $this->options['type'] == "bzip")
unlink($this->options['basedir'] . "/" . $this->options['name'] . ".tmp");
}
}
/**
* This function is used for add data to a archive
* @param string $data
* @return void
*/
function add_data($data)
{
if ($this->options['inmemory'] == 0)
fwrite($this->archive, $data);
else
$this->archive .= $data;
}
/**
* This function make a list
* @return void
*/
function make_list()
{
if (!empty ($this->exclude))
foreach ($this->files as $key => $value)
foreach ($this->exclude as $current)
if ($value['name'] == $current['name'])
unset ($this->files[$key]);
if (!empty ($this->storeonly))
foreach ($this->files as $key => $value)
foreach ($this->storeonly as $current)
if ($value['name'] == $current['name'])
$this->files[$key]['method'] = 0;
unset ($this->exclude, $this->storeonly);
}
/**
* Add files a list
* @param array $list
* @return void
*/
function add_files($list)
{
$temp = $this->list_files($list);
foreach ($temp as $current)
$this->files[] = $current;
}
/**
* This function exclude files of a list
* @param array $list
* @return void
*/
function exclude_files($list)
{
$temp = $this->list_files($list);
foreach ($temp as $current)
$this->exclude[] = $current;
}
/**
* This function store files
* @param array $list
*/
function store_files($list)
{
$temp = $this->list_files($list);
foreach ($temp as $current)
$this->storeonly[] = $current;
}
/**
* List files gives a List
* @param array $list
* @return array
*/
function list_files($list)
{
if (!is_array ($list)){
$temp = $list;
$list = array ($temp);
unset ($temp);
}
$files = array ();
$pwd = getcwd();
chdir($this->options['basedir']);
foreach ($list as $current){
$current = str_replace("\\", "/", $current);
$current = preg_replace("/\/+/", "/", $current);
$current = preg_replace("/\/$/", "", $current);
if (strstr($current, "*")){
$regex = preg_replace("/([\\\^\$\.\[\]\|\(\)\?\+\{\}\/])/", "\\\\\\1", $current);
$regex = str_replace("*", ".*", $regex);
$dir = strstr($current, "/") ? substr($current, 0, strrpos($current, "/")) : ".";
$temp = $this->parse_dir($dir);
foreach ($temp as $current2)
if (preg_match("/^{$regex}$/i", $current2['name']))
$files[] = $current2;
unset ($regex, $dir, $temp, $current);
}
else if (@is_dir($current)){
$temp = $this->parse_dir($current);
foreach ($temp as $file)
$files[] = $file;
unset ($temp, $file);
}
else if (@file_exists($current))
$files[] = array ('name' => $current, 'name2' => $this->options['prepend'] .
preg_replace("/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr($current, "/")) ?
substr($current, strrpos($current, "/") + 1) : $current),
'type' => @is_link($current) && $this->options['followlinks'] == 0 ? 2 : 0,
'ext' => substr($current, strrpos($current, ".")), 'stat' => stat($current));
}
chdir($pwd);
unset ($current, $pwd);
usort($files, array ("archive", "sort_files"));
return $files;
}
/**
* This function is for parse a directory name
* @param string $dirname
* @return array
*/
function parse_dir($dirname)
{
if ($this->options['storepaths'] == 1 && !preg_match("/^(\.+\/*)+$/", $dirname))
$files = array (array ('name' => $dirname, 'name2' => $this->options['prepend'] .
preg_replace("/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr($dirname, "/")) ?
substr($dirname, strrpos($dirname, "/") + 1) : $dirname), 'type' => 5, 'stat' => stat($dirname)));
else
$files = array ();
$dir = @opendir($dirname);
while ($file = @readdir($dir)){
$fullname = $dirname . "/" . $file;
if ($file == "." || $file == "..")
continue;
else if (@is_dir($fullname)){
if (empty ($this->options['recurse']))
continue;
$temp = $this->parse_dir($fullname);
foreach ($temp as $file2)
$files[] = $file2;
}
else if (@file_exists($fullname))
$files[] = array ('name' => $fullname, 'name2' => $this->options['prepend'] .
preg_replace("/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr($fullname, "/")) ?
substr($fullname, strrpos($fullname, "/") + 1) : $fullname),
'type' => @is_link($fullname) && $this->options['followlinks'] == 0 ? 2 : 0,
'ext' => substr($file, strrpos($file, ".")), 'stat' => stat($fullname));
}
@closedir($dir);
return $files;
}
/**
* This function sort two files
* @param array $a
* @param array $b
* @return boolean
*/
function sort_files($a, $b)
{
if ($a['type'] != $b['type'])
if ($a['type'] == 5 || $b['type'] == 2)
return -1;
else if ($a['type'] == 2 || $b['type'] == 5)
return 1;
else if ($a['type'] == 5)
return strcmp(strtolower($a['name']), strtolower($b['name']));
else if ($a['ext'] != $b['ext'])
return strcmp($a['ext'], $b['ext']);
else if ($a['stat'][7] != $b['stat'][7])
return $a['stat'][7] > $b['stat'][7] ? -1 : 1;
else
return strcmp(strtolower($a['name']), strtolower($b['name']));
return 0;
}
/**
* This function download a file
* @return void
*/
function download_file()
{
if ($this->options['inmemory'] == 0){
$this->error[] = "Can only use download_file() if archive is in memory. Redirect to file otherwise, it is faster.";
return;
}
switch ($this->options['type']){
case "zip":
header("Content-Type: application/zip");
break;
case "bzip":
header("Content-Type: application/x-bzip2");
break;
case "gzip":
header("Content-Type: application/x-gzip");
break;
case "tar":
header("Content-Type: application/x-tar");
}
$header = "Content-Disposition: attachment; filename=\"";
$header .= strstr($this->options['name'], "/") ? substr($this->options['name'], strrpos($this->options['name'], "/") + 1) : $this->options['name'];
$header .= "\"";
header($header);
header("Content-Length: " . strlen($this->archive));
header("Content-Transfer-Encoding: binary");
header("Cache-Control: no-cache, must-revalidate, max-age=60");
header("Expires: Sat, 01 Jan 2000 12:00:00 GMT");
print($this->archive);
}
}
/**
* This class is derived from the class archive, is imployed to use files .tar
*
*/
class tar_file extends archive
{
/**
* This function is the constructor of the class tar_file
* @param string $name
*/
function tar_file($name)
{
$this->archive($name);
$this->options['type'] = "tar";
}
/**
* This function create a file .tar
* @return boolean
*/
function create_tar()
{
$pwd = getcwd();
chdir($this->options['basedir']);
foreach ($this->files as $current){
if ($current['name'] == $this->options['name'])
continue;
if (strlen($current['name2']) > 99){
$path = substr($current['name2'], 0, strpos($current['name2'], "/", strlen($current['name2']) - 100) + 1);
$current['name2'] = substr($current['name2'], strlen($path));
if (strlen($path) > 154 || strlen($current['name2']) > 99){
$this->error[] = "Could not add {$path}{$current['name2']} to archive because the filename is too long.";
continue;
}
}
$block = pack("a100a8a8a8a12a12a8a1a100a6a2a32a32a8a8a155a12", $current['name2'], sprintf("%07o",
$current['stat'][2]), sprintf("%07o", $current['stat'][4]), sprintf("%07o", $current['stat'][5]),
sprintf("%011o", $current['type'] == 2 ? 0 : $current['stat'][7]), sprintf("%011o", $current['stat'][9]),
" ", $current['type'], $current['type'] == 2 ? @readlink($current['name']) : "", "ustar ", " ",
"Unknown", "Unknown", "", "", !empty ($path) ? $path : "", "");
$checksum = 0;
for ($i = 0; $i < 512; $i++)
$checksum += ord(substr($block, $i, 1));
$checksum = pack("a8", sprintf("%07o", $checksum));
$block = substr_replace($block, $checksum, 148, 8);
if ($current['type'] == 2 || $current['stat'][7] == 0)
$this->add_data($block);
else if ($fp = @fopen($current['name'], "rb")){
$this->add_data($block);
while ($temp = fread($fp, 1048576))
$this->add_data($temp);
if ($current['stat'][7] % 512 > 0){
$temp = "";
for ($i = 0; $i < 512 - $current['stat'][7] % 512; $i++)
$temp .= "\0";
$this->add_data($temp);
}
fclose($fp);
}
else
$this->error[] = "Could not open file {$current['name']} for reading. It was not added.";
}
$this->add_data(pack("a1024", ""));
chdir($pwd);
return 1;
}
/**
* This function is used for extract files of the class tar_file
* @return void
*/
function extract_files()
{
$pwd = getcwd();
chdir($this->options['basedir']);
if ($fp = $this->open_archive()){
if ($this->options['inmemory'] == 1)
$this->files = array ();
while ($block = fread($fp, 512)){
$temp = unpack("a100name/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1type/a100symlink/a6magic/a2temp/a32temp/a32temp/a8temp/a8temp/a155prefix/a12temp", $block);
$file = array (
'name' => $this->options['basedir'] . '/' . $temp['prefix'] . $temp['name'],
'stat' => array (
2 => $temp['mode'],
4 => octdec($temp['uid']),
5 => octdec($temp['gid']),
7 => octdec($temp['size']),
9 => octdec($temp['mtime']),
),
'checksum' => octdec($temp['checksum']),
'type' => $temp['type'],
'magic' => $temp['magic'],
);
if ($file['checksum'] == 0x00000000)
break;
else if (substr($file['magic'], 0, 5) != "ustar"){
$this->error[] = "This script does not support extracting this type of tar file.";
break;
}
$block = substr_replace($block, " ", 148, 8);
$checksum = 0;
for ($i = 0; $i < 512; $i++)
$checksum += ord(substr($block, $i, 1));
if ($file['checksum'] != $checksum)
$this->error[] = "Could not extract from {$this->options['name']}, it is corrupt.";
if ($this->options['inmemory'] == 1){
$file['data'] = fread($fp, $file['stat'][7]);
fread($fp, (512 - $file['stat'][7] % 512) == 512 ? 0 : (512 - $file['stat'][7] % 512));
unset ($file['checksum'], $file['magic']);
$this->files[] = $file;
}
else if ($file['type'] == 5){
if (!is_dir($file['name']))
//mkdir($file['name'], $file['stat'][2]);
mkdir($file['name'], 0775);
}
else if ($this->options['overwrite'] == 0 && file_exists($file['name'])){
$this->error[] = "{$file['name']} already exists.";
continue;
}
else if ($file['type'] == 2){
symlink($temp['symlink'], $file['name']);
//chmod($file['name'], $file['stat'][2]);
}
else if ($new = @fopen($file['name'], "wb")){
fwrite($new, fread($fp, $file['stat'][7]));
if ((512 - $file['stat'][7] % 512) != 512) {
fread($fp, (512 - $file['stat'][7] % 512));
}
//fread($fp, (512 - $file['stat'][7] % 512) == 512 ? 0 : (512 - $file['stat'][7] % 512));
fclose($new);
//chmod($file['name'], $file['stat'][2]);
chmod($file['name'], 0777);
$this->files[] = $file['name'];
}
else{
$this->error[] = "Could not open {$file['name']} for writing.";
continue;
}
//chown($file['name'], $file['stat'][4]);
//chgrp($file['name'], $file['stat'][5]);
@touch($file['name'], $file['stat'][9]);
unset ($file);
}
}
else
$this->error[] = "Could not open file {$this->options['name']}";
chdir($pwd);
}
/**
* This function open a archive of the class tar_file
* @return void
*/
function open_archive()
{
return @fopen($this->options['name'], "rb");
}
}
/**
* This class is derived of the class archive, is employed to use archives .gzip
*
*/
class gzip_file extends tar_file
{
/**
* This function is the constructor of the class gzip_file
* @param string $name
* @return void
*/
function gzip_file($name)
{
$this->tar_file($name);
$this->options['type'] = "gzip";
}
/**
* This function is employed to create files .gzip
* @return boolean
*/
function create_gzip()
{
if ($this->options['inmemory'] == 0){
$pwd = getcwd();
chdir($this->options['basedir']);
if ($fp = gzopen($this->options['name'], "wb{$this->options['level']}")){
fseek($this->archive, 0);
while ($temp = fread($this->archive, 1048576))
gzwrite($fp, $temp);
gzclose($fp);
chdir($pwd);
}
else{
$this->error[] = "Could not open {$this->options['name']} for writing.";
chdir($pwd);
return 0;
}
}
else
$this->archive = gzencode($this->archive, $this->options['level']);
return 1;
}
/**
* This function open a archive of the class gzip_file
* @return void
*/
function open_archive()
{
return @gzopen($this->options['name'], "rb");
}
}
/**
*
* This class is derived from the class archive, is employed to use files .bzip
*
*/
class bzip_file extends tar_file
{
/**
* This function is the constructor of the class bzip_file
* @param string $name
* @return void
*/
function bzip_file($name)
{
$this->tar_file($name);
$this->options['type'] = "bzip";
}
/**
* This function is employed to create files .bzip
* @return boolean
*/
function create_bzip()
{
if ($this->options['inmemory'] == 0){
$pwd = getcwd();
chdir($this->options['basedir']);
if ($fp = bzopen($this->options['name'], "wb")){
fseek($this->archive, 0);
while ($temp = fread($this->archive, 1048576))
bzwrite($fp, $temp);
bzclose($fp);
chdir($pwd);
}
else{
$this->error[] = "Could not open {$this->options['name']} for writing.";
chdir($pwd);
return 0;
}
}
else
$this->archive = bzcompress($this->archive, $this->options['level']);
return 1;
}
/**
* This function open a archive of the class bzip_file
* @return void
*/
function open_archive()
{
return @bzopen($this->options['name'], "rb");
}
}
/**
* This class is derived from the class archive, is imployed to use files .zip
*/
class zip_file extends archive
{
function zip_file($name)
{
$this->archive($name);
$this->options['type'] = "zip";
}
/**
* This function is used to create archives .zip
* @return boolean
*/
function create_zip()
{
$files = 0;
$offset = 0;
$central = "";
if (!empty ($this->options['sfx']))
if ($fp = @fopen($this->options['sfx'], "rb")){
$temp = fread($fp, filesize($this->options['sfx']));
fclose($fp);
$this->add_data($temp);
$offset += strlen($temp);
unset ($temp);
}
else
$this->error[] = "Could not open sfx module from {$this->options['sfx']}.";
$pwd = getcwd();
chdir($this->options['basedir']);
foreach ($this->files as $current){
if ($current['name'] == $this->options['name'])
continue;
$timedate = explode(" ", date("Y n j G i s", $current['stat'][9]));
$timedate = ($timedate[0] - 1980 << 25) | ($timedate[1] << 21) | ($timedate[2] << 16) |
($timedate[3] << 11) | ($timedate[4] << 5) | ($timedate[5]);
$block = pack("VvvvV", 0x04034b50, 0x000A, 0x0000, (isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate);
if ($current['stat'][7] == 0 && $current['type'] == 5){
$block .= pack("VVVvv", 0x00000000, 0x00000000, 0x00000000, strlen($current['name2']) + 1, 0x0000);
$block .= $current['name2'] . "/";
$this->add_data($block);
$central .= pack("VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000,
(isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate,
0x00000000, 0x00000000, 0x00000000, strlen($current['name2']) + 1, 0x0000, 0x0000, 0x0000, 0x0000, $current['type'] == 5 ? 0x00000010 : 0x00000000, $offset);
$central .= $current['name2'] . "/";
$files++;
$offset += (31 + strlen($current['name2']));
}
else if ($current['stat'][7] == 0){
$block .= pack("VVVvv", 0x00000000, 0x00000000, 0x00000000, strlen($current['name2']), 0x0000);
$block .= $current['name2'];
$this->add_data($block);
$central .= pack("VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000,
(isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate,
0x00000000, 0x00000000, 0x00000000, strlen($current['name2']), 0x0000, 0x0000, 0x0000, 0x0000, $current['type'] == 5 ? 0x00000010 : 0x00000000, $offset);
$central .= $current['name2'];
$files++;
$offset += (30 + strlen($current['name2']));
}
else if ($fp = @fopen($current['name'], "rb")){
$temp = fread($fp, $current['stat'][7]);
fclose($fp);
$crc32 = crc32($temp);
if (!isset($current['method']) && $this->options['method'] == 1){
$temp = gzcompress($temp, $this->options['level']);
$size = strlen($temp) - 6;
$temp = substr($temp, 2, $size);
}
else
$size = strlen($temp);
$block .= pack("VVVvv", $crc32, $size, $current['stat'][7], strlen($current['name2']), 0x0000);
$block .= $current['name2'];
$this->add_data($block);
$this->add_data($temp);
unset ($temp);
$central .= pack("VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000,
(isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate,
$crc32, $size, $current['stat'][7], strlen($current['name2']), 0x0000, 0x0000, 0x0000, 0x0000, 0x00000000, $offset);
$central .= $current['name2'];
$files++;
$offset += (30 + strlen($current['name2']) + $size);
}
else
$this->error[] = "Could not open file {$current['name']} for reading. It was not added.";
}
$this->add_data($central);
$this->add_data(pack("VvvvvVVv", 0x06054b50, 0x0000, 0x0000, $files, $files, strlen($central), $offset,
!empty ($this->options['comment']) ? strlen($this->options['comment']) : 0x0000));
if (!empty ($this->options['comment']))
$this->add_data($this->options['comment']);
chdir($pwd);
return 1;
}
}
?>

View File

@@ -0,0 +1,231 @@
<?php
/**
* class.calendar.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.
*
*
*
* @name calendar
* @created 2010-03-22
*
* @author Hugo Loza <hugo@colosa.com> 2010-03-22
*/
require_once ( "classes/model/CalendarDefinition.php" );
/**
* A Calendar object where it is defined Working Days, Business Hours and Holidays
* A Calendar is applied to a User, Process or Task
* Extends CalendarDefinition.
*
* @author Hugo Loza <hugo@colosa.com> 2010-03-22
* @uses CalendarDefinition
*
*/
class calendar extends CalendarDefinition
{
/**
* @param string(32) $userUid
* @param string(32) $proUid
* @param string(32) $tasUid
*/
function calendar($userUid = NULL, $proUid = NULL, $tasUid = NULL)
{
$this->userUid = $userUid;
$this->proUid = $proUid;
$this->tasUid = $tasUid;
$this->calendarLog = "";
$this->setupCalendar($userUid,$proUid,$tasUid);
}
/**
* Small function used to add important information about the calcs and actions
* to the log (that log will be saved)
*
* @name addCalendarLog
* @param text $msg
* @access public
*
*/
function addCalendarLog($msg)
{
$this->calendarLog .= "\n".date("D M j G:i:s T Y").": " . $msg;
}
/**
* setupCalendar is used to generate a valid instance of calendar using $userUid, $proUid and $tasUid
* to find a valid calendar. If there is no valid calendar then use the Default
*
* @name setupCalendar
* @param string(32) $userUid
* @param string(32) $proUid
* @param string(32) $tasUid
* @return void
*/
function setupCalendar($userUid,$proUid,$tasUid)
{
$calendarDefinition = $this->getCalendarFor($userUid,$proUid,$tasUid);
$this->calendarUid = $calendarDefinition['CALENDAR_UID'];
$this->calendarDefinition = $calendarDefinition;
}
/**
* getnextValidBusinessHoursrange is used recursivily to find a valid BusinessHour
* for the given $date and $time. This function use all the exeptions defined for
* Working days, Business Hours and Holidays.
*
* @author Hugo Loza <hugo@colosa.com>
* @name getNextValidBusinessHoursRange
* @param date $date
* @param time $time
*
* @var array $businessHoursA Object with all the infromation about the valid Business Hours found
* $return array('DATE'=>$date,'TIME'=>$time,'BUSINESS_HOURS'=>$businessHoursA)
*/
function getNextValidBusinessHoursRange($date, $time)
{
$this->addCalendarLog("================= Start : $date,$time ================");
//First Validate if is a valid date
$sw_valid_date = false;
$sw_date_changed = false;
while (!$sw_valid_date) {
$dateArray = explode("-",$date);
$hour = 0;
$minute = 0;
$second = 0;
$month = $dateArray[1];
$day = $dateArray[2];
$year = $dateArray[0];
$weekDay = date("w",mktime($hour,$minute,$second,$month,$day,$year));
$weekDayLabel = date("l",mktime($hour,$minute,$second,$month,$day,$year));
$dateInt = mktime($hour,$minute,$second,$month,$day,$year);
$this->addCalendarLog("**** $weekDayLabel ($weekDay) * $date");
$sw_week_day = false;
$sw_not_holiday = true;
if(in_array($weekDay,$this->calendarDefinition['CALENDAR_WORK_DAYS_A'])){
$sw_week_day = true;
}
if(!$sw_week_day){
$this->addCalendarLog("Valid working Dates: ".$this->calendarDefinition['CALENDAR_WORK_DAYS_A']);
$this->addCalendarLog("- Non working Day");
}
foreach ($this->calendarDefinition['HOLIDAY'] as $key => $holiday) {
//Normalize Holiday date to SAME year of date
$holidayStartA = explode(" ",$holiday['CALENDAR_HOLIDAY_START']);
$holidayStartA = explode("-",$holidayStartA[0]);
$normalizedHolidayStart = date("Y-m-d",mktime($hour,$minute,$second,$holidayStartA[1],$holidayStartA[2],$year));
$normalizedHolidayStartInt = mktime($hour,$minute,$second,$holidayStartA[1],$holidayStartA[2],$year);
$holidayEndA = explode(" ",$holiday['CALENDAR_HOLIDAY_END']);
$holidayEndA = explode("-",$holidayEndA[0]);
$normalizedHolidayEnd = date("Y-m-d",mktime($hour,$minute,$second,$holidayEndA[1],$holidayEndA[2],$year));
$normalizedHolidayEndInt = mktime($hour,$minute,$second,$holidayEndA[1],$holidayEndA[2],$year);
$sw_not_holiday_aux = true;
if( $dateInt >= $normalizedHolidayStartInt && $dateInt <= $normalizedHolidayEndInt ){
$sw_not_holiday = false;
$sw_not_holiday_aux = false;
}
if(!$sw_not_holiday_aux){
$this->addCalendarLog("It is a holiday -> ".$holiday['CALENDAR_HOLIDAY_NAME']." ($normalizedHolidayStart - $normalizedHolidayEnd)");
}
}
$sw_valid_date=$sw_week_day && $sw_not_holiday;
if(!$sw_valid_date){//Go to next day
$date=date("Y-m-d",mktime($hour,$minute+1,$second,$month,$day+1,$year));
$sw_date_changed=true;
}else{
$this->addCalendarLog("FOUND VALID DATE -> $date");
//We got a valid day, now get the valid Business Hours
//Here Need to find a rule to get the most nea
$businessHoursA=array();
$prevHour="00:00";
if($sw_date_changed){// If date has changed then Use the first available period
$time="00:01";
}
foreach($this->calendarDefinition['BUSINESS_DAY'] as $keyBH => $businessHours){
// First the period may correspond to ALL or to the current week day
if(($businessHours['CALENDAR_BUSINESS_DAY']==7)||($businessHours['CALENDAR_BUSINESS_DAY']==$weekDay)){
$this->addCalendarLog("Validating ($time/$prevHour) From: ".$businessHours['CALENDAR_BUSINESS_START']." to ".$businessHours['CALENDAR_BUSINESS_END']);
//Prev Hour
$prevHourA = explode(":",$prevHour);
$prevHourSeconds = ($prevHourA[0]*60*60)+($prevHour[1]*60);
$calendarBusinessStartA = explode(":",$businessHours['CALENDAR_BUSINESS_START']);
$calendarBusinessStartSeconds = ($calendarBusinessStartA[0]*60*60)+($calendarBusinessStartA[1]*60);
$calendarBusinessEndA = explode(":",$businessHours['CALENDAR_BUSINESS_END']);
$calendarBusinessEndSeconds = ($calendarBusinessEndA[0]*60*60)+($calendarBusinessEndA[1]*60);
$timeAuxA = explode(":",$time);
$timeAuxSeconds = ($timeAuxA[0]*60*60)+($timeAuxA[1]*60);
if(($timeAuxSeconds>=$prevHourSeconds)&&($timeAuxSeconds<$calendarBusinessEndSeconds)){
$this->addCalendarLog("*** FOUND VALID BUSINESS HOUR ".$businessHours['CALENDAR_BUSINESS_START']." - ".$businessHours['CALENDAR_BUSINESS_END']);
if($timeAuxSeconds<$calendarBusinessStartSeconds){//Out of range then assign first hour
$this->addCalendarLog("Set to default start hour to: ".$businessHours['CALENDAR_BUSINESS_START']);
$time = $businessHours['CALENDAR_BUSINESS_START'];
}
$prevHour = $businessHours['CALENDAR_BUSINESS_END'];
$businessHoursA = $businessHours;
}
}
}
}
if(empty($businessHoursA)){
$this->addCalendarLog("> No Valid Business Hour found for current date, go to next");
$date = date("Y-m-d", mktime($hour,$minute+1,$second,$month,$day+1,$year));
$sw_date_changed = true;
$sw_valid_date = false;
}
}
$return['DATE'] = $date;
$return['TIME'] = $time;
$return['BUSINESS_HOURS'] = $businessHoursA;
return $return;
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,423 @@
<?php
/**
* class.configuration.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.
*
*/
//
// It works with the table CONFIGURATION in a WF dataBase
//
// Copyright (C) 2007 COLOSA
//
// License: LGPL, see LICENSE
////////////////////////////////////////////////////
/**
* ProcessConfiguration - ProcessConfiguration class
* @package ProcessMaker
* @author David S. Callizaya S.
* @copyright 2007 COLOSA
*/
require_once 'classes/model/Configuration.php';
/**
* Extends Configuration
*
*
* @copyright 2007 COLOSA
* @version Release: @package_version@
*/
class Configurations // extends Configuration
{
var $aConfig = array();
private $Configuration = null;
/**
* Set Configurations
* @return void
*/
function Configurations()
{
$this->Configuration = new Configuration();
}
/**
* arrayClone
*
* @param array &$object Source array
* @param array &$cloneObject Array duplicate
* @return void
*/
function arrayClone( &$object, &$cloneObject )
{
if (is_array($object)) {
foreach($object as $k => $v ) {
$cloneObject[$k] = NULL;
$this->arrayClone( $object[$k], $cloneObject[$k] );
}
} else {
if (is_object($object)) {
} else {
$cloneObject=NULL;
}
}
}
/**
* configObject
*
* @param object &$object
* @param array &$from
* @return void
*/
function configObject( &$object, &$from )
{
if (!(is_object($object) || is_array($object)))
return;
if (!isset($from))
$from = &$this->aConfig;
foreach($from as $k => $v ) {
if (isset($v) && array_key_exists($k,$object)) {
if (is_object($v))
throw new Exception( 'Object is not permited inside configuration array.' );
if (is_object($object)) {
if (is_array($v))
$this->configObject($object->{$k}, $v);
else
$object->{$k} = $v;
} else {
if (is_array($object)) {
if (is_array($v))
$this->configObject($object[$k], $v);
else
$object[$k] = $v;
}
}
}
}
}
/**
* loadConfig
*
* @param object &$object
* @param string $cfg
* @param object $obj
* @param string $pro
* @param string $usr
* @param string $app
* @return void
*/
function loadConfig(&$object, $cfg, $obj, $pro = '', $usr = '', $app = '')
{
$this->Fields = array();
if ($this->Configuration->exists( $cfg, $obj, $pro, $usr, $app ))
$this->Fields = $this->Configuration->load( $cfg, $obj, $pro, $usr, $app );
$aConfig = $this->aConfig;
if (isset($this->Fields['CFG_VALUE']))
$aConfig = unserialize($this->Fields['CFG_VALUE']);
if (!is_array($aConfig))
$aConfig = $this->aConfig;
$this->aConfig = $aConfig;
$this->configObject($object,$this->aConfig);
}
/**
* saveConfig
*
* @param object &$object
* @param array &$from
* @return void
*/
function saveConfig($cfg,$obj,$pro='',$usr='',$app='')
{
$aFields = array(
'CFG_UID' => $cfg,
'OBJ_UID' => $obj,
'PRO_UID' => $pro,
'USR_UID' => $usr,
'APP_UID' => $app,
'CFG_VALUE' => serialize($this->aConfig)
);
if ($this->Configuration->exists($cfg,$obj,$pro,$usr,$app)) {
$this->Configuration->update($aFields);
} else {
$this->Configuration->create($aFields);
$this->Configuration->update($aFields);
}
}
/**
* saveObject
*
* @param object &$object
* @param array &$from
* @return void
*/
function saveObject(&$object,$cfg,$obj,$pro='',$usr='',$app='')
{
$aFields = array(
'CFG_UID' => $cfg,
'OBJ_UID' => $obj,
'PRO_UID' => $pro,
'USR_UID' => $usr,
'APP_UID' => $app,
'CFG_VALUE' => serialize(array(&$object))
);
if ($this->Configuration->exists($cfg,$obj,$pro,$usr,$app)) {
$this->Configuration->update($aFields);
} else {
$this->Configuration->create($aFields);
$this->Configuration->update($aFields);
}
}
/**
* loadObject
* this function is deprecated, we dont know why return an object, use the function getConfiguration below
*
* @param string $cfg
* @param object $obj
* @param string $pro
* @param string $usr
* @param string $app
* @return void
*/
function loadObject($cfg, $obj, $pro = '', $usr = '', $app = '')
{
$objectContainer=array((object) array());
$this->Fields = array();
if ($this->Configuration->exists( $cfg, $obj, $pro, $usr, $app ))
$this->Fields = $this->Configuration->load( $cfg, $obj, $pro, $usr, $app );
else
return $objectContainer[0];
if (isset($this->Fields['CFG_VALUE']))
$objectContainer = unserialize($this->Fields['CFG_VALUE']);
if (!is_array($objectContainer)||sizeof($objectContainer)!=1)
return (object) array();
else
return $objectContainer[0];
}
/**
* getConfiguration
*
* @param string $cfg
* @param object $obj
* @param string $pro
* @param string $usr
* @param string $app
* @return void
*/
function getConfiguration($cfg, $obj, $pro = '', $usr = '', $app = '')
{
try {
$oCfg = ConfigurationPeer::retrieveByPK( $cfg, $obj, $pro, $usr, $app );
if (!is_null($oCfg)) {
$row = $oCfg->toArray(BasePeer::TYPE_FIELDNAME);
$result = unserialize($row['CFG_VALUE']);
if ( is_array($result) && sizeof($result)==1 ) {
return $result[0];
} else {
return $result;
}
}
else {
return null;
}
}
catch (Exception $oError) {
return null;
}
}
/**
* setConfig
*
* @param string $route
* @param object &$object
* @param object &$to
* @return void
*/
function setConfig( $route , &$object , &$to )
{
if (!isset($to))
$to = &$this->aConfig;
$routes = explode(',',$route);
foreach($routes as $r) {
$ro = explode('/',$r);
if (count($ro)>1) {
$rou = $ro;
unset($rou[0]);
if ($ro[0]==='*') {
foreach($object as $k => $v ) {
if (is_object($object)) {
if (!isset($to[$k]))
$to[$k] = array();
$this->setConfig(implode('/',$rou),$object->{$k},$to[$k]);
} else {
if (is_array($object)) {
if (!isset($to[$k]))
$to[$k] = array();
$this->setConfig(implode('/',$rou),$object[$k],$to[$k]);
}
}
}
} else {
if (is_object($object)) {
if (!isset($to[$ro[0]]))
$to[$ro[0]] = array();
$this->setConfig(implode('/',$rou),$object->{$ro[0]},$to[$ro[0]]);
} else {
if (is_array($object)) {
if (!isset($to[$ro[0]]))
$to[$ro[0]] = array();
$this->setConfig(implode('/',$rou),$object[$ro[0]],$to[$ro[0]]);
} else {
$to = $object;
}
}
}
} else {
if ($ro[0]==='*') {
foreach($object as $k => $v ) {
if (is_object($object)) {
if (!isset($to[$k]))
$to[$k] = array();
$to[$k] = $object->{$k};
} else {
if (is_array($object)) {
if (!isset($to[$k]))
$to[$k] = array();
$to[$k] = $object[$k];
}
}
}
} else {
if (!isset($to[$r]))
$to[$r] = array();
if (is_object($object)) {
$to[$r] = $object->{$r};
} elseif (is_array($object)) {
$to[$r] = $object[$r];
} else {
$to[$r] = $object;
}
}
}
}
}
function getDateFormats(){
$formats[] = Array(
'id'=>'Y-m-d H:i:s', //the id , don't translate
'name'=>G::loadTranslation('ID_DATE_FORMAT_1') //'Y-m-d H:i:s' i.e: '2010-11-17 10:25:07'
);
$formats[] = Array(
'id'=>'d/m/Y',
'name'=>G::loadTranslation('ID_DATE_FORMAT_2') //'d/m/Y' i.e:'17/11/2010'
);
$formats[] = Array(
'id'=>'m/d/Y',
'name'=>G::loadTranslation('ID_DATE_FORMAT_3')//'m/d/Y' i.e:'11/17/2010'
);
$formats[] = Array(
'id'=>'Y/d/m',
'name'=>G::loadTranslation('ID_DATE_FORMAT_4')//'Y/d/m' i.e:'2010/17/11'
);
$formats[] = Array(
'id'=>'Y/m/d',
'name'=>G::loadTranslation('ID_DATE_FORMAT_5')//'Y/m/d' i.e:'2010/11/17'
);
$formats[] = Array(
'id'=>'F j, Y, g:i a',
'name'=>G::loadTranslation('ID_DATE_FORMAT_6')//'F j, Y, g:i a' i.e:'November 17, 2010, 10:45 am'
);
$formats[] = Array(
'id'=>'m.d.y',
'name'=>G::loadTranslation('ID_DATE_FORMAT_7')//'m.d.y' i.e: '11.17.10'
);
$formats[] = Array(
'id'=>'j, n, Y',
'name'=>G::loadTranslation('ID_DATE_FORMAT_8')//'j, n, Y' i.e:'17,11,2010'
);
$formats[] = Array(
'id'=>'D M j G:i:s T Y',
'name'=>G::loadTranslation('ID_DATE_FORMAT_9')//'D M j G:i:s T Y' i.e:'Thu Nov 17 10:48:18 BOT 2010'
);
$formats[] = Array(
'id'=>'D d M, Y',
'name'=>G::loadTranslation('ID_DATE_FORMAT_10')//'D d M, Y' i.e:'Thu 17 Nov, 2010'
);
$formats[] = Array(
'id'=>'D M, Y',
'name'=>G::loadTranslation('ID_DATE_FORMAT_11')//'D M, Y' i.e:'Thu Nov, 2010'
);
$formats[] = Array(
'id'=>'d M, Y',
'name'=>G::loadTranslation('ID_DATE_FORMAT_12')//'d M, Y' i.e:'17 Nov, 2010'
);
$formats[] = Array(
'id'=>'d m, Y',
'name'=>G::loadTranslation('ID_DATE_FORMAT_13')//'d m, Y' i.e:'17 11, 2010'
);
return $formats;
}
function getUserNameFormats(){
$formats[] = Array(
'id'=>'@firstName @lastName', //the id , don't translate
'name'=>G::loadTranslation('ID_USERNAME_FORMAT_1') //label displayed, can be translated
);
$formats[] = Array(
'id'=>'@firstName @lastName (@userName)',
'name'=>G::loadTranslation('ID_USERNAME_FORMAT_2')
);
$formats[] = Array(
'id'=>'@userName',
'name'=>G::loadTranslation('ID_USERNAME_FORMAT_3')
);
$formats[] = Array(
'id'=>'@userName (@firstName @lastName)',
'name'=>G::loadTranslation('ID_USERNAME_FORMAT_4')
);
$formats[] = Array(
'id'=>'@lastName @firstName',
'name'=>G::loadTranslation('ID_USERNAME_FORMAT_5')
);
$formats[] = Array(
'id'=>'@lastName, @firstName',
'name'=>G::loadTranslation('ID_USERNAME_FORMAT_6')
);
$formats[] = Array(
'id'=>'@lastName, @firstName (@userName)',
'name'=>G::loadTranslation('ID_USERNAME_FORMAT_7')
);
return $formats;
}
}
?>

View File

@@ -0,0 +1,177 @@
<?php
/**
* class.dashboards.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.
*
*/
/**
* Dashboards - Dashboard class
* @package ProcessMaker
* @author Julio Cesar Laura Avenda<64>o
* @copyright 2007 COLOSA
*/
class Dashboards
{
/**
* This function is used for get configuration of the dashboards
* @param string $sUserUID
* @return array configuration of the dashboard
*/
function getConfiguration($sUserUID)
{
require_once 'classes/model/Configuration.php';
$oConfiguration = new Configuration();
$sDelimiter = DBAdapter::getStringDelimiter();
$oCriteria = new Criteria('workflow');
$oCriteria->add(ConfigurationPeer::CFG_UID, 'Dashboards');
$oCriteria->add(ConfigurationPeer::OBJ_UID, '');
$oCriteria->add(ConfigurationPeer::PRO_UID, '');
$oCriteria->add(ConfigurationPeer::USR_UID, $sUserUID);
$oCriteria->add(ConfigurationPeer::APP_UID, '');
if (ConfigurationPeer::doCount($oCriteria) == 0) {
$oConfiguration->create(array('CFG_UID' => 'Dashboards', 'OBJ_UID' => '', 'CFG_VALUE' => '', 'PRO_UID' => '', 'USR_UID' => $sUserUID, 'APP_UID' => ''));
$aConfiguration = array();
}
else {
$aConfiguration = $oConfiguration->load('Dashboards', '', '', $sUserUID, '');
if ($aConfiguration['CFG_VALUE'] != '') {
$aConfiguration = unserialize($aConfiguration['CFG_VALUE']);
}
else {
$aConfiguration = array();
}
}
return $aConfiguration;
}
/**
* This function is used for save configuration of the dashboards
* @param string $sUserUID
* @param array $aConfiguration
*/
function saveConfiguration($sUserUID, $aConfiguration)
{
require_once 'classes/model/Configuration.php';
$oConfiguration = new Configuration();
$oConfiguration->update(array('CFG_UID' => 'Dashboards',
'OBJ_UID' => '',
'CFG_VALUE' => serialize($aConfiguration),
'PRO_UID' => '',
'USR_UID' => $sUserUID,
'APP_UID' => ''));
}
/**
* This function is used for get objects of the dashboards
* @param string $sUserUID
* @return object Services_JSON
*/
function getDashboardsObject($sUserUID)
{
$aConfiguration = $this->getConfiguration($sUserUID);
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$aAvailableDashboards = $oPluginRegistry->getDashboards();
$aLeftColumn = array ();
$aRightColumn = array ();
$iColumn = 0;
G::LoadClass('report');
$oReport = new Report();
$aReports = $oReport->getAvailableReports();
foreach ($aConfiguration as $aDashboard) {
if ($aDashboard['class'] == 'PM_Reports') {
if (!isset($aDashboard['element'])) $aDashboard['element'] = '';
foreach ($aReports as $sReport) {
$bFree = false;
if (($aDashboard['class'] == 'PM_Reports') && ($aDashboard['element'] == $sReport)) {
$bFree = true;
}
if ($bFree) {
$oElement = $aDashboard['object'];
$oElement->class = $aDashboard['class'];
$oElement->type = $aDashboard['type'];
$oElement->element = $aDashboard['element'];
if ($iColumn === 0) {
$aLeftColumn[] = $oElement;
}
else {
$aRightColumn[] = $oElement;
}
$iColumn = 1 - $iColumn;
}
}
}
else {
require_once PATH_PLUGINS. $aDashboard['class'] . PATH_SEP . 'class.' . $aDashboard['class'] . '.php';
$sClassName = $aDashboard['class'] . 'Class';
$oInstance = new $sClassName();
$aCharts = $oInstance->getAvailableCharts();
foreach ($aCharts as $sChart) {
$bFree = false;
foreach ($aAvailableDashboards as $sDashboardClass) {
if (($aDashboard['class'] == $sDashboardClass) && ($aDashboard['element'] == $sChart)) {
$bFree = true;
}
}
if ($bFree) {
$oElement = $oInstance->getChart($sChart);
$oElement->class = $aDashboard['class'];
$oElement->type = $aDashboard['type'];
$oElement->element = $aDashboard['element'];
if ($iColumn === 0) {
$aLeftColumn[] = $oElement;
}
else {
$aRightColumn[] = $oElement;
}
$iColumn = 1 - $iColumn;
}
}
if (method_exists($oInstance, 'getAvailablePages')) {
$aPages = $oInstance->getAvailablePages();
foreach ($aPages as $sPage) {
$bFree = false;
foreach ($aAvailableDashboards as $sDashboardClass) {
if (($aDashboard['class'] == $sDashboardClass) && ($aDashboard['element'] == $sPage)) {
$bFree = true;
}
}
if ($bFree) {
$oElement = $oInstance->getPage($sPage);
$oElement->class = $aDashboard['class'];
$oElement->type = $aDashboard['type'];
$oElement->element = $aDashboard['element'];
if ($iColumn === 0) {
$aLeftColumn[] = $oElement;
}
else {
$aRightColumn[] = $oElement;
}
$iColumn = 1 - $iColumn;
}
}
}
}
}
$aDashboards = array($aLeftColumn, $aRightColumn);
$oJSON = new Services_JSON();
return $oJSON->encode($aDashboards);
}
}

View File

@@ -0,0 +1,478 @@
<?php
/**
* class.dates.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.
*
*/
/*
* Created on 21/01/2008
* This class is used for handling dates
*
* @author David Callizaya <davidsantos@colosa.com>
*/
require_once ( "classes/model/TaskPeer.php" );
require_once ( "classes/model/HolidayPeer.php" );
class dates {
private $holidays = array();
private $weekends = array();
private $range = array();
private $skipEveryYear = true;
private $calendarDays = false; //by default we are using working days
private $hoursPerDay = 8; //you should change this
/**
* Function that calculate a final date based on $sInitDate and $iDuration
* This function also uses a Calendar component (class.calendar.php) where all the definition of
* a User, task, Process or default calendar is defined. base on that information is possible to setup different calendars
* and apply them to a task, process or user. Each calendar have Working Days, Business Hours and Holidays
*
* @name calculateDate
* @access public
* @author Hugo Loza <hugo@colosa.com>
* @param date $sInitDate
* @param double $iDuration
* @param string $sTimeUnit
* @param string $iTypeDay
* @param string $UsrUid
* @param string $ProUid
* @param string $TasUid
* @return array('DUE_DATE'=>'Final calculated date formatted as Y-m-d H:i:s','DUE_DATE_SECONDS'=>'Final calculated date in seconds','OLD_DUE_DATE'=>'Using deprecate4d function','OLD_DUE_DATE_SECONDS'=>'Using deprecated function','DUE_DATE_LOG'=>'Log of all the calculations made')
* @todo test this function with negative durations (for events)
*
*
*/
function calculateDate( $sInitDate, $iDuration, $sTimeUnit, $iTypeDay, $UsrUid = NULL, $ProUid = NULL, $TasUid =NULL )
{
$oldDate=$this->calculateDate_noCalendar( $sInitDate, $iDuration, $sTimeUnit, $iTypeDay, $UsrUid, $ProUid, $TasUid);
//Set Calendar when the object is instanced in this order/priority (Task, User, Process, Default)
G::LoadClass('calendar');
$calendarObj=new calendar($UsrUid,$ProUid,$TasUid);
//Get next Business Hours/Range based on :
switch(strtoupper($sTimeUnit)){
case 'DAYS': $hoursToProcess=$iDuration*8; break;//In Hours
default: $hoursToProcess=$iDuration; break;//In Hours
}
$dateArray = explode(" ",$sInitDate);
$currentDate = $dateArray[0];
$currentTime = isset($dateArray[1])? $dateArray[1]: "00:00:00";
$calendarObj->addCalendarLog(">>>>> Hours to Process: $hoursToProcess");
$calendarObj->addCalendarLog(">>>>> Current Date: $currentDate");
$calendarObj->addCalendarLog(">>>>> Current Time: $currentTime");
$array_hours = explode(":",$currentTime);
$seconds2 = $array_hours[2];
$minutes2 = 0;
while($hoursToProcess>0){
$validBusinessHour=$calendarObj->getNextValidBusinessHoursRange($currentDate,$currentTime);
//For Date/Time operations
$currentDateA = explode("-",$validBusinessHour['DATE']);
$currentTimeA = explode(":",$validBusinessHour['TIME']);
$hour = $currentTimeA[0];
$minute = $currentTimeA[1];
$second = isset($currentTimeA[2])?$currentTimeA[2]:0;
$month = $currentDateA[1];
$day = $currentDateA[2];
$year = $currentDateA[0];
$normalizedDate = date("Y-m-d H:i:s",mktime($hour,$minute,$second,$month,$day,$year));
$normalizedDateInt = mktime($hour,$minute,$second,$month,$day,$year);
$normalizedDateSeconds = ($hour*60*60)+($minute*60);
$arrayHour = explode(".",$hoursToProcess);
if(isset($arrayHour[1])){
$minutes1 = $arrayHour[1];
$cadm = strlen($minutes1);
$minutes2 = (($minutes1/pow(10,$cadm))*60);
}
$possibleTime=date("Y-m-d H:i:s",mktime($hour+$hoursToProcess,$minute+$minutes2,$second+$seconds2,$month,$day,$year));
$possibleTimeInt=mktime($hour+$hoursToProcess,$minute+$minutes2,$second+$seconds2,$month,$day,$year);
$offsetPermitedMinutes="0";
$calendarBusinessEndA=explode(":",$validBusinessHour['BUSINESS_HOURS']['CALENDAR_BUSINESS_END']);
$calendarBusinessEndNormalized=date("Y-m-d H:i:s",mktime($calendarBusinessEndA[0],$calendarBusinessEndA[1]+$offsetPermitedMinutes,0,$month,$day,$year));
$calendarBusinessEndInt=mktime($calendarBusinessEndA[0],$calendarBusinessEndA[1]+$offsetPermitedMinutes,0,$month,$day,$year);
$calendarBusinessEndSeconds=($calendarBusinessEndA[0]*60*60)+($calendarBusinessEndA[1]*60);
$calendarObj->addCalendarLog("Possible time: $possibleTime");
$calendarObj->addCalendarLog("Current Start Date/Time: $normalizedDate");
$calendarObj->addCalendarLog("Calendar Business End: $calendarBusinessEndNormalized");
if($possibleTimeInt>$calendarBusinessEndInt){
$currentDateTimeB = explode(" ",$calendarBusinessEndNormalized);
$currentDate = $currentDateTimeB[0];
$currentTime = $currentDateTimeB[1];
$diff = abs($normalizedDateSeconds-$calendarBusinessEndSeconds);
$diffHours = $diff/3600;
$hoursToProcess = $hoursToProcess-$diffHours;
}
else{
$currentDateTimeA = explode(" ",$possibleTime);
$currentDate = $currentDateTimeA[0];
$currentTime = $currentDateTimeA[1];
$hoursToProcess = 0;
}
$calendarObj->addCalendarLog("** Hours to Process: $hoursToProcess");
}
$calendarObj->addCalendarLog("+++++++++++ Calculated Due Date $currentDate $currentTime");
$result['DUE_DATE'] = $currentDate." ".$currentTime;
$result['DUE_DATE_SECONDS'] = strtotime($currentDate." ".$currentTime);
$result['OLD_DUE_DATE'] = date("Y-m-d H:i:s",$oldDate);
$result['OLD_DUE_DATE_SECONDS']= $oldDate;
$result['DUE_DATE_LOG'] = $calendarObj->calendarLog;
return $result;
}
/**
* Calculate $sInitDate + $iDaysCount, skipping non laborable days.
* Input: Any valid strtotime function type input.
* Returns: Integer timestamp of the result.
* Warning: It will hangs if there is no possible days to count as
* "laborable".
* @param date $sInitDate
* @param double $iDuration
* @param string $sTimeUnit
* @param string $iTypeDay
* @param string $UsrUid
* @param string $ProUid
* @param string $TasUid
* @return integer timestamp of the result
* @deprecated renamed by Hugo Loza (see calculateDate new function)
*/
function calculateDate_noCalendar( $sInitDate, $iDuration, $sTimeUnit, $iTypeDay, $UsrUid = NULL, $ProUid = NULL, $TasUid =NULL ) {
//load in class variables the config of working days, holidays etc..
$this->prepareInformation( $UsrUid , $ProUid , $TasUid );
$iHours = 0; $iDays = 0;
//convert the $iDuration and $sTimeUnit in hours and days, take in mind 8 hours = 1 day. and then we will have similar for 5 days = 1 weekends
if ( strtolower ( $sTimeUnit ) == 'hours' ) {
$iAux = intval(abs($iDuration));
$iHours = $iAux % $this->hoursPerDay;
$iDays = intval( $iAux / $this->hoursPerDay );
}
if ( strtolower ( $sTimeUnit ) == 'days' ) {
$iAux = intval(abs($iDuration * $this->hoursPerDay));
$iHours = $iAux % 8;
$iDays = intval( $iAux / 8 );
}
$addSign = ( $iDuration >= 0 ) ? '+' : '-';
$iInitDate = strtotime( $sInitDate );
if ( $iTypeDay == 1 ) { // working days
// if there are days calculate the days,
$iEndDate = $this->addDays( $iInitDate , $iDays, $addSign );
// if there are hours calculate the hours, and probably add a day if the quantity of hours for last day > 8 hours
$iEndDate = $this->addHours( $iEndDate , $iHours, $addSign );
}
else { // $task->getTasTypeDay() == 2 // calendar days
$iEndDate = strtotime( $addSign . $iDays . ' days ' , $iInitDate );
$iEndDate = strtotime( $addSign . $iHours . ' hours ' , $iEndDate );
}
return $iEndDate;
}
/**
* Calculate duration of the $sInitDate - $sEndDate.
* @param date $sInitDate
* @param date $sEndDate
* @param string $UsrUid
* @param string $ProUid
* @param string $TasUid
* @return int
*
*/
function calculateDuration( $sInitDate, $sEndDate = '', $UsrUid = NULL, $ProUid = NULL, $TasUid = NULL) {
$this->prepareInformation($UsrUid, $ProUid, $TasUid);
if ((string)$sEndDate == '') {
$sEndDate = date('Y-m-d H:i:s');
}
if (strtotime($sInitDate) > strtotime($sEndDate)) {
$sAux = $sInitDate;
$sInitDate = $sEndDate;
$sEndDate = $sAux;
}
$aAux1 = explode(' ', $sInitDate);
$aAux2 = explode(' ', $sEndDate);
$aInitDate = explode('-', $aAux1[0]);
$aEndDate = explode('-', $aAux2[0]);
$i = 1;
$iWorkedDays = 0;
$bFinished = false;
$fHours1 = 0.0;
$fHours2 = 0.0;
if (count($aInitDate) != 3) {
$aInitDate = array(0, 0, 0);
}
if (count($aEndDate) != 3) {
$aEndDate = array(0, 0, 0);
}
if ($aInitDate !== $aEndDate) {
while (!$bFinished && ($i < 10000)) {
$sAux = date('Y-m-d', mktime(0, 0, 0, $aInitDate[1], $aInitDate[2] + $i, $aInitDate[0]));
if ($sAux != implode('-', $aEndDate)) {
if (!in_array($sAux, $this->holidays)) {
if (!in_array(date('w', mktime(0, 0, 0, $aInitDate[1], $aInitDate[2] + $i, $aInitDate[0])), $this->weekends)) {
$iWorkedDays++;
}
}
$i++;
}
else {
$bFinished = true;
}
}
if (isset($aAux1[1])) {
$aAux1[1] = explode(':', $aAux1[1]);
$fHours1 = 24 - ($aAux1[1][0] + ($aAux1[1][1] / 60) + ($aAux1[1][2] / 3600));
}
if (isset($aAux2[1])) {
$aAux2[1] = explode(':', $aAux2[1]);
$fHours2 = $aAux2[1][0] + ($aAux2[1][1] / 60) + ($aAux2[1][2] / 3600);
}
$fDuration = ($iWorkedDays * 24) + $fHours1 + $fHours2;
}
else {
$fDuration = (strtotime($sEndDate) - strtotime($sInitDate)) / 3600;
}
return $fDuration;
}
/**
* Configuration functions
* @param string $UsrUid
* @param string $ProUid
* @param string $TasUid
* @return void
*/
function prepareInformation( $UsrUid = NULL , $ProUid = NULL , $TasUid =NULL )
{
// setup calendarDays according the task
if (isset($TasUid))
{
$task = TaskPeer::retrieveByPK( $TasUid );
if (!is_null($task)) {
$this->calendarDays = ($task->getTasTypeDay()==2);
}
}
//get an array with all holidays.
$aoHolidays=HolidayPeer::doSelect(new Criteria());
$holidays=array();
foreach($aoHolidays as $holiday)
$holidays[] = strtotime($holiday->getHldDate());
// by default the weekdays are from monday to friday
$this->weekends = array(0,6);
$this->holidays = $holidays;
return ;
}
/**
* Set to repeat for every year all dates defined in $this->holiday
* @param $bSkipEveryYear
* @return void
*/
function setSkipEveryYear( $bSkipEveryYear )
{
$this->skipEveryYear = $bSkipEveryYear===true;
}
/**
* Add a single date to holidays
* @param data $sDate
* @return void
*/
function addHoliday( $sDate )
{
if ($date=strtotime( $sDate )) $this->holidays[]=self::truncateTime($date);
else throw new Exception("Invalid date: $sDate.");
}
/**
* Set all the holidays
* @param date/array $aDate must be an array of (strtotime type) dates
* @return void
*/
function setHolidays( $aDates )
{
foreach($aDates as $sDate) $this->holidays = $aDates;
}
/**
* Set all the weekends
* @param array/integers $aWeekends must be an array of integers [1,7]
* 1=Sunday
* 7=Saturday
* @return void
*/
function setWeekends( $aWeekends )
{
$this->weekends = $aWeekends;
}
/**
* Add one day of week to the weekends list
* @param $iDayNumber must be an array of integers [1,7]
* 1=Sunday
* 7=Saturday
* @return void
*/
function skipDayOfWeek( $iDayNumber )
{
if ($iDayNumber<1 || $iDayNumber>7) throw new Exception("The day of week must be a number from 1 to 7.");
$this->weekends[]=$iDayNumber;
}
/**
* Add a range of non working dates
* @param date $sDateA must be a (strtotime type) dates
* @param date $sDateB must be a (strtotime type) dates
* @return void
*/
function addNonWorkingRange( $sDateA , $sDateB )
{
if ($date=strtotime( $sDateA )) $iDateA=self::truncateTime($date);
else throw new Exception("Invalid date: $sDateA.");
if ($date=strtotime( $sDateB )) $iDateB=self::truncateTime($date);
else throw new Exception("Invalid date: $sDateB.");
if ($iDateA>$iDateB) { $s=$iDateA;$iDateA=$iDateB;$iDateB=$s; };
$this->range[]=array( $iDateA , $iDateB );
}
/**
* PRIVATE UTILITARY FUNCTIONS
* Add days to the date
* @param date $iInitDate
* @param int $iDaysCount
* @param string $addSign
* @return date $iEndDate
*/
private function addDays( $iInitDate , $iDaysCount, $addSign = '+' )
{
$iEndDate = $iInitDate;
$aList = $this->holidays;
for( $r=1; $r <= $iDaysCount ; $r++) {
$iEndDate = strtotime( $addSign . "1 day", $iEndDate );
$dayOfWeek = idate('w',$iEndDate); //now sunday=0
if ( array_search( $dayOfWeek, $this->weekends )!== false ) $r--; //continue loop, but we are adding one more day.
}
return $iEndDate;
}
/**
* Add hours to the date
* @param date $iInitDate
* @param int $iHoursCount
* @param string $addSign
* @return $iEndDate
*/
private function addHours( $sInitDate , $iHoursCount, $addSign = '+' )
{
$iEndDate = strtotime( $addSign . $iHoursCount ." hours", $sInitDate );
return $iEndDate;
}
/**
* Compare if the date is in range
* @param $iDate = valid timestamp
* @return:true if it is within any of the ranges defined.
*/
private function inRange( $iDate )
{
$aRange = $this->range;
$iYear = idate( 'Y', $iDate );
foreach($aRange as $key => $rang)
{
if ($this->skipEveryYear)
{
$deltaYears = idate( 'Y', $rang[1] ) - idate( 'Y', $rang[0] );
$rang[0]=self::changeYear( $rang[0] , $iYear );
$rang[1]=self::changeYear( $rang[1] , $iYear + $deltaYears );
}
if (($iDate>=$rang[0]) && ($iDate<=$rang[1])) return true;
}
return false;
}
/**
* Truncate a date
* @param $iDate = valid timestamp
* @return date
*/
private function truncateTime( $iDate )
{
return mktime(0,0,0,idate('m',$iDate),idate('d',$iDate),idate('Y',$iDate));
}
/**
* Get time
* @param timestamp $iDate
* @return date
*/
private function getTime( $iDate )
{
return array(idate('H',$iDate),idate('m',$iDate),idate('s',$iDate));
}
/**
* Set time
* @param timestamp $iDate
* @param timestamp $aTime
* @return date
*/
private function setTime( $iDate , $aTime )
{
return mktime($aTime[0],$aTime[1],$aTime[2],idate('m',$iDate),idate('d',$iDate),idate('Y',$iDate));
}
/**
* Returns an array with all the dates of $this->skip['List'] with its
* year changed to $iYear.
* Warning: Don't know what to do if change a 29-02-2004 to 29-02-2005
* the last one does not exists.
* @param List $iYear
* @return array
*/
private function listForYear( $iYear )
{
$aList = $this->holidays;
foreach($aList as $k => $v)
{
$aList[$k] = self::changeYear( $v , $iYear );
}
return $aList;
}
/**
* Returns an array with all the dates of $this->skip['List'] with its
* year changed to $iYear.
* Warning: Don't know what to do if change a 29-02-2004 to 29-02-2005
* the last one does not exists.
* @param array $iYear
* @param date $iDate
* @return array
*/
private function changeYear( $iDate , $iYear )
{
if ($delta = ( $iYear - idate('Y',$iDate) ) )
{
$iDate = strtotime( "$delta year" , $iDate );
}
return $iDate;
}
}
?>

View File

@@ -0,0 +1,399 @@
<?php
/**
* @Author: Erik Amaru Ortiz <erik@colosa.com>
* @Description:This is a class for load all additional connections; if exist in a particular proccess
* @Date: 15-05-2008
*
*
* class.dbConnections.php
*
* Email bugs/suggestions to erik@colosa.com
*
*
*/
require_once 'model/DbSource.php';
require_once 'model/Content.php';
/**
* dbConnections
*
*
* @copyright 2008 Colosa
*
*/
class dbConnections
{
private $PRO_UID;
public $connections;
private $types;
/*errors handle*/
private $errno;
private $errstr;
private $encodesList;
/**
* construct of dbConnections
*
* @param string $pPRO_UID
* @return void
*/
public function __construct($pPRO_UID = null)
{
$this->errno = 0;
$this->errstr = "";
$this->PRO_UID = $pPRO_UID;
$this->getAllConnections();
}
/**
* getAllConnections
*
* @return Array $connections
*/
public function getAllConnections()
{
if( isset($this->PRO_UID) ){
$oDBSource = new DbSource();
$oContent = new Content();
$connections = Array();
$types = Array();
$this->have_any_connectios = false;
$c = new Criteria();
$c->clearSelectColumns();
$c->addSelectColumn(DbSourcePeer::DBS_UID);
$c->addSelectColumn(DbSourcePeer::PRO_UID);
$c->addSelectColumn(DbSourcePeer::DBS_TYPE);
$c->addSelectColumn(DbSourcePeer::DBS_SERVER);
$c->addSelectColumn(DbSourcePeer::DBS_DATABASE_NAME);
$c->addSelectColumn(DbSourcePeer::DBS_USERNAME);
$c->addSelectColumn(DbSourcePeer::DBS_PASSWORD);
$c->addSelectColumn(DbSourcePeer::DBS_PORT);
$c->addSelectColumn(DbSourcePeer::DBS_ENCODE);
$c->addSelectColumn(ContentPeer::CON_VALUE);
$c->add(DbSourcePeer::PRO_UID, $this->PRO_UID);
$c->add(ContentPeer::CON_CATEGORY, 'DBS_DESCRIPTION');
$c->addJoin(DbSourcePeer::DBS_UID, ContentPeer::CON_ID);
$result = DbSourcePeer::doSelectRS($c);
$result->next();
$row = $result->getRow();
while ($row = $result->getRow()) {
$connections[] = Array(
'DBS_UID' => $row[0],
'DBS_TYPE' => $row[2],
'DBS_SERVER' => $row[3],
'DBS_DATABASE_NAME' => $row[4],
'DBS_USERNAME' => $row[5],
'DBS_PASSWORD' => $row[6],
'DBS_PORT' => $row[7],
'DBS_ENCODE' => $row[8],
'CON_VALUE' => $row[9],
);
$result->next();
}
if(!in_array($row[2], $types)) {
$types[] = $row[2];
}
$this->connections = $connections;
return $connections;
}
}
/**
* getConnections
*
* @param string $pType
* @return Array $connections
*/
public function getConnections($pType){
$connections = Array();
foreach($this->connections as $c){
if(trim($pType) == trim($c['DBS_TYPE'])){
$connections[] = $c;
}
}
if(count($connections) > 0){
return $connections;
} else {
return false;
}
}
/**
* getConnectionsProUid
*
* @param string $pType
* @return Array $connections
*/
public function getConnectionsProUid($pProUid)
{
$connections = Array();
$c = new Criteria();
$c->clearSelectColumns();
$c->addSelectColumn(DbSourcePeer::DBS_UID);
$c->addSelectColumn(DbSourcePeer::PRO_UID);
$c->addSelectColumn(DbSourcePeer::DBS_TYPE);
$c->addSelectColumn(DbSourcePeer::DBS_SERVER);
$c->addSelectColumn(DbSourcePeer::DBS_DATABASE_NAME);
$result = DbSourcePeer::doSelectRS($c);
$result->next();
$row = $result->getRow();
while ($row = $result->getRow()) {
if(trim($pProUid) == trim($row[1])){
$connections[] = Array(
'DBS_UID' => $row[0],
'DBS_NAME' => '[' . $row[3] . '] ' . $row[2] . ': ' . $row[4]
);
}
$result->next();
}
if(count($connections) > 0){
return $connections;
} else {
return Array();
}
}
/**
* loadAdditionalConnections
*
* @return void
*/
public function loadAdditionalConnections()
{
PROPEL::Init ( PATH_METHODS.'dbConnections/genericDbConnections.php');
}
/**
* getDbServicesAvailables
*
* @return array $servicesAvailables
*/
public function getDbServicesAvailables()
{
$servicesAvailables = Array();
$dbServices = Array(
'mysql' => Array(
'id' => 'mysql',
'command' => 'mysql_connect',
'name' => 'MySql'
),
'pgsql' => Array(
'id' => 'pgsql',
'command' => 'pg_connect',
'name' => 'PostgreSql'
),
'mssql' => Array(
'id' => 'mssql',
'command' => 'mssql_connect',
'name' => 'Microsoft SQL Server'),
'oracle'=> Array(
'id' => 'oracle',
'command' => 'oci_connect',
'name' => 'Oracle'
)
);
/*,
'informix'=> Array(
'id' => 'informix',
'command' => 'ifx_connect',
'name' => 'Informix'
),
'sqlite' => Array(
'id' => 'sqlite',
'command' => 'sqlite_open',
'name' => 'SQLite'
)
*/
foreach($dbServices as $service) {
if(@function_exists($service['command'])){
$servicesAvailables[] = $service;
}
}
return $servicesAvailables;
}
/**
* showMsg
*
* @return void
*/
public function showMsg()
{
if ($this->errno != 0) {
$msg = "
<center>
<fieldset style='width:90%'><legend>Class NET</legend>
<div align=left>
<font color='red'>
<b>NET::ERROR NO -> $this->errno<br/>
NET::ERROR MSG -> $this->errstr</b>
</font>
</div>
</fieldset>
<center>";
print ($msg);
}
}
/**
* getEncondeList
*
* @param string $engine
* @return $this->ordx($this->encodesList);
*/
public function getEncondeList($engine = ''){
switch( $engine ){
default:
case 'mysql':
$encodes = Array(
Array('big5', 'big5 - Big5 Traditional Chinese'),
Array('dec8', 'dec8 - DEC West European'),
Array('cp850', 'cp850 - DOS West European'),
Array('hp8', 'hp8 - HP West European'),
Array('koi8r', 'koi8r - KOI8-R Relcom Russian'),
Array('latin1', 'latin1 - cp1252 West European'),
Array('latin2', 'latin2 - ISO 8859-2 Central European'),
Array('swe7', 'swe7 - 7bit Swedish'),
Array('ascii', 'ascii - US ASCII'),
Array('ujis', 'ujis - EUC-JP Japanese'),
Array('sjis', 'sjis - Shift-JIS Japanese'),
Array('hebrew', 'hebrew - ISO 8859-8 Hebrew'),
Array('tis620', 'tis620 - TIS620 Thai'),
Array('euckr', 'euckr - EUC-KR Korean'),
Array('koi8u', 'koi8u - KOI8-U Ukrainian'),
Array('gb2312', 'gb2312 - GB2312 Simplified Chinese'),
Array('greek', 'greek - ISO 8859-7 Greek'),
Array('cp1250', 'cp1250 - Windows Central European'),
Array('gbk', 'gbk - GBK Simplified Chinese'),
Array('latin5', 'latin5 - ISO 8859-9 Turkish'),
Array('armscii8', 'armscii8 - ARMSCII-8 Armenian'),
Array('utf8', 'utf8 - UTF-8 Unicode'),
Array('ucs2', 'ucs2 - UCS-2 Unicode'),
Array('cp866', 'cp866 - DOS Russian'),
Array('keybcs2', 'keybcs2 - DOS Kamenicky Czech-Slovak'),
Array('macce', 'macce - Mac Central European'),
Array('macroman', 'macroman - Mac West European'),
Array('cp852', 'cp852 - DOS Central European'),
Array('latin7', 'atin7 - ISO 8859-13 Baltic'),
Array('cp1251', 'cp1251 - Windows Cyrillic'),
Array('cp1256', 'cp1256 - Windows Arabic'),
Array('cp1257', 'cp1257 - Windows Baltic'),
Array('binary', 'binary - Binary pseudo charset'),
Array('geostd8', 'geostd8 - GEOSTD8 Georgian'),
Array('cp932', 'cp932] - SJIS for Windows Japanese'),
Array('eucjpms', 'eucjpms - UJIS for Windows Japanese')
);
break;
case 'pgsql':
$encodes = Array(
Array("BIG5", "BIG5"),
Array("EUC_CN", "EUC_CN"),
Array("EUC_JP", "EUC_JP"),
Array("EUC_KR", "EUC_KR"),
Array("EUC_TW", "EUC_TW"),
Array("GB18030", "GB18030"),
Array("GBK", "GBK"),
Array("ISO_8859_5", "ISO_8859_5"),
Array("ISO_8859_6", "ISO_8859_6"),
Array("ISO_8859_7", "ISO_8859_7"),
Array("ISO_8859_8", "ISO_8859_8"),
Array("JOHAB", "JOHAB"),
Array("KOI8", "KOI8"),
Array("selected", "LATIN1"),
Array("LATIN2", "LATIN2"),
Array("LATIN3", "LATIN3"),
Array("LATIN4", "LATIN4"),
Array("LATIN5", "LATIN5"),
Array("LATIN6", "LATIN6"),
Array("LATIN7", "LATIN7"),
Array("LATIN8", "LATIN8"),
Array("LATIN9", "LATIN9"),
Array("LATIN10", "LATIN10"),
Array("SJIS", "SJIS"),
Array("SQL_ASCII", "SQL_ASCII"),
Array("UHC", "UHC"),
Array("UTF8", "UTF8"),
Array("WIN866", "WIN866"),
Array("WIN874", "WIN874"),
Array("WIN1250", "WIN1250"),
Array("WIN1251", "WIN1251"),
Array("WIN1252", "WIN1252"),
Array("WIN1256", "WIN1256"),
Array("WIN1258", "WIN1258")
);
break;
case 'mssql':
$encodes = Array(Array('utf8', 'utf8 - UTF-8 Unicode'));
break;
case 'oracle':
$encodes = Array();
break;
}
$this->encodesList = $encodes;
return $this->ordx($this->encodesList);
}
/**
* getErrno
*
* @return integer $errno
*/
public function getErrno()
{
return $this->errno;
}
/**
* getErrmsg
*
* @return string errstr
*/
public function getErrmsg()
{
return $this->errstr;
}
/**
* getErrmsg
*
* @param array $m
* @return array $aRet
*/
public function ordx($m)
{
$aTmp = Array();
$aRet = Array();
for($i=0; $i<count($m); $i++){
array_push($aTmp, $m[$i][0].'|'.$m[$i][1]);
}
usort($aTmp,"strnatcasecmp");
for($i=0; $i<count($aTmp); $i++){
$x = explode('|', $aTmp[$i]);
array_push($aRet, Array($x[0], $x[1]));
}
return $aRet;
}
}

View File

@@ -0,0 +1,970 @@
<?php
/**
* class.derivation.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.
*
*/
require_once ( "classes/model/Task.php" );
require_once ( "classes/model/Process.php" );
require_once ( "classes/model/Step.php" );
require_once ( "classes/model/Application.php" );
require_once ( 'classes/model/Groupwf.php' );
require_once ( "classes/model/GroupUser.php" );
require_once ( "classes/model/AppDelegation.php" );
require_once ( "classes/model/Route.php" );
require_once ( 'classes/model/SubApplication.php');
require_once ( 'classes/model/SubProcess.php' );
require_once ( "classes/model/Users.php" );
G::LoadClass( "plugin" );
/**
* derivation - derivation class
* @package ProcessMaker
*
*/
class Derivation
{
var $case;
/**
* prepareInformation
*
* @param array $aData
* @return $taskInfo
*/
function prepareInformation($aData)
{
$oTask = new Task();
//SELECT *
//FROM APP_DELEGATION AS A
//LEFT JOIN TASK AS T ON(T.TAS_UID = A.TAS_UID)
//LEFT JOIN ROUTE AS R ON(R.TAS_UID = A.TAS_UID)
//WHERE
//APP_UID = '$aData['APP_UID']'
//AND DEL_INDEX = '$aData['DEL_INDEX']'
$c = new Criteria ( 'workflow' );
$c->clearSelectColumns();
$c->addSelectColumn ( AppDelegationPeer::TAS_UID );
$c->addSelectColumn ( RoutePeer::ROU_CONDITION );
$c->addSelectColumn ( RoutePeer::ROU_NEXT_TASK );
$c->addSelectColumn ( RoutePeer::ROU_TYPE );
$c->addJoin ( AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN );
$c->addJoin ( AppDelegationPeer::TAS_UID, RoutePeer::TAS_UID, Criteria::LEFT_JOIN );
$c->add ( AppDelegationPeer::APP_UID, $aData['APP_UID'] );
$c->add ( AppDelegationPeer::DEL_INDEX, $aData['DEL_INDEX'] );
$c->addAscendingOrderByColumn ( RoutePeer::ROU_CASE );
$rs = AppDelegationPeer::doSelectRs ( $c );
$rs->setFetchmode (ResultSet::FETCHMODE_ASSOC);
$rs->next();
$aDerivation = $rs->getRow();
$i = 0;
$taskInfo = array();
$oUser = new Users();
$this->case = new Cases();
// 1. there is no rule
if ( is_null ( $aDerivation['ROU_NEXT_TASK'] ) ) {
throw ( new Exception ( G::LoadTranslation ( 'ID_NO_DERIVATION_RULE') ) );
}
while( is_array( $aDerivation) ) {
$oTask = new Task();
$aDerivation = G::array_merges( $aDerivation, $aData );
$bContinue = true;
//evaluate the condition if there are conditions defined.
if( isset( $aDerivation['ROU_CONDITION'] ) && $aDerivation['ROU_CONDITION'] != ''
&& ( $aDerivation['ROU_TYPE'] != 'SELECT' || $aDerivation['ROU_TYPE'] == 'PARALLEL-BY-EVALUATION') ) {
$AppFields = $this->case->loadCase( $aData['APP_UID'] );
G::LoadClass('pmScript');
$oPMScript = new PMScript();
$oPMScript->setFields( $AppFields['APP_DATA'] );
$oPMScript->setScript( $aDerivation['ROU_CONDITION'] );
$bContinue = $oPMScript->evaluate();
}
if ( $aDerivation['ROU_TYPE'] == 'EVALUATE' ) {
if ( count ( $taskInfo) >= 1) {
$bContinue = false;
}
}
if ($bContinue) {
$i++;
$TaskFields = $oTask->load( $aDerivation['TAS_UID'] );
$aDerivation = G::array_merges( $aDerivation, $TaskFields );
//2. if next case is an special case
if ( (int)$aDerivation['ROU_NEXT_TASK'] < 0) {
$aDerivation['NEXT_TASK']['TAS_UID'] = (int)$aDerivation['ROU_NEXT_TASK'];
$aDerivation['NEXT_TASK']['TAS_ASSIGN_TYPE'] = '';
$aDerivation['NEXT_TASK']['TAS_PRIORITY_VARIABLE'] = '';
$aDerivation['NEXT_TASK']['TAS_DEF_PROC_CODE'] = '';
$aDerivation['NEXT_TASK']['TAS_PARENT'] = '';
switch ($aDerivation['ROU_NEXT_TASK']) {
case -1: $aDerivation['NEXT_TASK']['TAS_TITLE'] = G::LoadTranslation('ID_END_OF_PROCESS');
break;
case -2: $aDerivation['NEXT_TASK']['TAS_TITLE'] = G::LoadTranslation('ID_TAREA_COLGANTE');
break;
}
$aDerivation['NEXT_TASK']['USR_UID'] = 'asdf';
}
else {
//3. load the task information of normal NEXT_TASK
$aDerivation['NEXT_TASK'] = $oTask->load( $aDerivation['ROU_NEXT_TASK'] );//print $aDerivation['ROU_NEXT_TASK']." **** ".$aDerivation['NEXT_TASK']['TAS_TYPE']."<hr>";
if ($aDerivation['NEXT_TASK']['TAS_TYPE'] === 'SUBPROCESS') {
$oCriteria = new Criteria('workflow');
$oCriteria->add(SubProcessPeer::PRO_PARENT, $aDerivation['PRO_UID']);
$oCriteria->add(SubProcessPeer::TAS_PARENT, $aDerivation['NEXT_TASK']['TAS_UID']);
$oDataset = SubProcessPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
$sTaskParent = $aDerivation['NEXT_TASK']['TAS_UID'];
$aDerivation['ROU_NEXT_TASK'] = $aRow['TAS_UID'];//print "<hr>Life is just a lonely highway";
$aDerivation['NEXT_TASK'] = $oTask->load( $aDerivation['ROU_NEXT_TASK'] );//print "<hr>Life is just a lonely highway";print"<hr>";
$oProcess = new Process();
$aRow = $oProcess->load($aRow['PRO_UID']);
$aDerivation['NEXT_TASK']['TAS_TITLE'] .= ' (' . $aRow['PRO_TITLE'] . ')';
$aDerivation['NEXT_TASK']['TAS_PARENT'] = $sTaskParent;
unset($oTask, $oProcess, $aRow, $sTaskParent);
}
else {
$aDerivation['NEXT_TASK']['TAS_PARENT'] = '';
}
$aDerivation['NEXT_TASK']['USER_ASSIGNED'] = $this->getNextAssignedUser($aDerivation);
}
$taskInfo[$i] = $aDerivation;
}
$rs->next();
$aDerivation = $rs->getRow();
}
return $taskInfo;
}
/**
* getRouteCondition
*
* @param array $aData
* @return $routeCondition
*/
function getRouteCondition($aData)
{
//SELECT *
//FROM APP_DELEGATION AS A
//LEFT JOIN TASK AS T ON(T.TAS_UID = A.TAS_UID)
//LEFT JOIN ROUTE AS R ON(R.TAS_UID = A.TAS_UID)
//WHERE
//APP_UID = '$aData['APP_UID']'
//AND DEL_INDEX = '$aData['DEL_INDEX']'
$c = new Criteria ( 'workflow' );
$c->clearSelectColumns();
$c->addSelectColumn ( AppDelegationPeer::TAS_UID );
$c->addSelectColumn ( RoutePeer::ROU_CONDITION );
$c->addSelectColumn ( RoutePeer::ROU_NEXT_TASK );
$c->addSelectColumn ( RoutePeer::ROU_TYPE );
$c->addSelectColumn ( RoutePeer::ROU_OPTIONAL);
$c->addJoin ( AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN );
$c->addJoin ( AppDelegationPeer::TAS_UID, RoutePeer::TAS_UID, Criteria::LEFT_JOIN );
$c->add ( AppDelegationPeer::APP_UID, $aData['APP_UID'] );
$c->add ( AppDelegationPeer::DEL_INDEX, $aData['DEL_INDEX'] );
$c->addAscendingOrderByColumn ( RoutePeer::ROU_CASE );
$rs = AppDelegationPeer::doSelectRs ( $c );
$rs->setFetchmode (ResultSet::FETCHMODE_ASSOC);
$rs->next();
$aDerivation = $rs->getRow();
while( is_array( $aDerivation) ) {
return $aDerivation;
}
}
function GetAppParentIndex($aData)
{
//('SELECT * FROM APP_THREAD WHERE APP_UID='".$aData['APP_UID']."' AND DEL_INDEX = '".$aData['DEL_INDEX']."'");
try {
$aThreads = array();
$c = new Criteria();
$c->addSelectColumn(AppThreadPeer::APP_THREAD_PARENT);
$c->add(AppThreadPeer::APP_UID, $aData['APP_UID']);
$c->add(AppThreadPeer::DEL_INDEX, $aData['DEL_INDEX']);
$rs = AppThreadPeer::doSelectRs($c);
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rs->next();
$row = $rs->getRow();
while (is_array($row)) {
$aThreads = $row;
$rs->next();
$row = $rs->getRow();
}
return $aThreads;
}
catch (exception $e) {
throw ($e);
}
}
/* get all users, from any task, if the task have Groups, the function expand the group
*
* @param string $sTasUid the task uidUser
* @return Array $users an array with userID order by USR_UID
*/
function getAllUsersFromAnyTask ( $sTasUid ) {
$users = array();
$c = new Criteria ( 'workflow' );
$c->clearSelectColumns();
$c->addSelectColumn( TaskUserPeer::USR_UID);
$c->addSelectColumn( TaskUserPeer::TU_RELATION);
$c->add ( TaskUserPeer::TAS_UID, $sTasUid);
$c->add ( TaskUserPeer::TU_TYPE, 1);
$rs = TaskUserPeer::DoSelectRs ($c);
$rs->setFetchmode (ResultSet::FETCHMODE_ASSOC);
$rs->next();
$row = $rs->getRow();
while ( is_array ( $row ) ) {
if ( $row['TU_RELATION'] == '2' ) {
$cGrp = new Criteria ('workflow');
$cGrp->add(GroupwfPeer::GRP_STATUS, 'ACTIVE');
$cGrp->add(GroupUserPeer::GRP_UID, $row['USR_UID']);
$cGrp->addJoin(GroupUserPeer::GRP_UID, GroupwfPeer::GRP_UID, Criteria::LEFT_JOIN);
$cGrp->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN);
$cGrp->add(UsersPeer::USR_STATUS, 'ACTIVE');
$rsGrp = GroupUserPeer::DoSelectRs ($cGrp);
$rsGrp->setFetchmode (ResultSet::FETCHMODE_ASSOC);
$rsGrp->next();
$rowGrp = $rsGrp->getRow();
while ( is_array ( $rowGrp ) ) {
$users[$rowGrp['USR_UID']] = $rowGrp['USR_UID'];
$rsGrp->next();
$rowGrp = $rsGrp->getRow();
}
}
else {
//filter to users that is in vacation or has an inactive estatus, and others
$oUser = UsersPeer::retrieveByPK( $row['USR_UID'] );
if( $oUser->getUsrStatus() == 'ACTIVE' ){
$users[$row['USR_UID']] = $row['USR_UID'];
} else if($oUser->getUsrStatus() == 'VACATION'){
//this a litle hook for this issue,...
//TODO if the user in getUsrReplacedBy() is not assignet to the same task,. will have problems,....
$UsrReplace = $oUser->getUsrReplacedBy();
if( trim($UsrReplace) != ''){
//$users[$UsrReplace] = $UsrReplace;
}
}
}
$rs->next();
$row = $rs->getRow();
}
//to do: different types of sort
sort($users);
return $users;
}
/* get an array of users, and returns the same arrays with User's fullname and other fields
*
* @param Array $aUsers the task uidUser
* @return Array $aUsersData an array with with User's fullname
*/
function getUsersFullNameFromArray ( $aUsers ) {
$oUser = new Users();
$aUsersData = array();
if ( is_array ( $aUsers ) ) {
foreach ( $aUsers as $key => $val ) {
$userFields = $oUser->load($val);
$auxFields['USR_UID'] = $userFields['USR_UID'];
$auxFields['USR_USERNAME'] = $userFields['USR_USERNAME'];
$auxFields['USR_FIRSTNAME'] = $userFields['USR_FIRSTNAME'];
$auxFields['USR_LASTNAME'] = $userFields['USR_LASTNAME'];
$auxFields['USR_FULLNAME'] = $userFields['USR_LASTNAME'] . ($userFields['USR_LASTNAME'] != '' ? ', ' : '') . $userFields['USR_FIRSTNAME'];
$auxFields['USR_EMAIL'] = $userFields['USR_EMAIL'];
$auxFields['USR_STATUS'] = $userFields['USR_STATUS'];
$auxFields['USR_COUNTRY'] = $userFields['USR_COUNTRY'];
$auxFields['USR_CITY'] = $userFields['USR_CITY'];
$auxFields['USR_LOCATION'] = $userFields['USR_LOCATION'];
$auxFields['DEP_UID'] = $userFields['DEP_UID'];
$auxFields['USR_HIDDEN_FIELD'] = '';
$aUsersData[] = $auxFields;
}
}
else {
$oCriteria = new Criteria();
$oCriteria->add(UsersPeer::USR_UID, $aUsers);
if (UsersPeer::doCount($oCriteria) < 1) {
return null;
}
$userFields = $oUser->load( $aUsers );
$auxFields['USR_UID'] = $userFields['USR_UID'];
$auxFields['USR_USERNAME'] = $userFields['USR_USERNAME'];
$auxFields['USR_FIRSTNAME'] = $userFields['USR_FIRSTNAME'];
$auxFields['USR_LASTNAME'] = $userFields['USR_LASTNAME'];
$auxFields['USR_FULLNAME'] = $userFields['USR_LASTNAME'] . ($userFields['USR_LASTNAME'] != '' ? ', ' : '') . $userFields['USR_FIRSTNAME'];
$auxFields['USR_EMAIL'] = $userFields['USR_EMAIL'];
$auxFields['USR_STATUS'] = $userFields['USR_STATUS'];
$auxFields['USR_COUNTRY'] = $userFields['USR_COUNTRY'];
$auxFields['USR_CITY'] = $userFields['USR_CITY'];
$auxFields['USR_LOCATION'] = $userFields['USR_LOCATION'];
$auxFields['DEP_UID'] = $userFields['DEP_UID'];
$aUsersData = $auxFields;
}
return $aUsersData;
}
/* get next assigned user
*
* @param Array $tasInfo
* @return Array $userFields
*/
function getNextAssignedUser( $tasInfo ){
$oUser = new Users();
$nextAssignedTask = $tasInfo['NEXT_TASK'];
$lastAssigned = $tasInfo['NEXT_TASK']['TAS_LAST_ASSIGNED'];
$sTasUid = $tasInfo['NEXT_TASK']['TAS_UID'];
// to do: we can increase the LOCATION by COUNTRY, STATE and LOCATION
/* Verify if the next Task is set with the option "TAS_ASSIGN_LOCATION == TRUE" */
$assignLocation = '';
if ($tasInfo['NEXT_TASK']['TAS_ASSIGN_LOCATION'] == 'TRUE')
{
$oUser->load( $tasInfo['USER_UID'] );
krumo ($oUser->getUsrLocation() );
//to do: assign for location
//$assignLocation = " AND USR_LOCATION = " . $oUser->Fields['USR_LOCATION'];
}
/* End - Verify if the next Task is set with the option "TAS_ASSIGN_LOCATION == TRUE" */
$uidUser = '';
switch( $nextAssignedTask['TAS_ASSIGN_TYPE'] ) {
case 'BALANCED' :
$users = $this->getAllUsersFromAnyTask ($sTasUid);
if ( is_array( $users) && count( $users ) > 0 ) {
//to do apply any filter like LOCATION assignment
$uidUser = $users[ 0 ];
$i = count($users) -1;
while ( $i > 0 ) {
if ( $lastAssigned < $users[$i] )
$uidUser = $users[ $i ];
$i--;
}
}
else {
throw ( new Exception (G::LoadTranslation( 'ID_NO_USERS' ) ) );
}
$userFields = $this->getUsersFullNameFromArray ($uidUser);
break;
case 'STATIC_MI':
case 'CANCEL_MI':
case 'MANUAL' :
$users = $this->getAllUsersFromAnyTask ($sTasUid);
$userFields = $this->getUsersFullNameFromArray ($users);
break;
case 'EVALUATE' :
$AppFields = $this->case->loadCase( $tasInfo['APP_UID'] );
$variable = str_replace ( '@@', '', $nextAssignedTask['TAS_ASSIGN_VARIABLE'] );
if ( isset ( $AppFields['APP_DATA'][$variable] ) ) {
if ($AppFields['APP_DATA'][$variable] != '') {
$value = $AppFields['APP_DATA'][$variable];
$userFields = $this->getUsersFullNameFromArray ($value);
if (is_null($userFields)) {
throw ( new Exception("Task doesn't have a valid user in variable $variable.") ) ;
}
}
else {
throw ( new Exception("Task doesn't have a valid user in variable $variable.") ) ;
}
}
else
throw ( new Exception("Task doesn't have a valid user in variable $variable or this variable doesn't exist.") ) ;
break;
case 'REPORT_TO' :
//default error user when the reportsTo is not assigned to that user
//look for USR_REPORTS_TO to this user
$userFields['USR_UID'] = '';
$userFields['USR_FULLNAME'] = 'Current user does not have a valid Reports To user';
$userFields['USR_USERNAME'] = 'Current user does not have a valid Reports To user';
$userFields['USR_FIRSTNAME'] = '';
$userFields['USR_LASTNAME'] = '';
$userFields['USR_EMAIL'] = '';
//look for USR_REPORTS_TO to this user
$useruid = $this->getDenpendentUser($tasInfo['USER_UID']);
if ( isset ( $useruid ) ) {
if ($useruid != '') {
$value = $useruid;
$userFields = $this->getUsersFullNameFromArray ($value);
if (is_null($userFields)) {
//throw ( new Exception("The current user does not have a valid Reports To user. Please contact administrator.") ) ;
}
}
else {
//throw ( new Exception("The current user does not have a valid Reports To user. Please contact administrator.") ) ;
}
}
else
$userFields = "ERROR";
//throw ( new Exception("The current user does not have a valid Reports To user. Please contact administrator.") ) ;
break;
case 'SELF_SERVICE' :
//look for USR_REPORTS_TO to this user
$userFields['USR_UID'] = '';
$userFields['USR_FULLNAME'] = '<b>' . G::LoadTranslation('ID_UNASSIGNED') . '</b>';
$userFields['USR_USERNAME'] = '<b>' . G::LoadTranslation('ID_UNASSIGNED') . '</b>';
$userFields['USR_FIRSTNAME'] = '';
$userFields['USR_LASTNAME'] = '';
$userFields['USR_EMAIL'] = '';
break;
default :
throw ( new Exception('Invalid Task Assignment method for Next Task ') ) ;
}
return $userFields;
}
/* getDenpendentUser
*
* @param string $USR_UID
* @return string $aRow['USR_REPORTS_TO']
*/
function getDenpendentUser($USR_UID)
{
//require_once 'classes/model/Users.php';
//here the uid to next Users
$oC=new Criteria();
$oC->addSelectColumn(UsersPeer::USR_REPORTS_TO);
$oC->add(UsersPeer::USR_UID,$USR_UID);
$oDataset=UsersPeer::doSelectRS($oC);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
return $aRow['USR_REPORTS_TO'];
}
/* setTasLastAssigned
*
* @param string $tasUid
* @param string $usrUid
* @throws Exception $e
* @return void
*/
function setTasLastAssigned ( $tasUid, $usrUid )
{
try {
$oTask = TaskPeer::retrieveByPk( $tasUid );
$oTask->setTasLastAssigned( $usrUid );
$oTask->save();
}
catch ( Exception $e ) {
throw ( $e );
}
}
/* derivate
*
* @param array $currentDelegation
* @param array $nextDelegations
* @return void
*/
function derivate($currentDelegation=array(), $nextDelegations =array())
{
if ( !defined('TASK_FINISH_PROCESS')) define('TASK_FINISH_PROCESS',-1);
if ( !defined('TASK_FINISH_TASK')) define('TASK_FINISH_TASK', -2);
$this->case = new cases();
//first, we close the current derivation, then we'll try to derivate to each defined route
$appFields = $this->case->loadCase($currentDelegation['APP_UID'], $currentDelegation['DEL_INDEX'] );
$this->case->CloseCurrentDelegation ( $currentDelegation['APP_UID'], $currentDelegation['DEL_INDEX'] );
//Count how many tasks should be derivated.
//$countNextTask = count($nextDelegations);
foreach($nextDelegations as $nextDel) {
//subprocesses??
if ($nextDel['TAS_PARENT'] != '') {
$oCriteria = new Criteria('workflow');
$oCriteria->add(SubProcessPeer::PRO_PARENT, $appFields['PRO_UID']);
$oCriteria->add(SubProcessPeer::TAS_PARENT, $nextDel['TAS_PARENT']);
if (SubProcessPeer::doCount($oCriteria) > 0) {
$oDataset = SubProcessPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aSP = $oDataset->getRow();
$aSP['USR_UID'] = $nextDel['USR_UID'];
$oTask = new Task();
$aTask = $oTask->load($nextDel['TAS_PARENT']);
$nextDel = array('TAS_UID' => $aTask['TAS_UID'],
'USR_UID' => $aSP['USR_UID'],
'TAS_ASSIGN_TYPE' => $aTask['TAS_ASSIGN_TYPE'],
'TAS_DEF_PROC_CODE' => $aTask['TAS_DEF_PROC_CODE'],
'DEL_PRIORITY' => 3,
'TAS_PARENT' => '');
}
else {
continue;
}
}
//get TAS_ASSIGN_TYPE for current Delegation
$oTask = TaskPeer::retrieveByPk( $currentDelegation['TAS_UID'] );
$aTask = $oTask->toArray(BasePeer::TYPE_FIELDNAME);
$currentDelegation['TAS_ASSIGN_TYPE'] = $aTask['TAS_ASSIGN_TYPE'];
$currentDelegation['TAS_MI_COMPLETE_VARIABLE'] = isset($aTask['TAS_MI_COMPLETE_VARIABLE']) ? $aTask['TAS_MI_COMPLETE_VARIABLE'] : '';
$currentDelegation['TAS_MI_INSTANCE_VARIABLE'] = isset($aTask['TAS_MI_INSTANCE_VARIABLE']) ? $aTask['TAS_MI_INSTANCE_VARIABLE'] : '';
//get open threads
$openThreads = $this->case->GetOpenThreads( $currentDelegation['APP_UID'] );
//if we are derivating to finish process but there are no more open thread then we are finishing only the task, we are not finishing the whole process
if (($nextDel['TAS_UID'] == TASK_FINISH_PROCESS) && (($openThreads + 1) > 1)) {
$nextDel['TAS_UID'] = TASK_FINISH_TASK;
}
switch ( $nextDel['TAS_UID'] ) {
case TASK_FINISH_PROCESS:
/*Close all delegations of $currentDelegation['APP_UID'] */
$this->case->closeAllDelegations ( $currentDelegation['APP_UID'] );
$this->case->closeAllThreads ( $currentDelegation['APP_UID']);
//I think we need to change the APP_STATUS to completed,
break;
case TASK_FINISH_TASK:
$iAppThreadIndex = $appFields['DEL_THREAD'];
$this->case->closeAppThread ( $currentDelegation['APP_UID'], $iAppThreadIndex);
break;
default:
// get all siblingThreads
//if($currentDelegation['TAS_ASSIGN_TYPE'] == 'STATIC_MI')
switch ($currentDelegation['TAS_ASSIGN_TYPE']) {
case 'CANCEL_MI':
case 'STATIC_MI':
$siblingThreads = $this->case->GetAllOpenDelegation($currentDelegation);
$aData = $this->case->loadCase($currentDelegation['APP_UID']);
if (isset($aData['APP_DATA'][str_replace('@@', '', $currentDelegation['TAS_MI_INSTANCE_VARIABLE'])]))
$sMIinstanceVar = $aData['APP_DATA'][str_replace('@@', '', $currentDelegation['TAS_MI_INSTANCE_VARIABLE'])];
else
$sMIinstanceVar = $aData['APP_DATA']['TAS_MI_INSTANCE_VARIABLE'];
if (isset($aData['APP_DATA'][str_replace('@@', '', $currentDelegation['TAS_MI_COMPLETE_VARIABLE'])]))
$sMIcompleteVar = $aData['APP_DATA'][str_replace('@@', '', $currentDelegation['TAS_MI_COMPLETE_VARIABLE'])];
else
$sMIcompleteVar = $aData['APP_DATA']['TAS_MI_COMPLETE_VARIABLE'];
$discriminateThread = $sMIinstanceVar - $sMIcompleteVar;
// -1 because One App Delegation is closed by above Code
if($discriminateThread == count($siblingThreads))
$canDerivate =true;
else
$canDerivate =false;
break;
default:
if ( $currentDelegation['ROU_TYPE'] == 'SEC-JOIN') {
$siblingThreads = $this->case->getOpenSiblingThreads($nextDel['TAS_UID'], $currentDelegation['APP_UID'], $currentDelegation['DEL_INDEX'], $currentDelegation['TAS_UID'],$currentDelegation['ROU_TYPE']);
$canDerivate = count($siblingThreads) == 0;
}
else if($currentDelegation['ROU_TYPE'] == 'DISCRIMINATOR')
{
//First get the total threads of Next Task where route type='Discriminator'
$siblingThreads = $this->case->getOpenSiblingThreads($nextDel['TAS_UID'], $currentDelegation['APP_UID'], $currentDelegation['DEL_INDEX'], $currentDelegation['TAS_UID'],$currentDelegation['ROU_TYPE']);
$siblingThreadsCount = count($siblingThreads);
$discriminateThread = $currentDelegation['ROU_CONDITION'];
//$checkThread = count($totalThreads) - $cond;
if($discriminateThread == $siblingThreadsCount)
$canDerivate = true;
else
$canDerivate = false;
}
else {
$canDerivate = true;
}
}
if ( $canDerivate ) {
$iAppThreadIndex = $appFields['DEL_THREAD'];
$delType = 'NORMAL';
switch ( $nextDel['TAS_ASSIGN_TYPE'] ) {
case 'CANCEL_MI':
case 'STATIC_MI':
// Create new delegation depending on the no of users in the group
$iNewAppThreadIndex = $appFields['DEL_THREAD'];
$this->case->closeAppThread ( $currentDelegation['APP_UID'], $iAppThreadIndex);
foreach($nextDel['NEXT_TASK']['USER_ASSIGNED'] as $key=>$aValue){
//Incrementing the Del_thread First so that new delegation has new del_thread
$iNewAppThreadIndex += 1;
//Creating new delegation according to users in group
$iMIDelIndex = $this->case->newAppDelegation( $appFields['PRO_UID'],$currentDelegation['APP_UID'],$nextDel['TAS_UID'],
(isset($aValue['USR_UID']) ? $aValue['USR_UID'] : ''),
$currentDelegation['DEL_INDEX'],
$nextDel['DEL_PRIORITY'],
$delType,
$iNewAppThreadIndex);
$iNewThreadIndex = $this->case->newAppThread ( $currentDelegation['APP_UID'], $iMIDelIndex, $iAppThreadIndex );
//Setting the del Index for Updating the AppThread delIndex
if($key == 0)
$iNewDelIndex = $iMIDelIndex -1;
}
break;
case 'BALANCED' :
$this->setTasLastAssigned ($nextDel['TAS_UID'], $nextDel['USR_UID']);
//No Break, need no execute the default ones....
default:
// Create new delegation
$iNewDelIndex = $this->case->newAppDelegation(
$appFields['PRO_UID'], $currentDelegation['APP_UID'], $nextDel['TAS_UID'],
(isset($nextDel['USR_UID']) ? $nextDel['USR_UID'] : ''),
$currentDelegation['DEL_INDEX'],
$nextDel['DEL_PRIORITY'],
$delType,
$iAppThreadIndex);
break;
}
$iAppThreadIndex = $appFields['DEL_THREAD'];
switch ( $currentDelegation['ROU_TYPE'] ) {
case 'PARALLEL' :
case 'PARALLEL-BY-EVALUATION' :
$this->case->closeAppThread ( $currentDelegation['APP_UID'], $iAppThreadIndex);
$iNewThreadIndex = $this->case->newAppThread ( $currentDelegation['APP_UID'], $iNewDelIndex, $iAppThreadIndex );
$this->case->updateAppDelegation ( $currentDelegation['APP_UID'], $iNewDelIndex, $iNewThreadIndex );
break;
case 'DISCRIMINATOR':
if($currentDelegation['ROU_OPTIONAL'] == 'TRUE')
{
$this->case->discriminateCases($currentDelegation);
} //No Break, executing Default Condition
default :
switch ($currentDelegation['TAS_ASSIGN_TYPE']) {
case 'CANCEL_MI':
$this->case->discriminateCases($currentDelegation);
} //No Break, executing updateAppThread
$this->case->updateAppThread ( $currentDelegation['APP_UID'], $iAppThreadIndex, $iNewDelIndex );
}//switch
//if there are subprocess to create
if (isset($aSP)) {
//Create the new case in the sub-process
// set the initial date to null the time its created
$aNewCase = $this->case->startCase($aSP['TAS_UID'], $aSP['USR_UID'],true);
//Copy case variables to sub-process case
$aFields = unserialize($aSP['SP_VARIABLES_OUT']);
$aNewFields = array();
$aOldFields = $this->case->loadCase($aNewCase['APPLICATION']);
foreach ($aFields as $sOriginField => $sTargetField) {
$sOriginField = str_replace('@', '', $sOriginField);
$sOriginField = str_replace('#', '', $sOriginField);
$sTargetField = str_replace('@', '', $sTargetField);
$sTargetField = str_replace('#', '', $sTargetField);
$aNewFields[$sTargetField] = isset($appFields['APP_DATA'][$sOriginField]) ? $appFields['APP_DATA'][$sOriginField] : '';
}
$aOldFields['APP_DATA'] = array_merge($aOldFields['APP_DATA'], $aNewFields);
$aOldFields['APP_STATUS'] = 'TO_DO';
$this->case->updateCase($aNewCase['APPLICATION'], $aOldFields);
//Create a registry in SUB_APPLICATION table
$aSubApplication = array('APP_UID' => $aNewCase['APPLICATION'],
'APP_PARENT' => $currentDelegation['APP_UID'],
'DEL_INDEX_PARENT' => $iNewDelIndex,
'DEL_THREAD_PARENT' => $iAppThreadIndex,
'SA_STATUS' => 'ACTIVE',
'SA_VALUES_OUT' => serialize($aNewFields),
'SA_INIT_DATE' => date('Y-m-d H:i:s'));
if ($aSP['SP_SYNCHRONOUS'] == 0) {
$aSubApplication['SA_STATUS'] = 'FINISHED';
$aSubApplication['SA_FINISH_DATE'] = $aSubApplication['SA_INIT_DATE'];
}
$oSubApplication = new SubApplication();
$oSubApplication->create($aSubApplication);
//If not is SYNCHRONOUS derivate one more time
if ($aSP['SP_SYNCHRONOUS'] == 0) {
$this->case->setDelInitDate($currentDelegation['APP_UID'], $iNewDelIndex);
$aDeriveTasks = $this->prepareInformation(
array( 'USER_UID' => -1,
'APP_UID' => $currentDelegation['APP_UID'],
'DEL_INDEX' => $iNewDelIndex)
);
if (isset($aDeriveTasks[1])) {
if ($aDeriveTasks[1]['ROU_TYPE'] != 'SELECT') {
$nextDelegations2 = array();
foreach ($aDeriveTasks as $aDeriveTask) {
$nextDelegations2[] = array(
'TAS_UID' => $aDeriveTask['NEXT_TASK']['TAS_UID'],
'USR_UID' => $aDeriveTask['NEXT_TASK']['USER_ASSIGNED']['USR_UID'],
'TAS_ASSIGN_TYPE' => $aDeriveTask['NEXT_TASK']['TAS_ASSIGN_TYPE'],
'TAS_DEF_PROC_CODE' => $aDeriveTask['NEXT_TASK']['TAS_DEF_PROC_CODE'],
'DEL_PRIORITY' => 3,
'TAS_PARENT' => $aDeriveTask['NEXT_TASK']['TAS_PARENT']
);
}
$currentDelegation2 = array(
'APP_UID' => $currentDelegation['APP_UID'],
'DEL_INDEX' => $iNewDelIndex,
'APP_STATUS' => 'TO_DO',
'TAS_UID' => $currentDelegation['TAS_UID'],
'ROU_TYPE' => $aDeriveTasks[1]['ROU_TYPE']
);
$this->derivate($currentDelegation2, $nextDelegations2);
}
}
}
}
}
else { //when the task doesnt generate a new AppDelegation
$iAppThreadIndex = $appFields['DEL_THREAD'];
switch ( $currentDelegation['ROU_TYPE'] ) {
case 'DISCRIMINATOR':
case 'SEC-JOIN' :
$this->case->closeAppThread ( $currentDelegation['APP_UID'], $iAppThreadIndex);
break;
default :
if($currentDelegation['TAS_ASSIGN_TYPE'] == 'STATIC_MI' || $currentDelegation['TAS_ASSIGN_TYPE'] == 'CANCEL_MI')
$this->case->closeAppThread ( $currentDelegation['APP_UID'], $iAppThreadIndex);
}//switch
}
}
//SETS THE APP_PROC_CODE
//if (isset($nextDel['TAS_DEF_PROC_CODE']))
//$appFields['APP_PROC_CODE'] = $nextDel['TAS_DEF_PROC_CODE'];
unset($aSP);
}
/* Start Block : UPDATES APPLICATION */
//Set THE APP_STATUS
$appFields['APP_STATUS'] = $currentDelegation['APP_STATUS'];
/* Start Block : Count the open threads of $currentDelegation['APP_UID'] */
$openThreads = $this->case->GetOpenThreads( $currentDelegation['APP_UID'] );
if ($openThreads == 0) {//Close case
$appFields['APP_STATUS'] = 'COMPLETED';
$appFields['APP_FINISH_DATE'] = 'now';
$this->verifyIsCaseChild($currentDelegation['APP_UID']);
}
$appFields['DEL_INDEX'] = (isset($iNewDelIndex) ? $iNewDelIndex : 0);
$appFields['TAS_UID'] = $nextDel['TAS_UID'];
/* Start Block : UPDATES APPLICATION */
$this->case->updateCase ( $currentDelegation['APP_UID'], $appFields );
/* End Block : UPDATES APPLICATION */
}
/* verifyIsCaseChild
*
* @param string $sApplicationUID
* @return void
*/
function verifyIsCaseChild($sApplicationUID)
{
//Obtain the related row in the table SUB_APPLICATION
$oCriteria = new Criteria('workflow');
$oCriteria->add(SubApplicationPeer::APP_UID, $sApplicationUID);
$oDataset = SubApplicationPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aSA = $oDataset->getRow();
if ($aSA) {
//Obtain the related row in the table SUB_PROCESS
$oCase = new Cases();
$aParentCase = $oCase->loadCase($aSA['APP_PARENT'], $aSA['DEL_INDEX_PARENT']);
$oCriteria = new Criteria('workflow');
$oCriteria->add(SubProcessPeer::PRO_PARENT, $aParentCase['PRO_UID']);
$oCriteria->add(SubProcessPeer::TAS_PARENT, $aParentCase['TAS_UID']);
$oDataset = SubProcessPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aSP = $oDataset->getRow();
if ($aSP['SP_SYNCHRONOUS'] == 1) {
$appFields = $oCase->loadCase($sApplicationUID);
//Copy case variables to parent case
$aFields = unserialize($aSP['SP_VARIABLES_IN']);
$aNewFields = array();
foreach ($aFields as $sOriginField => $sTargetField) {
$sOriginField = str_replace('@', '', $sOriginField);
$sOriginField = str_replace('#', '', $sOriginField);
$sTargetField = str_replace('@', '', $sTargetField);
$sTargetField = str_replace('#', '', $sTargetField);
$aNewFields[$sTargetField] = isset($appFields['APP_DATA'][$sOriginField]) ? $appFields['APP_DATA'][$sOriginField] : '';
}
$aParentCase['APP_DATA'] = array_merge($aParentCase['APP_DATA'], $aNewFields);
$oCase->updateCase($aSA['APP_PARENT'], $aParentCase);
//Update table SUB_APPLICATION
$oSubApplication = new SubApplication();
$oSubApplication->update(array('APP_UID' => $sApplicationUID,
'APP_PARENT' => $aSA['APP_PARENT'],
'DEL_INDEX_PARENT' => $aSA['DEL_INDEX_PARENT'],
'DEL_THREAD_PARENT' => $aSA['DEL_THREAD_PARENT'],
'SA_STATUS' => 'FINISHED',
'SA_VALUES_IN' => serialize($aNewFields),
'SA_FINISH_DATE' => date('Y-m-d H:i:s')));
//Derive the parent case
$aDeriveTasks = $this->prepareInformation(
array( 'USER_UID' => -1,
'APP_UID' => $aSA['APP_PARENT'],
'DEL_INDEX' => $aSA['DEL_INDEX_PARENT'])
);
if (isset($aDeriveTasks[1])) {
if ($aDeriveTasks[1]['ROU_TYPE'] != 'SELECT') {
$nextDelegations2 = array();
foreach ($aDeriveTasks as $aDeriveTask) {
if ( !isset($aDeriveTask['NEXT_TASK']['USER_ASSIGNED']['USR_UID']) ) {
$selectedUser = $aDeriveTask['NEXT_TASK']['USER_ASSIGNED'][0];
unset ($aDeriveTask['NEXT_TASK']['USER_ASSIGNED']);
$aDeriveTask['NEXT_TASK']['USER_ASSIGNED'] = $selectedUser;
$myLabels = array ( $aDeriveTask['NEXT_TASK']['TAS_TITLE'], $aParentCase['APP_NUMBER'], $selectedUser['USR_USERNAME'], $selectedUser['USR_FIRSTNAME'], $selectedUser['USR_LASTNAME'] );
G::SendTemporalMessage( 'ID_TASK_WAS_ASSIGNED_TO_USER', 'warning', 'labels', 10, null, $myLabels);
}
$nextDelegations2[] = array(
'TAS_UID' => $aDeriveTask['NEXT_TASK']['TAS_UID'],
'USR_UID' => $aDeriveTask['NEXT_TASK']['USER_ASSIGNED']['USR_UID'],
'TAS_ASSIGN_TYPE' => $aDeriveTask['NEXT_TASK']['TAS_ASSIGN_TYPE'],
'TAS_DEF_PROC_CODE' => $aDeriveTask['NEXT_TASK']['TAS_DEF_PROC_CODE'],
'DEL_PRIORITY' => 3,
'TAS_PARENT' => $aDeriveTask['NEXT_TASK']['TAS_PARENT']
);
}
$currentDelegation2 = array(
'APP_UID' => $aSA['APP_PARENT'],
'DEL_INDEX' => $aSA['DEL_INDEX_PARENT'],
'APP_STATUS' => 'TO_DO',
'TAS_UID' => $aParentCase['TAS_UID'],
'ROU_TYPE' => $aDeriveTasks[1]['ROU_TYPE']
);
$this->derivate($currentDelegation2, $nextDelegations2);
}
}
}
}
}
/* getDerivatedCases
* get all derivated cases and subcases from any task,
* this function is useful to know who users have been assigned and what task they do.
*
* @param string $sParentUid
* @param string $sDelIndexParent
* @return array $derivation
*
*/
function getDerivatedCases ( $sParentUid, $sDelIndexParent )
{
$oCriteria = new Criteria('workflow');
$cases = array();
$derivation = array();
//get the child delegations , of parent delIndex
$children = array();
$oCriteria->clearSelectColumns();
$oCriteria->addSelectColumn ( AppDelegationPeer::DEL_INDEX );
$oCriteria->add(AppDelegationPeer::APP_UID, $sParentUid);
$oCriteria->add(AppDelegationPeer::DEL_PREVIOUS, $sDelIndexParent );
$oDataset = AppDelegationPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
while ( is_array( $aRow) ) {
$children[] = $aRow['DEL_INDEX'];
$oDataset->next();
$aRow = $oDataset->getRow();
}
//foreach child , get the info of their derivations and subprocesses
foreach ( $children as $keyChild => $child ) {
$oCriteria = new Criteria('workflow');
$oCriteria->clearSelectColumns();
$oCriteria->addSelectColumn ( SubApplicationPeer::APP_UID );
$oCriteria->addSelectColumn ( AppDelegationPeer::APP_UID );
$oCriteria->addSelectColumn ( AppDelegationPeer::DEL_INDEX );
$oCriteria->addSelectColumn ( AppDelegationPeer::PRO_UID );
$oCriteria->addSelectColumn ( AppDelegationPeer::TAS_UID );
$oCriteria->addSelectColumn ( AppDelegationPeer::USR_UID );
$oCriteria->addSelectColumn ( UsersPeer::USR_USERNAME );
$oCriteria->addSelectColumn ( UsersPeer::USR_FIRSTNAME );
$oCriteria->addSelectColumn ( UsersPeer::USR_LASTNAME );
$oCriteria->add(SubApplicationPeer::APP_PARENT, $sParentUid);
$oCriteria->add(SubApplicationPeer::DEL_INDEX_PARENT, $child );
$oCriteria->addJoin ( SubApplicationPeer::APP_UID, AppDelegationPeer::APP_UID);
$oCriteria->addJoin ( AppDelegationPeer::USR_UID, UsersPeer::USR_UID);
$oDataset = SubApplicationPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
while ( is_array( $aRow) ) {
$oProcess = new Process();
$proFields = $oProcess->load($aRow['PRO_UID']);
$oCase = new Application();
$appFields = $oCase->load($aRow['APP_UID']);
$oTask = new Task();
$tasFields = $oTask->load($aRow['TAS_UID']);
$derivation[] = array (
'processId' => $aRow['PRO_UID'],
'processTitle' => $proFields['PRO_TITLE'],
'caseId' => $aRow['APP_UID'],
'caseNumber' => $appFields['APP_NUMBER'],
'taskId' => $aRow['TAS_UID'],
'taskTitle' => $tasFields['TAS_TITLE'],
'userId' => $aRow['USR_UID'],
'userName' => $aRow['USR_USERNAME'],
'userFullname' => $aRow['USR_FIRSTNAME'] . ' ' . $aRow['USR_LASTNAME']
);
$oDataset->next();
$aRow = $oDataset->getRow();
}
}
return $derivation;
}
function getGrpUser($aData)
{
G::LoadClass('groups');
G::LoadClass('tasks');
require_once 'classes/model/Content.php';
$oTasks = new Tasks();
$oGroups = new Groups();
$oContent = new Content();
$aGroup = array();
$aUsers = array();
$aGroup = $oTasks->getGroupsOfTask($aData['ROU_NEXT_TASK'],1);
$aGrpUid = $aGroup[0]['GRP_UID'];
$sGrpName = $oContent->load('GRP_TITLE', '',$aGrpUid, 'en');
$aGrp['GRP_NAME'] = $sGrpName;
$aGrp['GRP_UID'] = $aGrpUid;
$aUsers = $oGroups->getUsersOfGroup($aGroup[0]['GRP_UID']);
foreach($aUsers as $aKey=>$userid)
{
$aData[$aKey] = $userid;
}
return $aGrp;
//var_dump($aDerivation);
//die;
}
}

View File

@@ -0,0 +1,202 @@
<?php
/**
* class.dynaFormField.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.
*
*/
G::LoadClass('xmlDb');
/**
* Dynaform Field - DynaformField class
*
*/
class DynaFormField extends DBTable
{
/**
* Function SetTo
* @param string $objConnection
* @return void
*/
function SetTo( $objConnection )
{
DBTable::SetTo( $objConnection, 'dynaForm', array('XMLNODE_NAME') );
}
/**
* Load a dynaForm
* @param string $sUID
* @return void
*/
function Load( $sUID )
{
parent::Load( $sUID );
if (is_array($this->Fields)) {
foreach( $this->Fields as $name => $value ){
if (strcasecmp($name,'dependentfields')==0) {
$this->Fields[$name]=explode(',', $value );
}
}
}
}
/**
* Delete Fields of a dynaForm
* @param string $uid
* @return void
*/
function Delete ( $uid )
{
$this->Fields['XMLNODE_NAME'] = $uid;
parent::Delete();
}
/**
* Save Fields of a dynaform
* @param array $Fields
* @param array $labels
* @param array $options
* @return void
*/
function Save ( $Fields , $labels=array() , $options=array() )
{
if ($Fields['TYPE'] === 'javascript'){
$Fields['XMLNODE_VALUE'] = $Fields['CODE'];
unset($Fields['CODE']);
$labels = array();
}
if ($Fields['XMLNODE_NAME_OLD'] == '') {
if (($Fields['XMLNODE_NAME'][0] == '1') || ($Fields['XMLNODE_NAME'][0] == '2') ||
($Fields['XMLNODE_NAME'][0] == '3') || ($Fields['XMLNODE_NAME'][0] == '4') ||
($Fields['XMLNODE_NAME'][0] == '5') || ($Fields['XMLNODE_NAME'][0] == '6') ||
($Fields['XMLNODE_NAME'][0] == '7') || ($Fields['XMLNODE_NAME'][0] == '8') ||
($Fields['XMLNODE_NAME'][0] == '9') || ($Fields['XMLNODE_NAME'][0] == '10')) {
$Fields['XMLNODE_NAME'] = '_' . $Fields['XMLNODE_NAME'];
}
$res = $this->_dbses->Execute('SELECT * FROM dynaForm WHERE XMLNODE_NAME="'.$Fields['XMLNODE_NAME'].'"');
}
else {
if (($Fields['XMLNODE_NAME_OLD'][0] == '1') || ($Fields['XMLNODE_NAME_OLD'][0] == '2') ||
($Fields['XMLNODE_NAME_OLD'][0] == '3') || ($Fields['XMLNODE_NAME_OLD'][0] == '4') ||
($Fields['XMLNODE_NAME_OLD'][0] == '5') || ($Fields['XMLNODE_NAME_OLD'][0] == '6') ||
($Fields['XMLNODE_NAME_OLD'][0] == '7') || ($Fields['XMLNODE_NAME_OLD'][0] == '8') ||
($Fields['XMLNODE_NAME_OLD'][0] == '9') || ($Fields['XMLNODE_NAME_OLD'][0] == '10')) {
$Fields['XMLNODE_NAME_OLD'] = '_' . $Fields['XMLNODE_NAME_OLD'];
}
$res = $this->_dbses->Execute('SELECT * FROM dynaForm WHERE XMLNODE_NAME="'.$Fields['XMLNODE_NAME_OLD'].'"');
}
$this->is_new = ($res->count()==0);
$this->Fields = $Fields;
unset($this->Fields['XMLNODE_NAME_OLD']);
/*
* MPD-10 to create fields that do not appear many attributes, only the main ones?
* The show those who are not white
*/
if ($this->is_new){
foreach($this->Fields as $key => $value){
if ($value=="")
unset( $this->Fields[$key] );
}
}
else {
$this->Fields['XMLNODE_NAME'] = $Fields['XMLNODE_NAME_OLD'];
}
/*$res = $this->_dbses->Execute('INSERT INTO dynaForm'.
' (XMLNODE_TYPE,XMLNODE_VALUE)'.
' VALUES ("cdata", "'."\n".'")');*/
parent::Save();
if ($this->is_new) {
/*
* Create a new field.
*/
foreach( $labels as $lang => $value ) {
/*$res = $this->_dbses->Execute('INSERT INTO dynaForm'.
' (XMLNODE_TYPE,XMLNODE_VALUE)'.
' VALUES ("cdata", "'."\n".'")');*/
$res = $this->_dbses->Execute('INSERT INTO dynaForm.'
.$Fields['XMLNODE_NAME'].' (XMLNODE_NAME,XMLNODE_VALUE,XMLNODE_TYPE) '
.'VALUES ("","'."\n ".'","cdata")');
$res = $this->_dbses->Execute('INSERT INTO dynaForm.'
.$Fields['XMLNODE_NAME'].' (XMLNODE_NAME,XMLNODE_VALUE) '
.'VALUES ("'.$lang.'","'.str_replace('"','""',$value)/*."\n "*/.'")');
if (isset($options[$lang])) {
foreach($options[$lang] as $option => $text ) {
$res = $this->_dbses->Execute('INSERT INTO dynaForm.'
.$Fields['XMLNODE_NAME'].'.'.$lang.' (XMLNODE_NAME,XMLNODE_VALUE,XMLNODE_TYPE) '
.'VALUES ("","'." ".'","cdata")');
$res = $this->_dbses->Execute('INSERT INTO dynaForm.'
.$Fields['XMLNODE_NAME'].'.'.$lang.' (XMLNODE_NAME,XMLNODE_VALUE,name) '
.'VALUES ("option","'.str_replace('"','""',$text).'","'.str_replace('"','""',$option).'")');
$res = $this->_dbses->Execute('INSERT INTO dynaForm.'
.$Fields['XMLNODE_NAME'].'.'.$lang.' (XMLNODE_NAME,XMLNODE_VALUE,XMLNODE_TYPE) '
.'VALUES ("","'."\n ".'","cdata")');
}
}
$res = $this->_dbses->Execute('INSERT INTO dynaForm.'
.$Fields['XMLNODE_NAME'].' (XMLNODE_NAME,XMLNODE_VALUE,XMLNODE_TYPE) '
.'VALUES ("","'."\n".'","cdata")');
}
$res = $this->_dbses->Execute('INSERT INTO dynaForm'.
' (XMLNODE_TYPE,XMLNODE_VALUE)'.
' VALUES ("cdata", "'."\n".'")');
} else {
/*
* Update an existing field.
*/
$this->_dbses->Execute('UPDATE dynaForm SET XMLNODE_NAME = "' . $Fields['XMLNODE_NAME'] . '" WHERE XMLNODE_NAME = "' . $Fields['XMLNODE_NAME_OLD'] . '"');
foreach( $labels as $lang => $value ) {
$res = $this->_dbses->Execute('SELECT * FROM dynaForm.'
.$Fields['XMLNODE_NAME'].' WHERE XMLNODE_NAME ="'.$lang.'"');
if ($res->count()>0) {
$res = $this->_dbses->Execute('UPDATE dynaForm.'
.$Fields['XMLNODE_NAME'].' SET XMLNODE_VALUE = '
.'"'.str_replace('"','""',$value).'" WHERE XMLNODE_NAME ="'.$lang.'"');
} else {
$res = $this->_dbses->Execute('INSERT INTO dynaForm.'
.$Fields['XMLNODE_NAME'].' (XMLNODE_NAME,XMLNODE_VALUE) '
.'VALUES ("'.$lang.'","'.str_replace('"','""',$value).'")');
}
if (isset($options[$lang])) {
$res = $this->_dbses->Execute('DELETE FROM dynaForm.'
.$Fields['XMLNODE_NAME'].'.'.$lang.' WHERE 1');
foreach($options[$lang] as $option => $text ) {
$res = $this->_dbses->Execute('INSERT INTO dynaForm.'
.$Fields['XMLNODE_NAME'].'.'.$lang.' (XMLNODE_NAME,XMLNODE_VALUE,name) '
.'VALUES ("option","'.str_replace('"','""',$text).'","'.str_replace('"','""',$option).'")');
}
}
}
}
}
/**
* Verify if is New the Field
* @return array
*/
function isNew()
{
$res = $this->_dbses->Execute('SELECT * FROM dynaForm WHERE XMLNODE_NAME="'.$this->Fields['XMLNODE_NAME'].'"');
return ($res->count()==0);
}
}
?>

View File

@@ -0,0 +1,923 @@
<?php
/**
* class.dynaformEditor.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.
*
*/
/**
* Created on 21/12/2007
* Dynaform - Dynaform class
* @copyright 2007 COLOSA
* @author David Callizaya <davidsantos@colosa.com>
*/
G::LoadSystem("webResource");
G::LoadClass('toolBar');
G::LoadClass('dynaFormField');
require_once('classes/model/Process.php');
require_once('classes/model/Dynaform.php');
G::LoadClass('xmlDb');
class dynaformEditor extends WebResource
{
private $isOldCopy = false;
var $file='';
var $title='New Dynaform';
var $dyn_uid='';
var $dyn_type='';
var $home='';
/**
* Other Options for Editor:
* left: 'getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))',
* top: 'getAbsoluteTop(document.getElementById("dynaformEditor[0]"))',
* height: '3/4*(document.body.clientWidth-getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))*2)',
* left: 'getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))'
* left: 'getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))'
*
* Other Options for Toolbar:
* left: 'getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))',
* top: 'getAbsoluteTop(document.getElementById("dynaformEditor[0]"))',
*/
var $defaultConfig = array(
'Editor' =>array(
'left' =>'0',
'top' =>'0',
'width' =>'document.body.clientWidth-4',
'height'=>'document.body.clientHeight-4'
),
'Toolbar' =>array(
'left' =>'document.body.clientWidth-2-toolbar.clientWidth-24-3+7',
'top' =>'52'
),
'FieldsList'=>array(
'left' =>'4+toolbar.clientWidth+24',
'top' =>'getAbsoluteTop(document.getElementById("dynaformEditor[0]"))',
'width' => 244,
'height'=> 400,
)
);
var $panelConf=array(
'style' =>array(
'title'=>array('textAlign'=>'center')
),
'width' =>700,
'height' =>600,
'tabWidth' =>120,
'modal' =>true,
'drag' =>false,
'resize' =>false,
'blinkToFront'=>false
);
/**
* Constructor of the class dynaformEditor
* @param string $get
* @return void
*/
function dynaformEditor($get)
{
$this->panelConf = array_merge( $this->panelConf , $this->defaultConfig['Editor'] );
//'title' => G::LoadTranslation('ID_DYNAFORM_EDITOR').' - ['.$this->title.']',
}
/**
* Create the xml form default
* @param string $filename
* @return void
*/
function _createDefaultXmlForm($fileName)
{
//Create the default Dynaform
$sampleForm='<?xml version="1.0" encoding="UTF-8"?>'."\n";
$sampleForm.='<dynaForm type="'.$this->dyn_type.'" name="" width="500" enabletemplate="0" mode="edit">'."\n";
switch ($this->dyn_type) {
case "xmlform":
/*$sampleForm.='<title type="title" enablehtml="0">' . "\n" .
' <en>Sample form</en>' . "\n" .
'</title>'."\n";
$sampleForm.='<submit type="submit" enablehtml="0" onclick="">' . "\n" .
' <en>Submit</en>' . "\n" .
'</submit>'."\n";*/
break;
case "grid":
/*$sampleForm.='<fieldA type="text" >' . "\n" .
'<en>A</en>' . "\n" .
'</fieldA>'."\n";
$sampleForm.='<fieldB type="text" >' . "\n" .
'<en>B</en>' . "\n" .
'</fieldB>'."\n";*/
break;
}
$sampleForm.='</dynaForm>';
G::verifyPath(dirname($fileName), true);
$fp=fopen($fileName,'w');
$sampleForm=str_replace('name=""','name="'.$this->_getFilename($this->file).'"', $sampleForm );
fwrite($fp, $sampleForm);
fclose($fp);
}
/**
* Prints the DynaformEditor
* @return void
*/
function _render()
{
global $G_PUBLISH;
$script='';
/* Start Block: Load (Create if not exists) the xmlform */
$Parameters = array(
'SYS_LANG' => SYS_LANG,
'URL' => G::encrypt( $this->file , URL_KEY ),
'DYN_UID' => $this->dyn_uid,
'PRO_UID' => $this->pro_uid,
'DYNAFORM_NAME'=> $this->dyn_title,
'FILE' => $this->file,
);
$_SESSION['Current_Dynafom']['Parameters'] = $Parameters;
$XmlEditor = array(
'URL'=> G::encrypt( $this->file , URL_KEY ),
'XML'=> ''//$openDoc->getXml()
);
$JSEditor = array(
'URL'=> G::encrypt( $this->file , URL_KEY ),
);
$A=G::encrypt( $this->file , URL_KEY );
try {
$openDoc = new Xml_Document();
$fileName= $this->home . $this->file . '.xml';
if (file_exists($fileName)) {
$openDoc->parseXmlFile($fileName);
}
else {
$this->_createDefaultXmlForm($fileName);
$openDoc->parseXmlFile($fileName);
}
//$form = new Form( $this->file , $this->home, SYS_LANG, true );
$Properties = dynaformEditorAjax::get_properties( $A , $this->dyn_uid );
/* Start Block: Prepare the XMLDB connection */
define('DB_XMLDB_HOST', PATH_DYNAFORM . $this->file . '.xml' );
define('DB_XMLDB_USER','');
define('DB_XMLDB_PASS','');
define('DB_XMLDB_NAME','');
define('DB_XMLDB_TYPE','myxml');
/* Start Block: Prepare the dynaformEditor */
$G_PUBLISH = new Publisher;
$sName='dynaformEditor';
$G_PUBLISH->publisherId=$sName;
$oHeadPublisher =& headPublisher::getSingleton();
$oHeadPublisher->setTitle(G::LoadTranslation('ID_DYNAFORM_EDITOR'). ' - ' . $Properties['DYN_TITLE']);
$G_PUBLISH->AddContent('blank');
$this->panelConf['title']=$this->title;
$G_PUBLISH->AddContent('panel-init', 'mainPanel', $this->panelConf );
if ($Properties['DYN_TYPE'] == 'xmlform') {
$G_PUBLISH->AddContent('xmlform', 'toolbar', 'dynaforms/fields_Toolbar', 'display:none', $Parameters , '', '');
}
else {
$G_PUBLISH->AddContent('xmlform', 'toolbar', 'dynaforms/fields_ToolbarGrid', 'display:none', $Parameters , '', '');
}
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_Editor', 'display:none', $Parameters , '', '');
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_XmlEditor', 'display:none', $XmlEditor , '', '');
$G_PUBLISH->AddContent('blank');
$i = 0;
$aFields = array();
$aFields[] = array(
'XMLNODE_NAME' => 'char',
'TYPE' => 'char',
'UP' => 'char',
'DOWN' => 'char'
);
$oSession = new DBSession(new DBConnection(PATH_DYNAFORM . $this->file . '.xml', '', '', '', 'myxml'));
$oDataset = $oSession->Execute('SELECT * FROM dynaForm WHERE NOT( XMLNODE_NAME = "" ) AND TYPE <> "pmconnection"');
$iMaximun = $oDataset->count();
while ($aRow = $oDataset->Read()) {
$aFields[] = array(
'XMLNODE_NAME' => $aRow['XMLNODE_NAME'],
'TYPE' => $aRow['TYPE'],
'UP' => ($i > 0 ? G::LoadTranslation('ID_UP') : ''),
'DOWN' => ($i < $iMaximun-1 ? G::LoadTranslation('ID_DOWN') : ''),
'row__' => ($i + 1)
);
$i++;
break;
}
global $_DBArray;
$_DBArray['fields'] = $aFields;
$_SESSION['_DBArray'] = $_DBArray;
G::LoadClass('ArrayPeer');
$oCriteria = new Criteria('dbarray');
$oCriteria->setDBArrayTable('fields');
/***@Erik-> this is deprecated,. (unuseful) $G_PUBLISH->AddContent('propeltable', 'paged-table', 'dynaforms/fields_List', $oCriteria, $Parameters, '', SYS_URI.'dynaforms/dynaforms_PagedTableAjax');***/
$G_PUBLISH->AddContent('blank');
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_JSEditor', 'display:none', $JSEditor , '', '');
}
catch (Exception $e) {
}
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_Properties', 'display:none', $Properties , '', '');
//for showHide tab option @Neyek
$G_PUBLISH->AddContent('blank');
$G_PUBLISH->AddContent('panel-tab',G::LoadTranslation("ID_PREVIEW"),$sName.'[3]','dynaformEditor.changeToPreview','dynaformEditor.saveCurrentView');
$G_PUBLISH->AddContent('panel-tab',G::LoadTranslation("ID_XML"),$sName.'[4]','dynaformEditor.changeToXmlCode','dynaformEditor.saveCurrentView');
$G_PUBLISH->AddContent('panel-tab',G::LoadTranslation("ID_HTML"),$sName.'[5]','dynaformEditor.changeToHtmlCode','dynaformEditor.saveCurrentView');
$G_PUBLISH->AddContent('panel-tab',G::LoadTranslation("ID_FIELDS_LIST"),$sName.'[6]','dynaformEditor.changeToFieldsList','dynaformEditor.saveCurrentView');
$G_PUBLISH->AddContent('panel-tab',G::LoadTranslation("ID_JAVASCRIPTS"),$sName.'[7]','dynaformEditor.changeToJavascripts','dynaformEditor.saveCurrentView');
$G_PUBLISH->AddContent('panel-tab',G::LoadTranslation("ID_PROPERTIES"),$sName.'[8]','dynaformEditor.changeToProperties','dynaformEditor.saveCurrentView');
//for showHide tab option @Neyek
$G_PUBLISH->AddContent('panel-tab',G::LoadTranslation("ID_CONDITIONS_EDITOR"),$sName.'[9]','dynaformEditor.changeToShowHide','dynaformEditor.saveShowHide');
$G_PUBLISH->AddContent('panel-close');
$oHeadPublisher->addScriptFile('/jscore/dynaformEditor/core/dynaformEditor.js');
$oHeadPublisher->addScriptFile('/js/dveditor/core/dveditor.js');
$oHeadPublisher->addScriptFile('/codepress/codepress.js',1);
$oHeadPublisher->addScriptFile('/js/grid/core/grid.js');
$oHeadPublisher->addScriptCode('
var DYNAFORM_URL="'.$Parameters['URL'].'";
leimnud.event.add(window,"load",function(){ loadEditor(); });
');
G::RenderPage( "publish-treeview" );
}
/**
* Get the filename
* @param string $file
* @return string
*/
function _getFilename($file)
{
return (strcasecmp(substr($file,-5),'_tmp0')==0)? substr($file,0,strlen($file)-5) : $file;
}
/**
* Set the temporal copy
* @param string $onOff
* @return void
*/
function _setUseTemporalCopy($onOff)
{
$file = self::_getFilename( $this->file );
if ($onOff) {
$this->file=$file.'_tmp0';
self::_setTmpData(array('useTmpCopy'=>true));
if (!file_exists(PATH_DYNAFORM . $file . '.xml'))
$this->_createDefaultXmlForm(PATH_DYNAFORM . $file . '.xml');
//Creates a copy if it does not exists, else, use the old copy
if (!file_exists(PATH_DYNAFORM . $this->file . '.xml'))
self::_copyFile(PATH_DYNAFORM . $file . '.xml',PATH_DYNAFORM . $this->file . '.xml');
if (!file_exists(PATH_DYNAFORM . $this->file . '.html')
&& file_exists(PATH_DYNAFORM . $file . '.html'))
self::_copyFile(PATH_DYNAFORM . $file . '.html',PATH_DYNAFORM . $this->file . '.html');
}
else {
$this->file=$file;
self::_setTmpData(array());
}
}
/**
* Set temporal data
* @param $data
* @return void
*/
function _setTmpData($data)
{
G::verifyPath(PATH_C . 'dynEditor/',true);
$fp=fopen(PATH_C . 'dynEditor/'.session_id().'.php','w');
fwrite($fp,'$tmpData=unserialize(\''.addcslashes(serialize($data),'\\\'').'\');');
fclose($fp);
}
/**
* Get temporal data
* @param string $filename
* @return array
*/
function _getTmpData()
{
$tmpData = array();
$file = PATH_C . 'dynEditor/'.session_id().'.php';
if (file_exists($file)) eval(implode('',file($file)));
return $tmpData;
}
/**
* Copy files
* @param file $from
* @param file $to
* @return void
*/
function _copyFile($from,$to)
{
$copy = implode('',file($from));
$fcopy = fopen($to,"w");
fwrite($fcopy, $copy);
fclose($fcopy);
}
}
interface iDynaformEditorAjax
{
//public function render_preview($A);
}
/**
* DynaformEditorAjax - DynaformEditorAjax class
*/
class dynaformEditorAjax extends dynaformEditor implements iDynaformEditorAjax
{
/**
* Constructor of the class dynaformEditorAjax
* @param var $post
* @return void
*/
function dynaformEditorAjax($post)
{
$this->_run($post);
}
/**
* Function Run
* @param var $post
* @return void
*/
function _run($post)
{
WebResource::WebResource($_SERVER['REQUEST_URI'],$post);
}
/**
* Prints the DynaformEditorAjax
* @param object $A
* @return ob_get_clean
*/
function render_preview($A)
{ ob_start();
$file = G::decrypt( $A , URL_KEY );
global $G_PUBLISH;
$G_PUBLISH = new Publisher;
$G_PUBLISH->publisherId='preview';
$form = new Form( $file , PATH_DYNAFORM, SYS_LANG, true, $G_PUBLISH->publisherId);
switch(basename($form->template,'.html')) {
case 'grid':
$template = 'grid';
$aAux = array_keys($form->fields);
if (count($aAux) > 0) {
$aFields = (array_combine($aAux,$aAux));
}
else {
$aFields = $aAux;
}
if (is_array($aFields)) {
foreach($aFields as $key => $val)
$aFields[$key]=array(1=>"",2=>"",3=>"",4=>"",5=>"");
}
break;
default:
$template = 'xmlform_' . $G_PUBLISH->publisherId;
$aFields = array( '__DYNAFORM_OPTIONS'=> array(
'PREVIOUS_STEP' => '#',
'NEXT_STEP' => '#',
'PREVIOUS_ACTION' => 'return false;',
'NEXT_ACTION' => 'return false;'
)
);
}
$G_PUBLISH->AddContent('dynaform', $template , $file, '',$aFields, '');
G::RenderPage('publish','raw');
return ob_get_clean();
}
/**
* Prints the Dynaform in format HTML
* @param object $A
* @return array
*/
function render_htmledit($A)
{
$script = '';
$file = G::decrypt( $A , URL_KEY );
ob_start();
global $G_PUBLISH;
$form = new Form( $file , PATH_DYNAFORM, SYS_LANG, true );
$G_PUBLISH = new Publisher;
$G_PUBLISH->publisherId = '';
$html = $this->get_htmlcode($A);
if (!is_string($html)) {
$error = $html;
$html = '';
}
else {
$error = 0;
}
$HtmlEditor = array(
'URL' => $A,
'HTML'=> $html
);
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_HtmlEditor', '', $HtmlEditor , '', '');
G::RenderPage( "publish", 'raw' );
return array('error'=>$error,'html'=>ob_get_clean());
}
/**
* Get the html code
* Loads the stored HTML or the default Template if
* it does not exists.
* @param object $A
* @return code html
*/
function get_htmlcode($A)
{
try {
$script = '';
$file = G::decrypt( $A , URL_KEY );
$form = new Form( $file , PATH_DYNAFORM, SYS_LANG, true );
/* Navigation Bar */
/*$form->fields=G::array_merges(
array('__DYNAFORM_OPTIONS' => new XmlForm_Field_XmlMenu(
new Xml_Node(
'__DYNAFORM_OPTIONS',
'complete',
'',
array('type'=>'xmlmenu','xmlfile'=>'gulliver/dynaforms_Options')
),SYS_LANG,PATH_XMLFORM,$form)
),
$form->fields);*/
/**/
/*
* Loads the stored HTML or the default Template if
* it does not exists.
*/
$filename = substr($form->fileName , 0, -3) .
( $form->type==='xmlform' ? '' : '.' . $form->type ) . 'html';
if (!file_exists( $filename )) {
$html = $form->printTemplate( $form->template , $script );
}
else {
$html = implode( '', file( $filename ) );
}
/*
* It adds the new fields automatically at the bottom of the form.
* TODO: <20>TOP OR BOTTOM?
* Improving detection algorithm of new fields.
* Current: Do not check the fields that have already been reviewed (saving)
* Already checked the temporary file dynaforms editor.
*/
$tmp = self::_getTmpData();
if (!isset($tmp['OLD_FIELDS'])) $tmp['OLD_FIELDS']=array();//var_dump($html);die;
$aAux = explode('</form>', $html);
foreach($form->fields as $field) {
if ((strpos( $html , '{$form.'.$field->name.'}' )===FALSE) &&
(strpos( $html , '{$'.$field->name.'}' )===FALSE) ) {
//Aparantly is new (but could be a deleted or non visible like private type fields)
switch (strtolower($field->type)) {
case 'private':
case 'phpvariable':
break;
default:
if (array_search( $field->name , $tmp['OLD_FIELDS'] )===false) {
//TOP
$aAux[0] .= '<br/>{$'.$field->name.'}'.'{$form.'.$field->name.'}';
//$html.='<br/>{$'.$field->name.'}'.'{$form.'.$field->name.'}';
//BOTTOM
//$html='{$'.$field->name.'}'.'{$form.'.$field->name.'}'.$html;
//$tmp['OLD_FIELDS'][]=$field->name;
}
}
}
}
self::_setTmpData($tmp);
//$html=str_replace('{$form_className}','formDefault', $html );
$html=str_replace('{$form_className}','formDefault', $aAux[0] . '</form>' );
return $html;
}
catch (Exception $e) {
return (array) $e;
}
}
/**
* Restore the html code
* @param object $A
* @return code html
*/
function restore_html($A)
{
$script = '';
$fileTmp = G::decrypt( $A , URL_KEY );
$file = dynaformEditor::_getFilename($fileTmp);
$form = new Form( $fileTmp , PATH_DYNAFORM, SYS_LANG, true );
/* Navigation Bar */
$form->fields=G::array_merges(
array('__DYNAFORM_OPTIONS' => new XmlForm_Field_XmlMenu(
new Xml_Node(
'__DYNAFORM_OPTIONS',
'complete',
'',
array('type'=>'xmlmenu','xmlfile'=>'gulliver/dynaforms_Options')
),SYS_LANG,PATH_XMLFORM,$form)
),
$form->fields);
$form->enableTemplate = false;
$html = $form->printTemplate( $form->template , $script );
$html = str_replace('{$form_className}','formDefault', $html );
if (file_exists(PATH_DYNAFORM . $fileTmp . '.html')) {
unlink(PATH_DYNAFORM . $fileTmp . '.html');
}
$fp=fopen(PATH_DYNAFORM . $fileTmp . '.html','w');
fwrite($fp, $html);
fclose($fp);
return $html;
}
/**
* Set the html code
* @param object $A
* @return array
*/
function set_htmlcode($A,$htmlcode)
{
try {
$file = G::decrypt( $A , URL_KEY );
$form = new Form( $file , PATH_DYNAFORM, SYS_LANG, true );
$filename = substr($form->fileName , 0, -3) .
( $form->type==='xmlform' ? '' : '.' . $form->type ) . 'html';
$fp=fopen($filename, 'w');
fwrite($fp, $htmlcode );
fclose($fp);
return 0;
}
catch(Exception $e) {
return (array)$e;
}
}
/**
* Get the xml code
* @param object $A
* @return array
*/
function get_xmlcode($A)
{
try {
$file = G::decrypt( $A , URL_KEY );
$xmlcode = implode('',file(PATH_DYNAFORM . $file . '.xml'));
return array("xmlcode"=>$xmlcode,"error"=>0);
}
catch(Exception $e) {
return array("xmlcode"=>"","error"=>(array)$e);
}
}
/**
* Set the xml code
* @param object $A
* @param array $xmlcode
* @return string
*/
function set_xmlcode($A,$xmlcode)
{
$file = G::decrypt( $A , URL_KEY );
$xmlcode = str_replace('&nbsp;', ' ', trim($xmlcode));
$fp = fopen(PATH_DYNAFORM . $file . '.xml', 'w');
fwrite($fp, $xmlcode );
fclose($fp);
return "";
}
/**
* Get the javascript code
* @param object $A
* @param string $fieldName
* @return array
*/
function get_javascripts($A,$fieldName)
{
try {
$file = G::decrypt( $A , URL_KEY );
$form = new Form( $file , PATH_DYNAFORM, SYS_LANG, true );
$aOptions = array();
$sCode = '';
foreach($form->fields as $name => $value ) {
if (strcasecmp($value->type,"javascript")==0) {
$aOptions[] = array('key'=>$name,'value'=>$name);
if ( $name == $fieldName )
$sCode = $value->code;
}
}
return array('aOptions'=>$aOptions, 'sCode'=>$sCode );
}
catch(Exception $e) {
return (array) $e;
}
}
/**
* Set the javascript code
* @param object $A
* @param string $fieldName
* @param string $sCode
* @return array
*/
function set_javascript($A,$fieldName,$sCode)
{
try {
$sCode = rtrim($sCode);
$file = G::decrypt( $A , URL_KEY );
$dbc2 = new DBConnection( PATH_DYNAFORM . $file . '.xml' ,'','','','myxml' );
$ses2 = new DBSession($dbc2);
$ses2->execute(G::replaceDataField("UPDATE dynaForm SET XMLNODE_VALUE = @@CODE WHERE XMLNODE_NAME = @@FIELDNAME ", array('FIELDNAME'=>$fieldName,'CODE'=>$sCode), "myxml" ));
return 0;
}
catch(Exception $e) {
return (array) $e;
}
}
/**
* Get properties of the dynaForm
* @param file $A
* @param string $DYN_UID
* @return array
*/
function get_properties( $A, $DYN_UID )
{
$file = G::decrypt( $A , URL_KEY );
$tmp = self::_getTmpData();
if (!(isset($tmp['Properties']) && isset($tmp['useTmpCopy']))) {
$dynaform = new dynaform;
$dynaform->load( $DYN_UID );
$form = new Form( $file , PATH_DYNAFORM, SYS_LANG, true );
$Properties = array(
'A' => $A,
'DYN_UID' => $dynaform->getDynUid(),
'PRO_UID' => $dynaform->getProUid(),
'DYN_TITLE' => $dynaform->getDynTitle(),
'DYN_TYPE' => $dynaform->getDynType(),
'DYN_DESCRIPTION'=> $dynaform->getDynDescription(),
'WIDTH' => $form->width,
//'ENABLETEMPLATE'=> $form->enableTemplate,
'MODE' => $form->mode,
'PRINTDYNAFORM' => $form->printdynaform,
'NEXTSTEPSAVE' => $form->nextstepsave
);
$tmp['Properties']=$Properties;
self::_setTmpData($tmp);
}
else {
$form = new Form( $file , PATH_DYNAFORM, SYS_LANG, true );
$Properties = $tmp['Properties'];
if (!isset($Properties['ENABLETEMPLATE'])) $Properties['ENABLETEMPLATE'] ="0";
$Properties['WIDTH']=$form->width;
$Properties['MODE']=$form->mode;
}
return $Properties;
}
/**
* Set properties of the dynaForm
* @param file $A
* @param string $DYN_UID
* @param array $getFields
* @return array
*/
function set_properties($A, $DYN_UID, $getFields)
{
try {
$post = array();
parse_str( $getFields, $post );
$Fields = $post['form'];
//if (!isset($Fields['ENABLETEMPLATE'])) $Fields['ENABLETEMPLATE'] ="0";
$file = G::decrypt( $A , URL_KEY );
$tmp=self::_getTmpData();
if (!isset($tmp['useTmpCopy'])) {
$dynaform = new dynaform;
$dynaform->update( $Fields );
}
else {
$tmp['Properties']=$Fields;
self::_setTmpData($tmp);
}
$dbc2 = new DBConnection( PATH_DYNAFORM . $file . '.xml' ,'','','','myxml' );
$ses2 = new DBSession($dbc2);
//if (!isset($Fields['ENABLETEMPLATE'])) $Fields['ENABLETEMPLATE'] ="0";
if (isset($Fields['WIDTH'])) {
$ses2->execute(G::replaceDataField("UPDATE . SET WIDTH = @@WIDTH WHERE XMLNODE_NAME = 'dynaForm' ", $Fields));
}
/*if (isset($Fields['ENABLETEMPLATE'])) {
$ses2->execute(G::replaceDataField("UPDATE . SET ENABLETEMPLATE = @@ENABLETEMPLATE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields));
}*/
if (isset($Fields['DYN_TYPE'])) {
$ses2->execute(G::replaceDataField("UPDATE . SET TYPE = @@DYN_TYPE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields));
}
if (isset($Fields['MODE'])) {
$ses2->execute(G::replaceDataField("UPDATE . SET MODE = @@MODE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields));
}
if (isset($Fields['NEXTSTEPSAVE'])) {
$ses2->execute(G::replaceDataField("UPDATE . SET NEXTSTEPSAVE = @@NEXTSTEPSAVE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields));
}
if (isset($Fields['PRINTDYNAFORM'])) {
$ses2->execute(G::replaceDataField("UPDATE . SET PRINTDYNAFORM = @@PRINTDYNAFORM WHERE XMLNODE_NAME = 'dynaForm' ", $Fields));
}
return 0;
}
catch(Exception $e) {
return (array) $e;
}
}
/**
* Get enable template
* @param object $A
* @return string
*/
function get_enabletemplate( $A )
{
$file = G::decrypt( $A , URL_KEY );
$form = new Form( $file , PATH_DYNAFORM, SYS_LANG, true );
return $form->enableTemplate;
}
/**
* Set enable template
* @param object $A
* @param string $value
* @return string
*/
function set_enabletemplate( $A, $value )
{
$file = G::decrypt( $A , URL_KEY );
$value = $value=="1"?"1":"0";
$dbc2 = new DBConnection( PATH_DYNAFORM . $file . '.xml' ,'','','','myxml' );
$ses2 = new DBSession($dbc2);
$ses2->execute("UPDATE . SET ENABLETEMPLATE = '$value'");
return $value;
}
/**
* Save a dynaForm
* @param object $A
* @param string $DYN_UID
* @return array
*/
function save($A,$DYN_UID)
{
try {
$answer = 0;
$file = G::decrypt( $A , URL_KEY );
$tmp = self::_getTmpData();
if (isset($tmp['useTmpCopy'])) { /*Save Register*/
$dynaform = new dynaform;
$dynaform->update( $tmp['Properties'] );
/*Save file*/
$copy = implode('',file(PATH_DYNAFORM . $file . '.xml'));
/*
* added by krlos carlos/a/colosa.com
* in here we are validation if a xmlform has a submit action
*/
if(!eregi('type="submit"',$copy) && !eregi('type="grid"',$copy) && !isset($_SESSION['submitAction']) ){
$_SESSION['submitAction']= 1;
$answer = 'noSub';
}
$copyHtml = false;
if (file_exists(PATH_DYNAFORM . $file . '.html')) {
$copyHtml = implode('',file(PATH_DYNAFORM . $file . '.html'));
}
$file = dynaformEditor::_getFilename($file);
$fcopy = fopen(PATH_DYNAFORM . $file . '.xml',"w");
fwrite($fcopy, $copy);
fclose($fcopy);
if ($copyHtml) {
$fcopy = fopen(PATH_DYNAFORM . $file . '.html',"w");
fwrite($fcopy, $copyHtml);
fclose($fcopy);
}
}
else {
//throw new Exception("It should not come here unless you have disabled the temporary copy.");
}
return $answer;
}
catch(Exception $e) {
return (array) $e;
}
}
/**
* Close a dynaform
* @param object $A
* @return array
*/
function close($A)
{
try {
/*
* we are unseting this variable. It's our control about to save the xmlfrom
*/
unset($_SESSION['submitAction']);
$file = G::decrypt( $A , URL_KEY );
//return(array('response'=>PATH_DYNAFORM . $file . '.xml'));
/* Delete the temporal copy */
$tmp=self::_getTmpData();
$xmlFile = PATH_DYNAFORM . $file . '.xml';
$htmlFile = PATH_DYNAFORM . $file . '.html';
//return(array('response'=>$tmp['useTmpCopy']));
if (isset($tmp['useTmpCopy'])) {
//return(array('response'=>PATH_DYNAFORM . $file . '.xml'));
if ($file!==dynaformEditor::_getFilename($file)) {
// return(array('response'=>PATH_DYNAFORM . $file . '.xml'));
if(file_exists($xmlFile)) {
unlink($xmlFile);
}
if(file_exists($htmlFile))
unlink($htmlFile);
}
}
return 0;
}catch(Exception $e) {
return (array) $e;
}
}
/**
* Checks if a dynaform was changed
* @param file $A
* @param string $DYN_UID
* @return array
*/
function is_modified($A,$DYN_UID)
{
$file = G::decrypt( $A , URL_KEY );
try {
/* Compare Properties */
$dynaform = new dynaform;
$dynaform->load( $DYN_UID );
$form = new Form( $file , PATH_DYNAFORM, SYS_LANG, true );
$sp = array(
'A' => $A,
'DYN_UID' => $dynaform->getDynUid(),
'PRO_UID' => $dynaform->getProUid(),
'DYN_TITLE' => $dynaform->getDynTitle(),
'DYN_TYPE' => $dynaform->getDynType(),
'DYN_DESCRIPTION'=> $dynaform->getDynDescription(),
'WIDTH' => $form->width,
'ENABLETEMPLATE' => $form->enableTemplate,
'MODE' => $form->mode
);
$P = self::get_properties($A,$DYN_UID);
if (!isset($P['DYN_TITLE'])) {
$P['DYN_TITLE'] = $sp['DYN_TITLE'];
}
if (!isset($P['DYN_TYPE'])) {
$P['DYN_TYPE'] = $sp['DYN_TYPE'];
}
if (!isset($P['DYN_DESCRIPTION'])) {
$P['DYN_DESCRIPTION'] = $sp['DYN_DESCRIPTION'];
}
if (!isset($P['WIDTH'])) {
$P['WIDTH'] = $sp['WIDTH'];
}
if (!isset($P['ENABLETEMPLATE'])) {
$P['ENABLETEMPLATE'] = $sp['ENABLETEMPLATE'];
}
if (!isset($P['MODE'])) {
$P['MODE'] = $sp['MODE'];
}
$modPro = ($sp['DYN_TITLE']!=$P['DYN_TITLE']) ||
($sp['DYN_TYPE']!=$P['DYN_TYPE']) ||
($sp['DYN_DESCRIPTION']!=$P['DYN_DESCRIPTION']) /*||
($sp['WIDTH']!=$P['WIDTH']) ||
($sp['ENABLETEMPLATE']!=$P['ENABLETEMPLATE']) ||
($sp['MODE']!=$P['MODE'])*/;
/* Compare copies */
$fileOrigen = dynaformEditor::_getFilename($file);
$copy = implode('',file(PATH_DYNAFORM . $file . '.xml'));
$origen = implode('',file(PATH_DYNAFORM . $fileOrigen . '.xml'));
$copyHTML = file_exists(PATH_DYNAFORM . $file . '.html')?implode('',file(PATH_DYNAFORM . $file . '.html')):false;
$origenHTML = file_exists(PATH_DYNAFORM . $fileOrigen . '.html')? implode('',file(PATH_DYNAFORM . $fileOrigen . '.html')):false;
$modFile = ($copy!==$origen) || ($origenHTML && ($copyHTML!==$origenHTML));
//Return
//return array("*message"=>sprintf("%s, (%s= %s %s):", $modPro?"1":"0" , $modFile?"1":"0", ($copy!==$origen)?"1":"0" , ($origenHTML && ($copyHTML!==$origenHTML))?"1":"0" ));
//die("c'est fini");
return $modPro || $modFile;
}
catch(Exception $e) {
return (array) $e;
}
}
}
?>

View File

@@ -0,0 +1,84 @@
<?php
/**
* class.groupUser.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.
*
* It works with the table GROUP_USER
*
* Copyright (C) 2007 COLOSA
*
* License: LGPL, see LICENSE
*
*/
/**
* GroupUser - GroupUser class
* @package ProcessMaker
* @author Julio Cesar Laura Avendaño
* @copyright 2007 COLOSA
*/
G::LoadClass('pmObject');
class GroupUser extends DBTable
{
/**
* Constructor
* @param object $oConnection
* @return variant
*/
function GroupUser($oConnection = null)
{
if ($oConnection){
return parent::setTo($oConnection, 'GROUP_USER', array('GRP_UID', 'USR_UID'));
} else {
return;
}
}
/*
* Set the Data Base connection
* @param object $oConnection
* @return variant/ the connection or void
*/
function setTo($oConnection = null)
{
if ($oConnection) {
return parent::setTo($oConnection, 'GROUP_USER', array('GRP_UID', 'USR_UID'));
} else {
return;
}
}
/**
* Of to assign a user from a group
* @param string $sGroup
* @param string $sUser
* @return void
*/
function ofToAssignUser($sGroup = '', $sUser = '')
{
$this->Fields['GRP_UID'] = $sGroup;
$this->Fields['USR_UID'] = $sUser;
parent::delete();
}
}
?>

View File

@@ -0,0 +1,366 @@
<?php
/**
* class.groups.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.
*
*/
require_once 'classes/model/Groupwf.php';
require_once 'classes/model/GroupUser.php';
require_once 'classes/model/Users.php';
/**
* Groups - Groups class
* @package ProcessMaker
* @copyright 2007 COLOSA
*/
class Groups
{
/**
* Get the assigned users of a group
* @param string $sGroupUID
* @return array
*/
function getUsersOfGroup($sGroupUID)
{
try {
$aUsers = array();
$oCriteria = new Criteria();
$oCriteria->addJoin(UsersPeer::USR_UID, GroupUserPeer::USR_UID, Criteria::LEFT_JOIN);
$oCriteria->add(GroupUserPeer::GRP_UID, $sGroupUID);
$oCriteria->add(UsersPeer::USR_STATUS, 'ACTIVE');
$oDataset = UsersPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aUsers[] = $aRow;
$oDataset->next();
}
return $aUsers;
}
catch (exception $oError) {
throw ($oError);
}
}
/**
* Get the active groups for an user
* @param string $sUserUID
* @return array
*/
function getActiveGroupsForAnUser($sUserUID)
{
try {
$oCriteria = new Criteria();
$oCriteria->addSelectColumn(GroupUserPeer::GRP_UID);
$oCriteria->addSelectColumn(GroupwfPeer::GRP_STATUS);
$oCriteria->add(GroupUserPeer::USR_UID, $sUserUID);
$oCriteria->add(GroupwfPeer::GRP_STATUS, 'ACTIVE');
$oCriteria->addJoin(GroupUserPeer::GRP_UID, GroupwfPeer::GRP_UID, Criteria::LEFT_JOIN);
$oDataset = GroupUserPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aGroups = array();
$aRow = $oDataset->getRow();
while (is_array($aRow)) {
$aGroups[] = $aRow['GRP_UID'];
$oDataset->next();
$aRow = $oDataset->getRow();
}
return $aGroups;
}
catch (exception $oError) {
throw ($oError);
}
}
/**
* Set a user to group
* @param string $GrpUid, $UsrUid
* @return array
*/
function addUserToGroup($GrpUid, $UsrUid)
{
try {
$oGrp = GroupUserPeer::retrieveByPk($GrpUid, $UsrUid);
if (get_class($oGrp) == 'GroupUser') {
return true;
} else {
$oGrp = new GroupUser();
$oGrp->setGrpUid($GrpUid);
$oGrp->setUsrUid($UsrUid);
$oGrp->Save();
}
}
catch (exception $oError) {
throw ($oError);
}
}
/*
* Remove a user from group
* @param string $GrpUid, $UsrUid
* @return array
*/
function removeUserOfGroup($GrpUid, $UsrUid)
{
$gu = new GroupUser();
$gu->remove($GrpUid, $UsrUid);
}
/**
* get all groups
* @param none
* @return $objects
*/
function getAllGroups()
{
try {
$criteria = new Criteria();
$criteria->add(GroupwfPeer::GRP_UID, "", Criteria::NOT_EQUAL);
$con = Propel::getConnection(GroupwfPeer::DATABASE_NAME);
$objects = GroupwfPeer::doSelect($criteria, $con);
return $objects;
}
catch (exception $e) {
throw $e;
}
}
/**
* get all the groups from a single user
* @param $sUserUid user uid
* @return an array of group objects
*/
function getUserGroups($sUserUID)
{
try {
$criteria = new Criteria();
$criteria->add(GroupwfPeer::GRP_UID, "", Criteria::NOT_EQUAL);
$criteria->add(GroupUserPeer::USR_UID, $sUserUID);
$criteria->add(GroupwfPeer::GRP_STATUS, 'ACTIVE');
$criteria->addJoin(GroupUserPeer::GRP_UID, GroupwfPeer::GRP_UID, Criteria::LEFT_JOIN);
$con = Propel::getConnection(GroupwfPeer::DATABASE_NAME);
$objects = GroupwfPeer::doSelect($criteria, $con);
return $objects;
}
catch (exception $e) {
throw $e;
}
}
/**
* Remove a user from all groups
* @param string $sUsrUid
* @return void
*/
public function removeUserOfAllGroups($sUserUID = '')
{
try {
$oCriteria = new Criteria('workflow');
$oCriteria->add(GroupUserPeer::USR_UID, $sUserUID);
GroupUserPeer::doDelete($oCriteria);
}
catch (exception $oError) {
throw ($oError);
}
}
/**
* Get a criteria object of all users from group
* @param string $sGroupUID
* @return array
*/
function getUsersGroupCriteria($sGroupUID = '')
{
require_once 'classes/model/GroupUser.php';
require_once 'classes/model/Users.php';
try {
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(GroupUserPeer::GRP_UID);
$oCriteria->addSelectColumn(UsersPeer::USR_UID);
$oCriteria->addSelectColumn(UsersPeer::USR_USERNAME);
$oCriteria->addSelectColumn(UsersPeer::USR_FIRSTNAME);
$oCriteria->addSelectColumn(UsersPeer::USR_LASTNAME);
$oCriteria->addSelectColumn(UsersPeer::USR_EMAIL);
$oCriteria->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN);
$oCriteria->add(GroupUserPeer::GRP_UID, $sGroupUID);
$oCriteria->add(UsersPeer::USR_STATUS, 'ACTIVE');
return $oCriteria;
}
catch (exception $oError) {
throw ($oError);
}
}
/**
* Get a criteria object of all groups from user
* @param string $sGroupUID
* @return array
*/
function getUserGroupsCriteria($sUserUID = '')
{
require_once 'classes/model/GroupUser.php';
require_once 'classes/model/Users.php';
try {
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(UsersPeer::USR_UID);
$oCriteria->addSelectColumn(GroupUserPeer::GRP_UID);
$oCriteria->addSelectColumn(UsersPeer::USR_FIRSTNAME);
$oCriteria->addSelectColumn(UsersPeer::USR_LASTNAME);
$oCriteria->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN);
$oCriteria->add(GroupUserPeer::GRP_UID, $sUserUID);
$oCriteria->add(UsersPeer::USR_STATUS, 'ACTIVE');
return $oCriteria;
}
catch (exception $oError) {
throw ($oError);
}
}
/**
* Get the number of groups
* @param string $sGroupUid
* @return integer $cnt
*/
function getNumberGroups($sUserUID)
{
try {
$allGroups = $this->getUserGroups($sUserUID);
$cnt = 0;
foreach ($allGroups as $group) {
$cnt++;
}
return $cnt;
}
catch (exception $oError) {
print_r($oError);
}
}
/**
* Return the available users list criteria object
* @param string $sGroupUID
* @return object
*/
function getAvailableUsersCriteria($sGroupUID = '')
{
try {
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(UsersPeer::USR_UID);
$oCriteria->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN);
$oCriteria->add(GroupUserPeer::GRP_UID, $sGroupUID);
$oCriteria->add(UsersPeer::USR_STATUS, 'ACTIVE');
$oDataset = UsersPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aUIDs = array();
while ($aRow = $oDataset->getRow()) {
$aUIDs[] = $aRow['USR_UID'];
$oDataset->next();
}
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(UsersPeer::USR_UID);
$oCriteria->addSelectColumn(UsersPeer::USR_FIRSTNAME);
$oCriteria->addSelectColumn(UsersPeer::USR_LASTNAME);
$oCriteria->add(UsersPeer::USR_UID, $aUIDs, Criteria::NOT_IN);
$oCriteria->add(UsersPeer::USR_STATUS, 'ACTIVE');
return $oCriteria;
}
catch (exception $oError) {
throw ($oError);
}
}
/**
* Verify if a user is assigned to a group
* @param $GrpUid group Uid
* @param $UsrUid user Uid
* @return 1/0 if it's or not assigned
*/
function verifyUsertoGroup($GrpUid, $UsrUid)
{
try {
$oGrp = GroupUserPeer::retrieveByPk($GrpUid, $UsrUid);
if (get_class($oGrp) == 'GroupUser') {
return 1;
} else {
return 0;
}
}
catch (exception $oError) {
throw ($oError);
}
}
/**
* Verify the existence of a Group
* @param $sGroupUid group Uid
* @return 1/0 if exist or not
*/
function verifyGroup($sGroupUID)
{
try {
$aUsers = array();
$oCriteria = new Criteria();
//$oCriteria->addJoin(UsersPeer::USR_UID, GroupUserPeer::USR_UID, Criteria::LEFT_JOIN);
$oCriteria->add(GroupwfPeer::GRP_UID, $sGroupUID);
//$oCriteria->add(UsersPeer::USR_STATUS, 'ACTIVE');
$oDataset = GroupwfPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
if(is_array($aRow))
return 1;
else
return 0;
}
catch (exception $oError) {
throw ($oError);
}
}
/**
* Load all the data of a group with a search based on it uid
* @param $GrpUid group uid
* @return an array of objects/false/exception object
*
*/
public function load($GrpUid){
try {
$criteria = new Criteria();
$criteria->add(GroupwfPeer::GRP_UID, $GrpUid, Criteria::EQUAL);
$con = Propel::getConnection(GroupwfPeer::DATABASE_NAME);
$objects = GroupwfPeer::doSelect($criteria, $con);
if(is_array($objects) && count($objects)>0){
return $objects[0];
} else {
return false;
}
}
catch (exception $e) {
throw $e;
}
}
}

View File

@@ -0,0 +1,102 @@
<?php
/**
* @brief insert mail into the spool database
*
* @package Tomahawk_Mail
* @author Ian K Armstrong <ika@[REMOVE_THESE_CAPITALS]openmail.cc>
* @copyright Copyright (c) 2007, Ian K Armstrong
* @license http://www.opensource.org/licenses/gpl-3.0.html GNU Public License
* @link http://www.openmail.cc
*
* @category web_mail
* @subpackage send
* @filesource
* @version
*
* @file class.insert.php
*
*/
require_once ( "classes/model/AppMessage.php" );
class insert
{
private $db_spool;
private $status;
/**
* construct of insert
*
* @param string $pPRO_UID
* @return void
*/
function __construct($db_spool=array())
{
if(count($db_spool)>0)
$db_spool = $this->db_insert($db_spool);
}
/**
* returnStatus
*
* @return $this->status;
*/
public function returnStatus()
{
return $this->status;
}
/**
* db_insert
*
* @param array $db_spool
* @return string $sUID;
*/
public function db_insert($db_spool)
{
$sUID = G::generateUniqueID();
$spool = new AppMessage();
$spool->setAppMsgUid($sUID);
$spool->setMsgUid($db_spool['msg_uid']);
$spool->setAppUid($db_spool['app_uid']);
$spool->setDelIndex($db_spool['del_index']);
$spool->setAppMsgType($db_spool['app_msg_type']);
$spool->setAppMsgSubject($db_spool['app_msg_subject']);
$spool->setAppMsgFrom($db_spool['app_msg_from']);
$spool->setAppMsgTo($db_spool['app_msg_to']);
$spool->setAppMsgBody($db_spool['app_msg_body']);
$spool->setAppMsgDate(date('Y-m-d H:i:s'));
$spool->setAppMsgCc($db_spool['app_msg_cc']);
$spool->setAppMsgBcc($db_spool['app_msg_bcc']);
$spool->setappMsgAttach($db_spool['app_msg_attach']);
$spool->setAppMsgTemplate($db_spool['app_msg_template']);
$spool->setAppMsgStatus($db_spool['app_msg_status']);
if(!$spool->validate()) {
$errors = $spool->getValidationFailures();
$this->status = 'error';
foreach($errors as $key => $value) {
echo "Validation error - " . $value->getMessage($key) . "\n";
}
}
else {
//echo "Saving - validation ok\n";
$this->status = 'success';
$spool->save();
}
return $sUID;
}
} // end of class
?>

View File

@@ -0,0 +1,175 @@
<?php
/**
* class.javaBridgePM.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.
*
*/
if ( ! defined ( 'JAVA_BRIDGE_PATH') ) define ( 'JAVA_BRIDGE_PATH', 'JavaBridgePM' );
if ( ! defined ( 'JAVA_BRIDGE_PORT') ) define ( 'JAVA_BRIDGE_PORT', '8080' );
if ( ! defined ( 'JAVA_BRIDGE_HOST') ) define ( 'JAVA_BRIDGE_HOST', '127.0.0.1' );
class JavaBridgePM
{
var $JavaBridgeDir = JAVA_BRIDGE_PATH;
var $JavaBridgePort = JAVA_BRIDGE_PORT;
var $JavaBridgeHost = JAVA_BRIDGE_HOST;
/**
* checkJavaExtension
* check if the java extension was loaded.
*
* @return true or false
*/
function checkJavaExtension()
{
try {
if (!extension_loaded('java')) {
if (!(@include_once("java/Java.inc"))) {
$urlJavaInc = "http://$this->JavaBridgeHost:$this->JavaBridgePort/$this->JavaBridgeDir/java/Java.inc";
@include_once( $urlJavaInc);
$includedFiles = get_included_files();
$found = false;
foreach ($includedFiles as $filename) {
if ( $urlJavaInc == $filename ) $found = true;
}
if ( !$found ) {
throw new Exception ('The PHP/Java Bridge is not defined' ) ;
}
}
return true;
}
if ( !function_exists("java_get_server_name")) {
throw new Exception ('The loaded java extension is not the PHP/Java Bridge' );
}
return true;
}
catch ( Exception $e ) {
throw new Exception ( 'Error in checkJavaExtension: ' . $e->getMessage() );
}
}
/**
* convert a php value to a java one...
* @param string $value
* @param string $className
* @returns boolean success
*/
function convertValue($value, $className)
{
// if we are a string, just use the normal conversion
// methods from the java extension...
try {
if ($className == 'java.lang.String') {
$temp = new Java('java.lang.String', $value);
return $temp;
}
else if ($className == 'java.lang.Boolean' ||
$className == 'java.lang.Integer' ||
$className == 'java.lang.Long' ||
$className == 'java.lang.Short' ||
$className == 'java.lang.Double' ||
$className == 'java.math.BigDecimal') {
$temp = new Java($className, $value);
return $temp;
}
else if ($className == 'java.sql.Timestamp' ||
$className == 'java.sql.Time') {
$temp = new Java($className);
$javaObject = $temp->valueOf($value);
return $javaObject;
}
}
catch (Exception $err) {
echo ( 'unable to convert value, ' . $value .
' could not be converted to ' . $className);
return false;
}
echo ( 'unable to convert value, class name '.$className.
' not recognised');
return false;
}
/**
* generateJrxmlFromDynaform
* @param string $outDocUid
* @param string $dynaformUid
* @param object $template
* @return void
*/
function generateJrxmlFromDynaform ( $outDocUid, $dynaformUid, $template ) {
require_once 'classes/model/Dynaform.php';
$dyn = new Dynaform();
$aFields = $dyn->load( $dynaformUid);
$xmlFields = $dyn->getDynaformFields( $dynaformUid);
$reportTpl = PATH_TPL . 'javaBridgePM/classic.xml';
$reportFilename = PATH_DYNAFORM . $aFields['PRO_UID'] . PATH_SEP . $outDocUid .'.jrxml';
foreach ( $xmlFields as $key => $val ) {
if ( $val->type == 'submit' || $val->type == 'button' || $val->type == 'title' || $val->type == 'subtitle' )
unset ( $xmlFields[$key] );
}
//$sqlSentence = 'SELECT * from ' . $tableName;
$sqlSentence = 'dynaform/';
$template = new TemplatePower( $reportTpl );
$template->prepare();
$template->assign ( 'sqlSentence', $sqlSentence );
$template->assign ( 'tableName', $aFields['DYN_TITLE'] );
$template->assign ( 'heightDetail', count ($xmlFields)*15 + 20 );
$template->assign ( 'PAGE_NUMBER' , '{PAGE_NUMBER}' );
$logoReporte = 'http://' .$_SERVER['SERVER_NAME'] . ':' .$_SERVER['SERVER_PORT'] .
'/images/processmaker.logo.jpg';
$template->assign ( 'logoReporte', $logoReporte );
foreach ( $xmlFields as $key => $val ) {
$template->newBlock( 'fields');
$template->assign ( 'fieldName' , $key );
}
$posX = 140;
$posLabelX = 5;
$posY = 10;
foreach ( $xmlFields as $key => $val ) {
$template->newBlock( 'detailFields');
$template->assign ( 'fieldName' , '{' . $key . '}' );
$template->assign ( 'fieldLabel' , $key );
$template->assign ( 'labelPosX' , $posLabelX );
$template->assign ( 'fieldPosX' , $posX );
$template->assign ( 'fieldPosY' , $posY );
$posY += 15;
}
$content = $template->getOutputContent();
$iSize = file_put_contents ( $reportFilename, $content );
printf("saved %s bytes in file %s \n", $iSize, $reportFilename );
}
}

View File

@@ -0,0 +1,221 @@
<?php
/**
* class.jrml.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.
*
*/
/**
* Jrml - Jrml class
* @package ProcessMaker
* @author Maborak <maborak@maborak.com>
* @copyright 2008 COLOSA
*/
class Jrml
{
public $rows;
public $sql;
private $data;
/**
* This function is the constructor of the class Jrml
* @param array $data
* @return void
*/
function __construct($data=array())
{
$this->data = $data;
$this->sql = $data['sql'];
$this->rows = $this->get_rows($data['type']);
$this->md = $this->get_md();
}
/**
* This function is for get rows
* @param array $a
* @return array
*/
private function get_rows($a)
{
$b=array();
foreach ($a as $key=>$value){
$b[]=$key;
}
return $b;
}
public function get_md()
{
}
/**
* This function is for get the header
* @return string
*/
public function get_header()
{
$xml="<queryString><![CDATA[{$this->sql}]]></queryString>";
foreach ($this->data['type'] as $key=>$value)
{
$xml.="<field name='{$key}' class='{$value}'><fieldDescription><![CDATA[]]></fieldDescription></field>";
}
$xml.="<background><band/></background>";
$xml.='
<title>
<band height="58">
<line>
<reportElement x="0" y="8" width="555" height="1"/>
</line>
<line>
<reportElement positionType="FixRelativeToBottom" x="0" y="51" width="555" height="1"/>
</line>
<staticText>
<reportElement x="65" y="13" width="424" height="35"/>
<textElement textAlignment="Center">
<font size="26" isBold="true"/>
</textElement>
<text><![CDATA['.$this->data['title'].']]></text>
</staticText>
</band>
</title>
<pageHeader>
<band/>
</pageHeader>';
return $xml;
}
/**
* This function is for get a column of the header
* @return string
*/
public function get_column_header()
{
$xml="<columnHeader><band height='18'>";
$w = (int)($this->data['columnWidth']/sizeof($this->rows));
$i=0;
foreach ($this->data['type'] as $key=>$value)
{
$xml.="<staticText><reportElement mode='Opaque' x='{$i}' y='0' width='{$w}' height='18' forecolor='#FFFFFF' backcolor='#999999'/>
<textElement>
<font size='12'/>
</textElement>
<text><![CDATA[{$key}]]></text>
</staticText>";
$i=$i+$w;
}
$xml.=" </band></columnHeader>";
return $xml;
}
/**
* This function is for get the detail
* @return string
*/
public function get_detail()
{
$xml='<detail><band height="20">';
$w = (int)($this->data['columnWidth']/sizeof($this->rows));
$i=0;
foreach ($this->data['type'] as $key=>$value)
{
$xml.="<textField hyperlinkType='None'><reportElement x='{$i}' y='0' width='{$w}' height='20'/><textElement><font size='12'/></textElement><textFieldExpression class='{$value}'><![CDATA[\$F{{$key}}]]></textFieldExpression></textField>";
$i=$i+$w;
}
$xml.='</band></detail>';
return $xml;
}
/**
* This function is for get the footer
* @return string
*/
public function get_footer()
{
$xml='<columnFooter>
<band/>
</columnFooter>
<pageFooter>
<band height="26">
<textField evaluationTime="Report" pattern="" isBlankWhenNull="false" hyperlinkType="None">
<reportElement key="textField" x="516" y="6" width="36" height="19" forecolor="#000000" backcolor="#FFFFFF"/>
<box>
<topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
</box>
<textElement>
<font size="10"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA["" + $V{PAGE_NUMBER}]]></textFieldExpression>
</textField>
<textField pattern="" isBlankWhenNull="false" hyperlinkType="None">
<reportElement key="textField" x="342" y="6" width="170" height="19" forecolor="#000000" backcolor="#FFFFFF"/>
<box>
<topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
</box>
<textElement textAlignment="Right">
<font size="10"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA["Page " + $V{PAGE_NUMBER} + " of "]]></textFieldExpression>
</textField>
<textField pattern="" isBlankWhenNull="false" hyperlinkType="None">
<reportElement key="textField" x="1" y="6" width="209" height="19" forecolor="#000000" backcolor="#FFFFFF"/>
<box>
<topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
</box>
<textElement>
<font size="10"/>
</textElement>
<textFieldExpression class="java.util.Date"><![CDATA[new Date()]]></textFieldExpression>
</textField>
</band>
</pageFooter>
<summary>
<band/>
</summary>';
return $xml;
}
/**
* This function is for export
* @return string
*/
public function export()
{
$xml='<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="'.$this->data['name'].'" pageWidth="'.$this->data['pageWidth'].'" pageHeight="842" columnWidth="'.$this->data['columnWidth'].'" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">';
$xml.=$this->get_header();
$xml.=$this->get_column_header();
$xml.=$this->get_detail();
$xml.=$this->get_footer();
$xml.='</jasperReport>';
return $xml;
}
}

View File

@@ -0,0 +1,350 @@
<?php
/**
* class.languages.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.
*
*/
require_once 'classes/model/Content.php';
require_once 'classes/model/Language.php';
require_once 'classes/model/IsoCountry.php';
require_once 'classes/model/Translation.php';
G::LoadClass('xmlDb');
/**
* languages - Languages class
* @package ProcessMaker
*/
class languages {
/*
* Log
* @param text $text
* @return void
*/
function log ( $text )
{
$logFile = PATH_DATA . 'log' . PATH_SEP . 'query.log';
$fp = fopen ( $logFile, 'a+' );
fwrite ( $fp, date("Y-m-d H:i:s") . " " . $text . "\n" );
fclose ( $fp );
}
/*
* Import a language file
* @param string $sLanguageFile
* @param string $bXml
* @return void
*/
public function importLanguage2($sLanguageFile, $bXml = true)
{
try {
$this->log ( $sLanguageFile );
$oFile = fopen($sLanguageFile, 'r');
$bFind = false;
while (!$bFind && ($sLine = fgets($oFile))) {
if (strpos($sLine, '"X-Poedit-Language:') !== false) {
$aAux = explode(':', $sLine);
$sAux = trim(str_replace('\n"', '', $aAux[1]));
}
if (strpos($sLine, '#') !== false) {
$bFind = true;
}
}
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(LanguagePeer::LAN_ID);
$oCriteria->add(LanguagePeer::LAN_NAME, $sAux, Criteria::LIKE);
$oDataset = LanguagePeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
if ($aRow = $oDataset->getRow()) {
$sLanguageID = $aRow['LAN_ID'];
}
else {
throw new Exception('The .po file have a invalid language!');
}
if (!$bFind) {
throw new Exception('The .po file have a bad format!');
}
$oTranslation = new Translation();
$sAux = '';
while ($sLine = fgets($oFile)) {
if (strpos($sLine, '.xml') === false) {
$aAux = explode('/', str_replace('# ', '', $sLine));
if (!($sLine = fgets($oFile))) {
throw new Exception('The .po file have a bad format!');
}
if (!($sLine = fgets($oFile))) {
throw new Exception('The .po file have a bad format!');
}
if (!($sLine = fgets($oFile))) {
throw new Exception('The .po file have a bad format!');
}
$oTranslation->addTranslation($aAux[0], trim(str_replace(chr(10), '', $aAux[1])), $sLanguageID, substr(trim(str_replace(chr(10), '', $sLine)), 8, -1));
if (!($sLine = fgets($oFile))) {
throw new Exception('The .po file have a bad format!');
}
$sLine = fgets($oFile);
}
else {
$sXmlForm = trim(str_replace('# ', '', $sLine));
if (!($sLine = fgets($oFile))) {
throw new Exception('The .po file have a bad format!');
}
$aAux = explode(' - ', $sLine);
$sFieldName = trim(str_replace(chr(10), '', $aAux[1]));
if (!($sLine = fgets($oFile))) {
throw new Exception('The .po file have a bad format!');
}
if (!($sLine = fgets($oFile))) {
throw new Exception('The .po file have a bad format!');
}
if (file_exists(PATH_XMLFORM . $sXmlForm) && $bXml) {
if ($sAux == '') {
$sAux = $sXmlForm;
$oConnection = new DBConnection(PATH_XMLFORM . $sXmlForm, '', '', '', 'myxml');
$oSession = new DBSession($oConnection);
}
if ($sAux == $sXmlForm) {
if (count($aAux) == 2) {
$oDataset = $oSession->Execute('SELECT * FROM dynaForm WHERE XMLNODE_NAME = "' . $sFieldName . '"');
if ($oDataset->count() > 0) {
$oDataset2 = $oSession->Execute('SELECT * FROM dynaForm.' . $sFieldName . ' WHERE XMLNODE_NAME = "' . $sLanguageID . '"');
if ($oDataset2->count() == 0) {
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . ' (XMLNODE_NAME) VALUES ("' . $sLanguageID . '")');
}
$oSession->Execute('UPDATE dynaForm.' . $sFieldName . ' SET XMLNODE_VALUE = "' . str_replace("'", "\'", str_replace('"', '""', stripslashes(substr(trim(str_replace(chr(10), '', $sLine)), 8, -1)))) . '" WHERE XMLNODE_NAME = "' . $sLanguageID . '"');
}
else {
$oSession->Execute('INSERT INTO dynaForm (XMLNODE_NAME, XMLNODE_VALUE) VALUES ("' . $sFieldName . '", "")');
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . ' (XMLNODE_NAME, XMLNODE_VALUE) VALUES ("' . $sLanguageID . '", "' . str_replace("'", "\'", str_replace('"', '""', stripslashes(substr(trim(str_replace(chr(10), '', $sLine)), 8, -1)))) . '")');
}
$bDelete = true;
}
if (count($aAux) == 3) {
if ($bDelete) {
$oDataset = $oSession->Execute('SELECT * FROM dynaForm WHERE XMLNODE_NAME = "' . $sFieldName . '"');
if ($oDataset->count() > 0) {
$oDataset2 = $oSession->Execute('SELECT * FROM dynaForm.' . $sFieldName . ' WHERE XMLNODE_NAME = "' . $sLanguageID . '"');
if ($oDataset2->count() == 0) {
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . ' (XMLNODE_NAME) VALUES ("' . $sLanguageID . '")');
}
$oDataset = $oSession->Execute('SELECT * FROM dynaForm.' . $sFieldName . ' WHERE XMLNODE_NAME = "' . $sLanguageID . '"');
if ($oDataset->count() > 0) {
$oSession->Execute('DELETE FROM dynaForm.' . $sFieldName . '.' . $sLanguageID . ' WHERE 1');
}
else {
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . ' (XMLNODE_NAME, XMLNODE_VALUE) VALUES ("' . $sLanguageID . '", "")');
}
}
$bDelete = false;
}
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . '.' . $sLanguageID . ' (XMLNODE_NAME,XMLNODE_VALUE,name) VALUES ("option","' . str_replace("'", "\'", str_replace('"', '""', stripslashes(substr(trim(str_replace(chr(10), '', $sLine)), 8, -1)))) . '","' . trim(str_replace(chr(10), '', $aAux[2])) . '")');
}
}
else {
$oConnection = new DBConnection(PATH_XMLFORM . $sXmlForm, '', '', '', 'myxml');
$oSession = new DBSession($oConnection);
if (count($aAux) == 2) {
$oDataset = $oSession->Execute('SELECT * FROM dynaForm WHERE XMLNODE_NAME = "' . $sFieldName . '"');
if ($oDataset->count() > 0) {
$oDataset2 = $oSession->Execute('SELECT * FROM dynaForm.' . $sFieldName . ' WHERE XMLNODE_NAME = "' . $sLanguageID . '"');
if ($oDataset2->count() == 0) {
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . ' (XMLNODE_NAME) VALUES ("' . $sLanguageID . '")');
}
$oSession->Execute('UPDATE dynaForm.' . $sFieldName . ' SET XMLNODE_VALUE = "' . str_replace("'", "\'", str_replace('"', '""', stripslashes(substr(trim(str_replace(chr(10), '', $sLine)), 8, -1)))) . '" WHERE XMLNODE_NAME = "' . $sLanguageID . '"');
}
else {
$oSession->Execute('INSERT INTO dynaForm (XMLNODE_NAME, XMLNODE_VALUE) VALUES ("' . $sFieldName . '", "")');
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . ' (XMLNODE_NAME, XMLNODE_VALUE) VALUES ("' . $sLanguageID . '", "' . str_replace("'", "\'", str_replace('"', '""', stripslashes(substr(trim(str_replace(chr(10), '', $sLine)), 8, -1)))) . '")');
}
$bDelete = true;
}
if (count($aAux) == 3) {
if ($bDelete) {
$oDataset = $oSession->Execute('SELECT * FROM dynaForm WHERE XMLNODE_NAME = "' . $sFieldName . '"');
if ($oDataset->count() > 0) {
$oDataset2 = $oSession->Execute('SELECT * FROM dynaForm.' . $sFieldName . ' WHERE XMLNODE_NAME = "' . $sLanguageID . '"');
if ($oDataset2->count() == 0) {
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . ' (XMLNODE_NAME) VALUES ("' . $sLanguageID . '")');
}
$oDataset = $oSession->Execute('SELECT * FROM dynaForm.' . $sFieldName . ' WHERE XMLNODE_NAME = "' . $sLanguageID . '"');
if ($oDataset->count() > 0) {
$oSession->Execute('DELETE FROM dynaForm.' . $sFieldName . '.' . $sLanguageID . ' WHERE 1');
}
else {
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . ' (XMLNODE_NAME, XMLNODE_VALUE) VALUES ("' . $sLanguageID . '", "")');
}
}
$bDelete = false;
}
$oSession->Execute('INSERT INTO dynaForm.' . $sFieldName . '.' . $sLanguageID . ' (XMLNODE_NAME,XMLNODE_VALUE,name) VALUES ("option","' . str_replace("'", "\'", str_replace('"', '""', stripslashes(substr(trim(str_replace(chr(10), '', $sLine)), 8, -1)))) . '","' . trim(str_replace(chr(10), '', $aAux[2])) . '")');
}
$sAux = $sXmlForm;
}
}
if (!($sLine = fgets($oFile))) {
throw new Exception('The .po file have a bad format!');
}
$sLine = fgets($oFile);
}
}
fclose($oFile);
$oLanguage = new Language();
$oLanguage->update(array('LAN_ID' => $sLanguageID, 'LAN_ENABLED' => '1'));
if ($bXml) {
Translation::generateFileTranslation($sLanguageID);
}
$this->log ( "checking and updating CONTENT");
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(ContentPeer::CON_CATEGORY);
$oCriteria->addSelectColumn(ContentPeer::CON_ID);
$oCriteria->addSelectColumn(ContentPeer::CON_VALUE);
$oCriteria->add(ContentPeer::CON_LANG, 'en');
$oCriteria->add(ContentPeer::CON_VALUE, '', Criteria::NOT_EQUAL );
$oDataset = ContentPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$oContent = new Content();
while ($aRow = $oDataset->getRow()) {
$oContent->load($aRow['CON_CATEGORY'], '', $aRow['CON_ID'], $sLanguageID);
$oDataset->next();
}
}
catch (Exception $oError) {
throw($oError);
}
}
public function importLanguage($sLanguageFile, $updateXml = true)
{
try {
G::LoadSystem('i18n_po');
$POFile = new i18n_PO($sLanguageFile);
$POFile->readInit();
$POHeaders = $POFile->getHeaders();
/*getting the PO Language definition*/
$langName = $POHeaders['X-Poedit-Language'];
//find the lang id
$language = new Language();
$langRecord = $language->findByLanName($langName);
if( ! isset($langRecord['LAN_ID']) ) //if the language doesn't exist abort
throw new Exception('The .po file has a invalid X-Poedit-Language definition!');
$languageID = $langRecord['LAN_ID'];
/*getting the PO Language definition*/
$countryName = $POHeaders['X-Poedit-Country'];
if( $countryName != '.' ) {
$isoCountry = new IsoCountry();
$countryRecord = $isoCountry->findByIcName($countryName);
if( ! isset($countryRecord['IC_UID']) ) //if the language doesn't exist abort
throw new Exception('The .po file has a invalid X-Poedit-Country definition!');
$countryID = $countryRecord['IC_UID'];
//define locale
$LOCALE = "$languageID-$countryID";
} else {
$LOCALE = $languageID;
}
$oTranslation = new Translation();
$countItems = 0;
$countItemsSuccess = 0;
while( $rowTranslation = $POFile->getTranslation() ) {
$countItems++;
if ( ! isset($POFile->translatorComments[0]) || ! isset($POFile->translatorComments[1]) || ! isset($POFile->references[0]) ) {
throw new Exception('The .po file has not valid directives for Processmaker!');
}
$identifier = $POFile->translatorComments[0];
$context = $POFile->translatorComments[1];
$reference = $POFile->references[0];
if( $identifier == 'TRANSLATION') {
list($category, $id) = explode('/', $context);
$result = $oTranslation->addTranslation(
$category,
$id,
$LOCALE,
trim(str_replace(chr(10), '', $rowTranslation['msgstr']))
);
if( $result['codError'] == 0 )
$countItemsSuccess++;
} else if( $updateXml ){
$xmlForm = $context;
$codes = explode(' - ', $reference);
$fieldName = trim($codes[1]);
if( ! file_exists(PATH_XMLFORM . $xmlForm) ) {
continue;
}
G::LoadSystem('dynaformhandler');
$dynaform = new dynaFormHandler(PATH_XMLFORM . $xmlForm);
if( sizeof($codes) == 2 ) { //is a normal node
$dynaform->addChilds($fieldName, Array($LOCALE=>$rowTranslation['msgstr']));
} else if( sizeof($codes) == 3 ) { //is a node child for a language node
$name = trim($codes[2]);
$childNode = Array(
Array('name'=>'option', 'value'=>$rowTranslation['msgstr'], 'attributes'=>Array('name'=>$name))
);
$dynaform->addChilds($fieldName, Array($LOCALE=>NULL), $childNode);
}
$countItemsSuccess++;
}
}
$oLanguage = new Language();
$oLanguage->update(array('LAN_ID' => $languageID, 'LAN_ENABLED' => '1'));
Translation::generateFileTranslation($LOCALE);
Translation::addTranslationEnvironment($LOCALE, $POHeaders, $countItemsSuccess);
$this->log( "checking and updating CONTENT");
$content = new Content();
$content->regenerateContent($languageID);
//fill the results
$results = new stdClass();
$results->recordsCount = $countItems;
$results->recordsCountSuccess = $countItemsSuccess;
$results->lang = $languageID;
$results->headers = $POHeaders;
return $results;
}
catch (Exception $oError) {
throw($oError);
}
}
} // languages

View File

@@ -0,0 +1,505 @@
<?php
/*--------------------------------------------------
| net.class.php
| By Erik Amaru Ortiz
| CopyLeft (f) 2008
| Email: erik@colosa.com
+--------------------------------------------------
| Email bugs/suggestions to erik@colosa.com erik.260mb.com
+--------------------------------------------------
| This script has been created and released under
| the GNU GPL and is free to use and redistribute
| only if this copyright statement is not removed
+--------------------------------------------------*/
/**
* @LastModification 30/05/2008
*/
class NET
{
public $hostname;
public $ip;
private $db_user;
private $db_passwd;
private $db_sourcename;
private $db_port;
/*errors handle*/
public $error;
public $errno;
public $errstr;
/**
* This function is the constructor of the class net
* @param string $pHost
* @return void
*/
function __construct($pHost)
{
$this->errno = 0;
$this->errstr = "";
unset($this->db_user);
unset($this->db_passwd);
unset($this->db_sourcename);
#verifing valid param
if ($pHost == "") {
$this->errno = 1000;
$this->errstr = "NET::You must specify a host";
//$this->showMsg();
}
$this->resolv($pHost);
}
/**
* This function puts a host
* @param string $pHost
* @return void
*/
function resolv($pHost)
{
if ($this->is_ipaddress($pHost)) {
$this->ip = $pHost;
if (!$this->hostname = @gethostbyaddr($pHost)) {
$this->errno = 2000;
$this->errstr = "NET::Host down";
$this->error = "Destination Host Unreachable";
}
} else {
$ip = @gethostbyname($pHost);
$long = ip2long($ip);
if ( $long == -1 || $long === FALSE) {
$this->errno = 2000;
$this->errstr = "NET::Host down";
$this->error = "Destination Host Unreachable";
} else {
$this->ip = @gethostbyname($pHost);
$this->hostname = $pHost;
}
}
}
/**
* This function resolves IP from Hostname returns hostname on failure
* @param string $pPort
* @return true
*/
function scannPort($pPort)
{
define('TIMEOUT', 5);
$hostip = @gethostbyname($host); // resloves IP from Hostname returns hostname on failure
// attempt to connect
if (@fsockopen($this->ip, $pPort, $this->errno, $this->errstr, TIMEOUT)) {
return true;
@fclose($x); //close connection (i dont know if this is needed or not).
} else {
$this->errno = 9999;
$this->errstr = "NET::Port Host Unreachable";
$this->error = "Destination Port Unreachable";
return false;
}
}
/**
* This function checks if it is a ip address
* @param string $pHost
* @return true
*/
function is_ipaddress($pHost)
{
$key = true;
#verifing if is a ip address
$tmp = explode(".", $pHost);
#if have a ip address format
if (count($tmp) == 4) {
#if a correct ip address
for ($i = 0; $i < count($tmp); $i++) {
if (!is_int($tmp[$i])) {
$key = false;
break;
}
}
} else {
$key = false;
}
return $key;
}
/**
* This function executes pin -w time IP
* @param string $pHost
* @return true
*/
function ping($pTTL = 3000)
{
$cmd = "ping -w $pTTL $this->ip";
$output = exec($cmd, $a, $a1);
$this->errstr = "";
for ($i = 0; $i < count($a); $i++)
$this->errstr += $a[$i];
$this->errno = $a1;
}
/**
* This function logins in db
* @param string $pUser
* @param string $pPasswd
* @return void
*/
function loginDbServer($pUser, $pPasswd)
{
$this->db_user = $pUser;
$this->db_passwd = $pPasswd;
}
/**
* This function sets db
* @param string $pDb
* @param string $pPort
* @return void
*/
function setDataBase($pDb, $pPort='')
{
$this->db_sourcename = $pDb;
$this->db_port = $pPort;
}
/**
* This function tries to connect to server
* @param string $pDbDriver
* @return void
*/
function tryConnectServer($pDbDriver)
{
if($this->errno != 0) {
return 0;
}
$stat = new Stat();
if(isset($this->db_user) && (isset($this->db_passwd) || ('' == $this->db_passwd)) && isset($this->db_sourcename))
{
switch($pDbDriver)
{
case 'mysql':
if ($this->db_passwd == '') {
$link = @mysql_connect($this->ip.(($this->db_port != '') && ($this->db_port != 0) ? ':'.$this->db_port : ''), $this->db_user);
} else {
$link = @mysql_connect($this->ip.(($this->db_port != '') && ($this->db_port != 0) ? ':'.$this->db_port : ''), $this->db_user, $this->db_passwd);
}
if ($link) {
if (@mysql_ping($link)) {
$stat->status = 'SUCCESS';
$this->errstr = "";
$this->errno = 0;
} else {
$this->error = "Lost MySql Connection";
$this->errstr = "NET::MYSQL->Lost Connection";
$this->errno = 10010;
}
} else {
$this->error = "MySql connection refused!";
$this->errstr = "NET::MYSQL->The connection was refused";
$this->errno = 10001;
}
break;
case 'pgsql':
$this->db_port = ($this->db_port == "") ? "5432" : $this->db_port;
$link = @pg_connect("host='$this->ip' port='$this->db_port' user='$this->db_user' password='$this->db_passwd' dbname='$this->db_sourcename'");
if ($link) {
$stat->status = 'SUCCESS';
$this->errstr = "";
$this->errno = 0;
} else {
$this->error = "PostgreSql connection refused!";
$this->errstr = "NET::POSTGRES->The connection was refused";
$this->errno = 20001;
}
break;
case 'mssql':
$str_port = (($this->db_port == "") || ($this->db_port == 0) || ($this->db_port == 1433)) ? "" : ":".$this->db_port;
$link = @mssql_connect($this->ip . $str_port, $this->db_user, $this->db_passwd);
if ($link) {
$stat->status = 'SUCCESS';
$this->errstr = "";
$this->errno = 0;
} else {
$this->error = "MS-SQL Server connection refused";
$this->errstr = "NET::MSSQL->The connection was refused";
$this->errno = 30001;
}
break;
case 'oracle':
$this->db_port = (($this->db_port == "") || ($this->db_port == 0)) ? "1521" : $this->db_port;
try{
$link = $conn = @oci_connect($this->db_user,$this->db_passwd, "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP) (HOST=$this->ip) (PORT=$this->db_port) )) (CONNECT_DATA=(SERVICE_NAME=$this->db_sourcename)))");
if ($link) {
$stat->status = 'SUCCESS';
$this->errstr = "";
$this->errno = 0;
} else {
$this->error = "Oracle connection refused";
$this->errstr = "NET::ORACLE->The connection was refused";
$this->errno = 30001;
}
} catch (Exception $e){
throw new Exception("[erik] Couldn't connect to Oracle Server! - ".$e->getMessage());
}
break;
case 'informix':
break;
case 'sqlite':
break;
}
} else {
throw new Exception("CLASS::NET::ERROR: No connections param.");
}
return $stat;
}
/**
* This function tries to open to the DB
* @param string $pDbDriver
* @return void
*/
function tryOpenDataBase($pDbDriver)
{
if($this->errno != 0) {
return 0;
}
set_time_limit(0);
$stat = new Stat();
if(isset($this->db_user) && (isset($this->db_passwd) || ('' == $this->db_passwd)) && isset($this->db_sourcename))
{
switch($pDbDriver)
{
case 'mysql':
$link = @mysql_connect($this->ip.(($this->db_port != '') && ($this->db_port != 0) ? ':'.$this->db_port : ''), $this->db_user, $this->db_passwd);
$db = @mysql_select_db($this->db_sourcename);
if ($link) {
if ($db) {
$result = @mysql_query("show tables;");
if ($result) {
$stat->status = 'SUCCESS';
$this->errstr = "";
$this->errno = 0;
@mysql_free_result($result);
} else {
$this->error = "the user $this->db_user doesn't have privileges to run queries!";
$this->errstr = "NET::MYSQL->Test query failed";
$this->errno = 10100;
}
} else {
$this->error = "The $this->db_sourcename data base does'n exist!";
$this->errstr = "NET::MYSQL->Select data base failed";
$this->errno = 10011;
}
} else {
$this->error = "MySql connection refused!";
$this->errstr = "NET::MYSQL->The connection was refused";
$this->errno = 10001;
}
break;
case 'pgsql':
$this->db_port = (($this->db_port == "") || ($this->db_port == 0)) ? "5432" : $this->db_port;
$link = @pg_connect("host='$this->ip' port='$this->db_port' user='$this->db_user' password='$this->db_passwd' dbname='$this->db_sourcename'");
if ($link) {
if (@pg_ping($link)) {
$stat->status = 'SUCCESS';
$this->errstr = "";
$this->errno = 0;
} else {
$this->error = "PostgreSql Connection to $this->ip is unreachable!";
$this->errstr = "NET::POSTGRES->Lost Connection";
$this->errno = 20010;
}
} else {
$this->error = "PostgrSql connection refused";
$this->errstr = "NET::POSTGRES->The connection was refused";
$this->errno = 20001;
}
break;
case 'mssql':
$str_port = (($this->db_port == "") || ($this->db_port == 0) || ($this->db_port == 1433)) ? "" : ":".$this->db_port;
$link = @mssql_connect($this->ip . $str_port, $this->db_user, $this->db_passwd);
if ($link) {
$db = @mssql_select_db($this->db_sourcename, $link);
if ($db) {
$stat->status = 'SUCCESS';
$this->errstr = "";
$this->errno = 0;
} else {
$this->error = "The $this->db_sourcename data base does'n exist!";
$this->errstr = "NET::MSSQL->Select data base failed";
$this->errno = 30010;
}
} else {
$this->error = "MS-SQL Server connection refused!";
$this->errstr = "NET::MSSQL->The connection was refused";
$this->errno = 30001;
}
break;
case 'oracle':
$this->db_port = (($this->db_port == "") || ($this->db_port == 0)) ? "1521" : $this->db_port;
$link = @oci_connect($this->db_user,$this->db_passwd, "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP) (HOST=$this->ip) (PORT=$this->db_port) )) (CONNECT_DATA=(SERVICE_NAME=$this->db_sourcename)))");
if ($link) {
$stid = @oci_parse($link, 'select AUTHENTICATION_TYPE from v$session_connect_info');
$result = @oci_execute($stid, OCI_DEFAULT);
if($result){
$stat->status = 'SUCCESS';
$this->errstr = "";
$this->errno = 0;
@oci_close($link);
} else {
$this->error = "the user $this->db_user don't has privileges to run queries!";
$this->errstr = "NET::ORACLE->Couldn't execute any query on this server!";
$this->errno = 40010;
}
} else {
$this->error = "Oracle connection refused!";
$this->errstr = "NET::ORACLE->The connection was refused";
$this->errno = 40001;
}
break;
case 'informix':
break;
case 'sqlite':
break;
}
} else {
throw new Exception("CLASS::NET::ERROR: No connections param.");
}
return $stat;
}
/**
* This function gets DB-s version
* @param string $driver
* @return void
*/
function getDbServerVersion($driver)
{
if(!isset($this->ip))
$this->ip = getenv('HTTP_CLIENT_IP');
if(isset($this->ip) && isset($this->db_user) && isset($this->db_passwd)) {
try{
switch($driver)
{
case 'mysql':
if($link = @mysql_connect($this->ip, $this->db_user, $this->db_passwd)){
$v = @mysql_get_server_info();
} else {
throw new Exception(@mysql_error($link));
}
break;
case 'pgsql':
$this->db_port = (($this->db_port == "") || ($this->db_port == 0)) ? "5432" : $this->db_port;
$link = @pg_connect("host='$this->ip' port='$this->db_port' user='$this->db_user' password='$this->db_passwd' dbname='$this->db_sourcename'");
if($link){
$v = @pg_version($link);
} else {
throw new Exception(@pg_last_error($link));
}
break;
}
return (isset($v))?$v:'none';
} catch (Exception $e){
throw new Exception($e->getMessage());
}
}
else{
throw new Exception('NET::Error->No params for Data Base Server!');
}
}
/**
* This function reurns DB name
* @param string $pAdapter
* @return void
*/
function dbName($pAdapter)
{
switch($pAdapter)
{
case 'mysql': return 'MySql'; break;
case 'pgsql': return 'PostgreSQL'; break;
case 'mssql': return 'Microsoft SQL Server'; break;
case 'oracle': return 'Oracle'; break;
case 'informix': return 'Informix'; break;
case 'sqlite': return 'SQLite'; break;
}
}
/**
* If there is an error then it shows
* @param string $pAdapter
* @return void
*/
function showMsg()
{
if ($this->errno != 0) {
$msg = "
<center>
<fieldset style='width:90%'><legend>Class NET</legend>
<div align=left>
<font color='red'>
<b>NET::ERROR NO -> $this->errno<br/>
NET::ERROR MSG -> $this->errstr</b>
</font>
</div>
</fieldset>
<center>";
print ($msg);
}
}
/**
* This function gets an error
* @param
* @return string
*/
function getErrno()
{
return $this->errno;
}
/**
* This function gets an error message
* @param
* @return string
*/
function getErrmsg()
{
return $this->errstr;
}
}
class Stat
{
public $stutus;
function __construct()
{
$this->status = false;
}
}
?>

View File

@@ -0,0 +1,266 @@
<?php
/**
* @brief Package spool files for sending
*
* @package Tomahawk_Mail
* @author Ian K Armstrong <ika@[REMOVE_THESE_CAPITALS]openmail.cc>
* @copyright Copyright (c) 2007, Ian K Armstrong
* @license http://www.opensource.org/licenses/gpl-3.0.html GNU Public License
* @link http://www.openmail.cc
*
* @category web_mail
* @subpackage mail
* @filesource
* @version
*
* @file class.package.php
*
*/
class package
{
private $headers;
private $message;
private $charset;
private $emailboundary;
private $debug;
private $fileData;
private $max_line_length;
private $with_html;
/**
* This function is the constructor of the package class
* @param array $fileData
* @return void
*/
function __construct($fileData=array())
{
$this->fileData = array();
$this->debug = 1;
$this->emailboundary = 'Part-'.md5(uniqid(microtime()));
$this->charset = 'UTF-8'; //'ISO-8859-1'
$this->headers = '';
$this->message = '';
$this->with_html = false;
$this->max_line_length = '70';
if(count($fileData)>0) {
$this->fileData = $fileData;
$this->addHeaders();
$this->compileBody();
}
}
/**
* This function returns the header
* @param
* @return string
*/
public function returnHeader()
{
return $this->headers;
}
/**
* This function returns the body
* @param
* @return string
*/
public function returnBody()
{
return $this->message;
}
/**
* This function returns an error
* @param string $error
* @return string
*/
private function returnErrors($error)
{
if($this->debug>0) return $error;
}
/**
* This function puts a headers (to, cc, etc)
* @param
* @return void
*/
private function addHeaders()
{
$header = '';
(strlen($this->fileData['from_name'])>0)
? $header .= 'From: '."{$this->fileData['from_name']}".' <'."{$this->fileData['from_email']}>"."\r\n"
: $header .= 'From: '."<{$this->fileData['from_email']}>"."\r\n";
// to
if(strlen($this->fileData['to'])>0)
{
$to = "{$this->fileData['to']}";
$header .= 'To: '.$to."\r\n";
}
// cc
if(strlen($this->fileData['cc'])>0)
{
$cc = "{$this->fileData['cc']}";
$header .= 'Cc: '.$cc."\r\n";
}
$header .= 'X-Sender: '."{$this->fileData['from_email']}"."\r\n";
$header .= 'Return-Path: <'."{$this->fileData['from_email']}".'>'."\r\n";
$header .= 'Errors-To: '."{$this->fileData['from_email']}"."\r\n";
$header .= 'Reply-To: '."{$this->fileData['from_email']}"."\r\n";
if(!empty($this->fileData['reference']))
{
$header .= 'In-Reply-To: <'."{$this->fileData['reference']}".'>'."\r\n";
$header .= 'References: <'."{$this->fileData['reference']}".'>'."\r\n";
}
$header .= 'Message-Id: <'.md5(uniqid(rand())).':'
.str_replace(' ','_', "{$this->fileData['from_name']}")
.'@'."{$this->fileData['domain']}".'>'."\r\n";
$header .= 'X-Mailer: ProcessMaker <http://www.processmaker.com>'."\r\n";
$header .= 'X-Priority: 3'."\r\n";
$header .= 'Date: '."{$this->fileData['date']}"."\r\n";
$header .= 'Subject: '."{$this->fileData['subject']}"."\r\n";
$header .= 'MIME-Version: 1.0'."\r\n";
(count($this->fileData['attachments'])>0)
? $header .= 'Content-Type: multipart/mixed; '."\r\n\t".'boundary="'.$this->emailboundary.'"'."\r\n"
: $header .= 'Content-Type: multipart/alternative; '."\r\n\t".'boundary="'.$this->emailboundary.'"'."\r\n";
$header .= 'This is a multi-part message in MIME format'."\r\n";
$this->headers = $header;
}
/**
* This function adds a file (to, cc, etc)
* @param string $data
* @return string
*/
private function addAttachment($data='')
{
$attach_this = '';
if(trim($data)!='')
{
list($file,$name,$type) = explode('|',$data);
if(is_readable($file))
{
// attachment header
$attachment_header = '--'.$this->emailboundary."\r\n";
$attachment_header .= 'Content-type: '.$type.'; name="'.$name.'"'."\r\n";
$attachment_header .= 'Content-transfer-encoding: base64'."\r\n";
$attachment_header .= 'Content-disposition: attachment; filename="'.$name.'"'."\r\n\r\n";
// read, encode, chunk split
$file_content = file_get_contents($file);
$file_content = base64_encode($file_content);
$file_content = chunk_split($file_content,70);
// add content and header
$attach_this = $attachment_header.$file_content."\r\n";
} else { $this->returnErrors($file.' not readable in addAttachment');}
} else { $this->returnErrors('missing data in addAttachment');}
return $attach_this;
}
/**
* This function fixs body
* @param string $data
* @return string
*/
private function fixbody()
{
$lines = array();
$b = '';
$body = "{$this->fileData['body']}";
$body = str_replace("\r", "\n", str_replace("\r\n", "\n", $body));
$lines = explode("\n", $body);
foreach($lines as $line)
{
// wrap lines
$line = wordwrap($line, $this->max_line_length, "\r\n");
// leading dot problem
if(substr($line, 0,1) == '.') $line = '.' . $line;
$b .= $line."\r\n";
}
return $b;
}
/**
* This function compiles message
* @param
* @return void
*/
private function compileBody()
{
$comp = '';
$body = $this->fixbody();
// text
$comp .= '--'.$this->emailboundary."\r\n";
$comp .= 'Content-Type: text/plain; charset='.$this->charset."\r\n";
$comp .= 'Content-Transfer-Encoding: 8bit'."\r\n\r\n";
$comp .= "$body"."\r\n\r\n";
// html
if($this->with_html)
{
$temp = file_get_contents('template.html');
$temp = str_replace("\n", "", str_replace("\r", "", $temp));
$comp .= '--'.$this->emailboundary."\r\n";
$comp .= 'Content-Type: text/html; charset='.$this->charset."\r\n";
$comp .= 'Content-Transfer-Encoding: 8bit'."\r\n\r\n";
$body = str_replace('[>content<]',"$body",$temp);
$comp .= "$body"."\r\n\r\n";
}
// attachments
/*
if(count($this->fileData['attachments'])>0)
{
foreach($this->fileData['attachments'] as $data)
{
$comp .= $this->addAttachment($data);
}
}*/
$comp .= '--'.$this->emailboundary.'--'."\r\n";
$this->message = $comp;
}
} // end of class
?>

View File

@@ -0,0 +1,519 @@
<?php
/**
* class.plugin.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.
*
*/
require_once ( 'class.pluginRegistry.php');
define ( 'G_PLUGIN_CLASS', 1 );
define ( 'PM_CREATE_CASE', 1001 );
define ( 'PM_UPLOAD_DOCUMENT', 1002 );
define ( 'PM_CASE_DOCUMENT_LIST',1003 );
define ( 'PM_BROWSE_CASE', 1004 );
define ( 'PM_NEW_PROCESS_LIST', 1005 );
define ( 'PM_NEW_PROCESS_SAVE', 1006 );
define ( 'PM_NEW_DYNAFORM_LIST', 1007 );
define ( 'PM_NEW_DYNAFORM_SAVE', 1008 );
define ( 'PM_EXTERNAL_STEP', 1009 );
define ( 'PM_CASE_DOCUMENT_LIST_ARR', 1010 );
define ( 'PM_LOGIN', 1011 );
define ( 'PM_UPLOAD_DOCUMENT_BEFORE', 1012 );
class menuDetail {
var $sNamespace;
var $sMenuId;
var $sFilename;
/**
* This function is the constructor of the menuDetail class
* @param string $sNamespace
* @param string $sMenuId
* @param string $sFilename
* @return void
*/
function __construct( $sNamespace, $sMenuId, $sFilename ) {
$this->sNamespace = $sNamespace;
$this->sMenuId = $sMenuId;
$this->sFilename = $sFilename;
}
}
class toolbarDetail {
var $sNamespace;
var $sToolbarId;
var $sFilename;
/**
* This function is the constructor of the menuDetail class
* @param string $sNamespace
* @param string $sMenuId
* @param string $sFilename
* @return void
*/
function __construct( $sNamespace, $sToolbarId, $sFilename ) {
$this->sNamespace = $sNamespace;
$this->sToolbarId = $sToolbarId;
$this->sFilename = $sFilename;
}
}
class dashboardPage {
var $sNamespace;
var $sPage;
var $sName;
var $sIcon;
/**
* This function is the constructor of the dashboardPage class
* @param string $sNamespace
* @param string $sPage
* @return void
*/
function __construct( $sNamespace, $sPage, $sName, $sIcon ) {
$this->sNamespace = $sNamespace;
$this->sPage = $sPage;
$this->sName = $sName;
$this->sIcon = $sIcon;
}
}
class cssFile {
var $sNamespace;
var $sCssFile;
/**
* This function is the constructor of the dashboardPage class
* @param string $sNamespace
* @param string $sPage
* @return void
*/
function __construct( $sNamespace, $sCssFile) {
$this->sNamespace = $sNamespace;
$this->sCssFile = $sCssFile;
}
}
class triggerDetail {
var $sNamespace;
var $sTriggerId;
var $sTriggerName;
/**
* This function is the constructor of the triggerDetail class
* @param string $sNamespace
* @param string $sTriggerId
* @param string $sTriggerName
* @return void
*/
function __construct( $sNamespace, $sTriggerId, $sTriggerName ) {
$this->sNamespace = $sNamespace;
$this->sTriggerId = $sTriggerId;
$this->sTriggerName = $sTriggerName;
}
}
class folderDetail {
var $sNamespace;
var $sFolderId;
var $sFolderName;
/**
* This function is the constructor of the folderDetail class
* @param string $sNamespace
* @param string $sFolderId
* @param string $sFolderName
* @return void
*/
function __construct( $sNamespace, $sFolderId, $sFolderName ) {
$this->sNamespace = $sNamespace;
$this->sFolderId = $sFolderId;
$this->sFolderName = $sFolderName;
}
}
class stepDetail {
var $sNamespace;
var $sStepId;
var $sStepName;
var $sStepTitle;
var $sSetupStepPage;
/**
* This function is the constructor of the stepDetail class
* @param string $sNamespace
* @param string $sStepId
* @param string $sStepName
* @param string $sStepTitle
* @param string $sSetupStepPage
* @return void
*/
function __construct( $sNamespace, $sStepId, $sStepName, $sStepTitle, $sSetupStepPage ) {
$this->sNamespace = $sNamespace;
$this->sStepId = $sStepId;
$this->sStepName = $sStepName;
$this->sStepTitle = $sStepTitle;
$this->sSetupStepPage = $sSetupStepPage;
}
}
class redirectDetail {
var $sNamespace;
var $sRoleCode;
var $sPathMethod;
/**
* This function is the constructor of the redirectDetail class
* @param string $sNamespace
* @param string $sRoleCode
* @param string $sPathMethod
* @return void
*/
function __construct( $sNamespace, $sRoleCode, $sPathMethod ) {
$this->sNamespace = $sNamespace;
$this->sRoleCode = $sRoleCode;
$this->sPathMethod = $sPathMethod;
}
}
class folderData {
var $sProcessUid;
var $sProcessTitle;
var $sApplicationUid;
var $sApplicationTitle;
var $sUserUid;
var $sUserLogin;
var $sUserFullName;
/**
* This function is the constructor of the folderData class
* @param string $sProcessUid
* @param string $sProcessTitle
* @param string $sApplicationUid
* @param string $sApplicationTitle
* @param string $sUserUid
* @param string $sUserLogin
* @param string $sUserFullName
* @return void
*/
function __construct( $sProcessUid, $sProcessTitle, $sApplicationUid, $sApplicationTitle, $sUserUid, $sUserLogin = '', $sUserFullName ='') {
$this->sProcessUid = $sProcessUid;
$this->sProcessTitle = $sProcessTitle;
$this->sApplicationUid = $sApplicationUid;
$this->sApplicationTitle = $sApplicationTitle;
$this->sUserUid = $sUserUid;
$this->sUserLogin = $sUserLogin;
$this->sUserFullName = $sUserFullName;
}
}
class uploadDocumentData {
var $sApplicationUid;
var $sUserUid;
var $sFilename;
var $sFileTitle;
var $sDocumentUid;
var $bUseOutputFolder;
var $iVersion;
/**
* This function is the constructor of the uploadDocumentData class
* @param string $sApplicationUid
* @param string $sUserUid
* @param string $sFilename
* @param string $sFileTitle
* @param string $sDocumentUid
* @param integer $iVersion
* @return void
*/
function __construct( $sApplicationUid, $sUserUid, $sFilename, $sFileTitle, $sDocumentUid, $iVersion = 1 ) {
$this->sApplicationUid = $sApplicationUid;
$this->sUserUid = $sUserUid;
$this->sFilename = $sFilename;
$this->sFileTitle = $sFileTitle;
$this->sDocumentUid = $sDocumentUid;
$this->bUseOutputFolder = false;
$this->iVersion = $iVersion;
}
}
class loginInfo {
var $lName;
var $lPassword;
var $lSession;
/**
* This function is the constructor of the loginInfo class
* @param string $lName
* @param string $lPassword
* @param string $lSession
* @return void
*/
function __construct( $lName, $lPassword, $lSession ) {
$this->lName = $lName;
$this->lPassword = $lPassword;
$this->lSession = $lSession;
}
}
class caseSchedulerPlugin {
var $sNamespace;
var $sActionId;
var $sActionForm;
var $sActionSave;
var $sActionExecute;
var $sActionGetFields;
/**
* This function is the constructor of the caseSchedulerPlugin class
* @param string $sNamespace
* @param string $sActionId
* @param string $sActionForm
* @param string $sActionSave
* @param string $sActionExecute
* $param string $sActionGetFields
* @return void
*/
function __construct( $sNamespace, $sActionId, $sActionForm, $sActionSave, $sActionExecute, $sActionGetFields ) {
$this->sNamespace = $sNamespace;
$this->sActionId = $sActionId;
$this->sActionForm = $sActionForm;
$this->sActionSave = $sActionSave;
$this->sActionExecute = $sActionExecute;
$this->sActionGetFields = $sActionGetFields;
}
}
class PMPlugin {
var $sNamespace;
var $sClassName;
var $sFilename = null;
var $iVersion = 0;
var $sFriendlyName = null;
var $sPluginFolder = '';
var $aWorkspaces = null;
var $bPrivate = false;
/**
* This function sets values to the plugin
* @param string $sNamespace
* @param string $sFilename
* @return void
*/
function PMPlugin($sNamespace, $sFilename = null) {
$this->sNamespace = $sNamespace;
$this->sClassName = $sNamespace . 'Plugin';
$this->sPluginFolder = $sNamespace;
$this->sFilename = $sFilename;
}
/**
* With this function we can register the MENU
* @param string $menuId
* @param string $menuFilename
* @return void
*/
function registerMenu( $menuId, $menuFilename ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$sMenuFilename = PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $menuFilename;
$oPluginRegistry->registerMenu ( $this->sNamespace, $menuId, $sMenuFilename);
}
/**
* With this function we can register the dashboard
* @param
* @return void
*/
function registerDashboard( ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerDashboard ( $this->sNamespace);
}
/**
* With this function we can register the report
* @param
* @return void
*/
function registerReport( ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerReport ( $this->sNamespace);
}
/**
* With this function we can register the pm's function
* @param
* @return void
*/
function registerPmFunction( ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerPmFunction ( $this->sNamespace);
}
/**
* With this function we can set the company's logo
* @param
* @return void
*/
function setCompanyLogo( $filename ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->setCompanyLogo( $this->sNamespace, $filename);
}
/**
* With this function we can register the pm's function
* @param
* @return void
*/
function redirectLogin( $role, $pathMethod ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerRedirectLogin( $this->sNamespace, $role, $pathMethod );
}
/**
* Register a folder for methods
*
* @param unknown_type $sFolderName
*/
function registerFolder($sFolderId, $sFolderName ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerFolder( $this->sNamespace, $sFolderId, $sFolderName );
}
/**
* With this function we can register the steps
* @param
* @return void
*/
function registerStep($sStepId, $sStepName, $sStepTitle, $sSetupStepPage = '') {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerStep( $this->sNamespace, $sStepId, $sStepName, $sStepTitle, $sSetupStepPage );
}
/**
* With this function we can register the triggers
* @param string $sTriggerId
* @param string $sTriggerName
* @return void
*/
function registerTrigger( $sTriggerId, $sTriggerName ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerTrigger ( $this->sNamespace, $sTriggerId, $sTriggerName );
}
/**
* With this function we can delete a file
* @param string $sFilename
* @param string $bAbsolutePath
* @return void
*/
function delete($sFilename, $bAbsolutePath = false) {
if (!$bAbsolutePath) {
$sFilename = PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $sFilename;
}
@unlink($sFilename);
}
/**
* With this function we can copy a files
* @param string $sSouce
* @param string $sTarget
* @param string $bSourceAbsolutePath
* @param string $bTargetAbsolutePath
* @return void
*/
function copy($sSouce, $sTarget, $bSourceAbsolutePath = false, $bTargetAbsolutePath = false) {
if (!$bSourceAbsolutePath) {
$sSouce = PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $sSouce;
}
if (!$bTargetAbsolutePath) {
$sTarget = PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $sTarget;
}
G::verifyPath(dirname($sTarget), true);
@copy($sSouce, $sTarget);
}
/**
* With this function we can rename a files
* @param string $sSouce
* @param string $sTarget
* @param string $bSourceAbsolutePath
* @param string $bTargetAbsolutePath
* @return void
*/
function rename($sSouce, $sTarget, $bSourceAbsolutePath = false, $bTargetAbsolutePath = false) {
if (!$bSourceAbsolutePath) {
$sSouce = PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $sSouce;
}
if (!$bTargetAbsolutePath) {
$sTarget = PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $sTarget;
}
G::verifyPath(dirname($sTarget), true);
@chmod(dirname($sTarget), 0777);
@rename($sSouce, $sTarget);
}
/**
* This function registers a page who is break
* @param string $pageId
* @param string $templateFilename
* @return void
*/
function registerBreakPageTemplate( $pageId, $templateFilename ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$sPageFilename = PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $templateFilename;
$oPluginRegistry->registerBreakPageTemplate ( $this->sNamespace, $pageId, $sPageFilename);
}
/**
* With this function we can register a Dashboard Page for Cases Dashboard
* @param string $sPage
* @return void
*/
function registerDashboardPage( $sPage, $sName, $sIcon="") {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerDashboardPage ( $this->sNamespace, $sPage, $sName, $sIcon );
}
/**
* With this function we can register a Dashboard Page for Cases Dashboard
* @param string $sPage
* @return void
*/
function registerCss( $sCssFile) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerCss ( $this->sNamespace, $sCssFile );
}
/**
* With this function we can register the toolbar file for dynaform editor
* @param string $menuId
* @param string $menuFilename
* @return void
*/
function registerToolbarFile( $sToolbarId, $filename ) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$sFilename = PATH_PLUGINS . $this->sPluginFolder . PATH_SEP . $filename;
$oPluginRegistry->registerToolbarFile ( $this->sNamespace, $sToolbarId, $sFilename);
}
/**
* With this function we can register a Case Scheduler Plugin/Addon
* @param
* @return void
*/
function registerCaseSchedulerPlugin($sActionId, $sActionForm, $sActionSave, $sActionExecute, $sActionGetFields) {
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$oPluginRegistry->registerCaseSchedulerPlugin( $this->sNamespace, $sActionId, $sActionForm, $sActionSave, $sActionExecute, $sActionGetFields );
}
}

View File

@@ -0,0 +1,921 @@
<?php
/**
* class.pluginRegistry.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.
*
*/
class pluginDetail {
var $sNamespace;
var $sClassName;
var $sFriendlyName = null;
var $sDescription = null;
var $sSetupPage = null;
var $sFilename;
var $sPluginFolder = '';
var $sCompanyLogo = '';
var $iVersion = 0;
var $enabled = false;
var $aWorkspaces = null;
var $bPrivate = false;
/**
* This function is the constructor of the pluginDetail class
* @param string $sNamespace
* @param string $sClassName
* @param string $sFilename
* @param string $sFriendlyName
* @param string $sPluginFolder
* @param string $sDescription
* @param string $sSetupPage
* @param integer $iVersion
* @return void
*/
function __construct( $sNamespace, $sClassName, $sFilename, $sFriendlyName = '', $sPluginFolder ='', $sDescription ='', $sSetupPage ='', $iVersion = 0) {
$this->sNamespace = $sNamespace;
$this->sClassName = $sClassName;
$this->sFriendlyName = $sFriendlyName;
$this->sDescription = $sDescription;
$this->sSetupPage = $sSetupPage;
$this->iVersion = $iVersion;
$this->sFilename = $sFilename;
if ( $sPluginFolder == '')
$this->sPluginFolder = $sNamespace;
else
$this->sPluginFolder = $sPluginFolder ;
}
}
class PMPluginRegistry {
private $_aPluginDetails = array();
private $_aPlugins = array();
private $_aMenus = array();
private $_aFolders = array();
private $_aTriggers = array();
private $_aDashboards = array();
private $_aReports = array();
private $_aPmFunctions = array();
private $_aRedirectLogin = array();
private $_aSteps = array();
private $_aDashboardPages = array();
private $_aCSSStyleSheets = array();
private $_aToolbarFiles = array();
private $_aCaseSchedulerPlugin = array();
static private $instance = NULL;
/**
* This function is the constructor of the PMPluginRegistry class
* @param
* @return void
*/
private function __construct() {}
/**
* This function is instancing to this class
* @param
* @return object
*/
function &getSingleton() {
if (self::$instance == NULL) {
self::$instance = new PMPluginRegistry ();
}
return self::$instance;
}
/**
* This function generates a storable representation of a value
* @param
* @return void
*/
function serializeInstance() {
return serialize ( self::$instance);
}
/**
* This function takes a single serialized variable and converts it back a code
* @param string $serialized
* @return void
*/
function unSerializeInstance( $serialized ) {
if (self::$instance == NULL) {
self::$instance = new PMPluginRegistry ();
}
$instance = unserialize ( $serialized );
self::$instance = $instance;
}
//delete this function, it was here, only for test and debug purposes
function showArrays () {
krumo ( $this->_aPluginDetails);
krumo ( $this->_aPlugins);
krumo ( $this->_aMenus);
krumo ( $this->_aFolders);
krumo ( $this->_aTriggers);
krumo ( $this->_aDashboards);
krumo ( $this->_aReports);
krumo ( $this->_aPmFunctions);
krumo ( $this->_aRedirectLogin);
krumo ( $this->_aSteps);
}
/**
* Register the plugin in the singleton
*
* @param unknown_type $sClassName
* @param unknown_type $sNamespace
* @param unknown_type $sFilename
*/
function registerPlugin( $sNamespace, $sFilename = null)
{
$sClassName = $sNamespace . 'plugin';
if ( isset( $this->_aPluginDetails[$sNamespace] ) )
return;
//require_once ( $sFilename );
$plugin = new $sClassName ($sNamespace, $sFilename);
$detail = new pluginDetail (
$sNamespace,
$sClassName,
$sFilename,
$plugin->sFriendlyName,
$plugin->sPluginFolder,
$plugin->sDescription,
$plugin->sSetupPage,
$plugin->iVersion );
if ( isset ($plugin->aWorkspaces) )
$detail->aWorkspaces = $plugin->aWorkspaces;
if ( isset ($plugin->bPrivate) )
$detail->bPrivate = $plugin->bPrivate;
$this->_aPluginDetails[$sNamespace] = $detail;
}
/**
* get the plugin details, by filename
*
* @param unknown_type $sFilename
*/
function getPluginDetails( $sFilename ) {
foreach ( $this->_aPluginDetails as $key => $row ) {
if ( $sFilename == baseName ( $row->sFilename ) )
return $row;
}
}
/**
* Enable the plugin in the singleton
*
* @param unknown_type $sNamespace
*/
function enablePlugin($sNamespace ) {
foreach ( $this->_aPluginDetails as $namespace=>$detail ) {
if ( $sNamespace == $namespace ) {
$this->registerFolder($sNamespace, $sNamespace, $detail->sPluginFolder ); //register the default directory, later we can have more
$this->_aPluginDetails[$sNamespace]->enabled = true;
$oPlugin =& new $detail->sClassName( $detail->sNamespace, $detail->sFilename );
$this->_aPlugins[$detail->sNamespace] =& $oPlugin;
if (method_exists($oPlugin, 'enable')) {
$oPlugin->enable();
}
}
}
}
/**
* disable the plugin in the singleton
*
* @param unknown_type $sNamespace
*/
function disablePlugin($sNamespace )
{
foreach ( $this->_aPluginDetails as $namespace=>$detail ) {
if ( $sNamespace == $namespace ) {
unset ($this->_aPluginDetails[$sNamespace]);
$oPlugin =& new $detail->sClassName( $detail->sNamespace, $detail->sFilename );
$this->_aPlugins[$detail->sNamespace] =& $oPlugin;
if (method_exists($oPlugin, 'disable')) {
$oPlugin->disable();
}
}
}
foreach ( $this->_aMenus as $key=>$detail ) {
if ( $detail->sNamespace == $sNamespace )
unset ( $this->_aMenus[ $key ] );
}
foreach ( $this->_aFolders as $key=>$detail ) {
if ( $detail->sNamespace == $sNamespace )
unset ( $this->_aFolders[ $key ] );
}
foreach ( $this->_aTriggers as $key=>$detail ) {
if ( $detail->sNamespace == $sNamespace )
unset ( $this->_aTriggers[ $key ] );
}
foreach ( $this->_aDashboards as $key=>$detail ) {
if ( $detail == $sNamespace )
unset ( $this->_aDashboards[ $key ] );
}
foreach ( $this->_aReports as $key=>$detail ) {
if ( $detail == $sNamespace )
unset ( $this->_aReports[ $key ] );
}
foreach ( $this->_aPmFunctions as $key=>$detail ) {
if ( $detail == $sNamespace )
unset ( $this->_aPmFunctions[ $key ] );
}
foreach ( $this->_aRedirectLogin as $key=>$detail ) {
if ( $detail->sNamespace == $sNamespace )
unset ( $this->_aRedirectLogin[ $key ] );
}
foreach ( $this->_aSteps as $key=>$detail ) {
if ( $detail->sNamespace == $sNamespace )
unset ( $this->_aSteps[ $key ] );
}
foreach ( $this->_aToolbarFiles as $key=>$detail ) {
if ( $detail->sNamespace == $sNamespace )
unset ( $this->_aToolbarFiles[ $key ] );
}
foreach ( $this->_aDashboardPages as $key=>$detail ) {
if ( $detail->sNamespace == $sNamespace )
unset ( $this->_aDashboardPages[ $key ] );
}
foreach ( $this->_aCSSStyleSheets as $key=>$detail ) {
if ( $detail->sNamespace == $sNamespace )
unset ( $this->_aCSSStyleSheets[ $key ] );
}
foreach ( $this->_aCaseSchedulerPlugin as $key=>$detail ) {
if ( $detail->sNamespace == $sNamespace )
unset ( $this->_aCaseSchedulerPlugin[ $key ] );
}
}
/**
* get status plugin in the singleton
*
* @param unknown_type $sNamespace
*/
function getStatusPlugin($sNamespace ) {
foreach ( $this->_aPluginDetails as $namespace=>$detail ) {
if ( $sNamespace == $namespace )
if ( $this->_aPluginDetails[$sNamespace]->enabled )
return 'enabled';
else
return 'disabled';
}
return 0;
}
/**
* install the plugin
*
* @param unknown_type $sNamespace
*/
function installPlugin($sNamespace ) {
try {
foreach ( $this->_aPluginDetails as $namespace=>$detail ) {
if ( $sNamespace == $namespace ) {
$oPlugin =& new $detail->sClassName( $detail->sNamespace, $detail->sFilename );
$this->_aPlugins[$detail->sNamespace] =& $oPlugin;
$oPlugin->install();
}
}
}
catch ( Exception $e ) {
global $G_PUBLISH;
$aMessage['MESSAGE'] = $e->getMessage();
$G_PUBLISH = new Publisher;
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'login/showMessage', '', $aMessage );
G::RenderPage( 'publish' );
die;
}
}
/**
* Register a menu in the singleton
*
* @param unknown_type $sNamespace
* @param unknown_type $sMenuId
* @param unknown_type $sFilename
*/
function registerMenu($sNamespace, $sMenuId, $sFilename ) {
$found = false;
foreach ( $this->_aMenus as $row=>$detail ) {
if ( $sMenuId == $detail->sMenuId && $sNamespace == $detail->sNamespace )
$found = true;
}
if ( !$found ) {
$menuDetail = new menuDetail ($sNamespace, $sMenuId, $sFilename);
$this->_aMenus[] = $menuDetail;
}
}
/**
* Register a dashboard class in the singleton
*
* @param unknown_type $sNamespace
* @param unknown_type $sMenuId
* @param unknown_type $sFilename
*/
function registerDashboard($sNamespace ) {
$found = false;
foreach ( $this->_aDashboards as $row=>$detail ) {
if ( $sNamespace == $detail )
$found = true;
}
if ( !$found ) {
$this->_aDashboards[] = $sNamespace;
}
}
/**
* Register a dashboard page for cases in the singleton
*
* @param unknown_type $sNamespace
* @param unknown_type $sPage
*/
function registerDashboardPage($sNamespace, $sPage, $sName, $sIcon ) {
$found = false;
foreach ( $this->_aDashboardPages as $row=>$detail ) {
if ( $sPage == $detail->sPage && $sNamespace == $detail->sNamespace ){
$detail->sName=$sName;
$detail->sIcon=$sIcon;
$found = true;
}
}
if ( !$found ) {
$dashboardPage = new dashboardPage ($sNamespace, $sPage, $sName, $sIcon);
$this->_aDashboardPages[] = $dashboardPage;
}
}
/**
* return all dashboard pages
*
* @return array
*/
function getDashboardPages() {
return $this->_aDashboardPages;
}
/**
* Register a stylesheet in the singleton
*
* @param unknown_type $sNamespace
* @param unknown_type $sPage
*/
function registerCss($sNamespace, $sCssFile ) {
$found = false;
foreach ( $this->_aCSSStyleSheets as $row=>$detail ) {
if ( $sCssFile == $detail->sCssFile && $sNamespace == $detail->sNamespace ){
$detail->sCssFile=$sCssFile;
$found = true;
}
}
if ( !$found ) {
$cssFile = new cssFile ($sNamespace, $sCssFile);
$this->_aCSSStyleSheets[] = $cssFile;
}
}
/**
* return all dashboard pages
*
* @return array
*/
function getRegisteredCss() {
return $this->_aCSSStyleSheets;
}
/**
* Register a reports class in the singleton
*
* @param unknown_type $sNamespace
* @param unknown_type $sMenuId
* @param unknown_type $sFilename
*/
function registerReport($sNamespace ) {
$found = false;
foreach ( $this->_aReports as $row=>$detail ) {
if ( $sNamespace == $detail )
$found = true;
}
if ( !$found ) {
$this->_aReports[] = $sNamespace;
}
}
/**
* Register a PmFunction class in the singleton
*
* @param unknown_type $sNamespace
* @param unknown_type $sMenuId
* @param unknown_type $sFilename
*/
function registerPmFunction($sNamespace ) {
$found = false;
foreach ( $this->_aPmFunctions as $row=>$detail ) {
if ( $sNamespace == $detail )
$found = true;
}
if ( !$found ) {
$this->_aPmFunctions[] = $sNamespace;
}
}
/**
* Register a redirectLogin class in the singleton
*
* @param unknown_type $sNamespace
* @param unknown_type $sRole
* @param unknown_type $sPath
*/
function registerRedirectLogin($sNamespace, $sRole, $sPathMethod ) {
$found = false;
foreach ( $this->_aRedirectLogin as $row=>$detail ) {
if (( $sNamespace == $detail->sNamespace )&&( $sRole == $detail->sRoleCode )) //Filters based on Workspace and Role Code
$found = true;
}
if ( !$found ) {
$this->_aRedirectLogin[] = new redirectDetail ( $sNamespace, $sRole, $sPathMethod);
}
}
/**
* Register a folder for methods
*
* @param unknown_type $sFolderName
*/
function registerFolder($sNamespace, $sFolderId, $sFolderName ) {
$found = false;
foreach ( $this->_aFolders as $row=>$detail )
if ( $sFolderId == $detail->sFolderId && $sNamespace == $detail->sNamespace )
$found = true;
if ( !$found ) {
$this->_aFolders[] = new folderDetail ( $sNamespace, $sFolderId, $sFolderName);
}
}
/**
* Register a step for process
*
* @param unknown_type $sFolderName
*/
function registerStep($sNamespace, $sStepId, $sStepName, $sStepTitle, $setupStepPage = '') {
$found = false;
foreach ( $this->_aSteps as $row=>$detail )
if ( $sStepId == $detail->sStepId && $sNamespace == $detail->sNamespace )
$found = true;
if ( !$found ) {
$this->_aSteps[] = new stepDetail ( $sNamespace, $sStepId, $sStepName, $sStepTitle, $setupStepPage);
}
}
/**
* return true if the $sFolderName is registered in the singleton
*
* @param unknown_type $sFolderName
*/
function isRegisteredFolder( $sFolderName ) {
foreach ( $this->_aFolders as $row => $folder ) {
if ( $sFolderName == $folder->sFolderName && is_dir ( PATH_PLUGINS . $folder->sFolderName )){
return true;
}elseif( $sFolderName == $folder->sFolderName && is_dir ( PATH_PLUGINS .$folder->sNamespace.PATH_SEP. $folder->sFolderName )){
return $folder->sNamespace;
}
}
return false;
}
/**
* return all menus related to a menuId
*
* @param unknown_type $menuId
*/
function getMenus( $menuId ) {
foreach ( $this->_aMenus as $row=>$detail ) {
if ( $menuId == $detail->sMenuId && file_exists ( $detail->sFilename ) ) {
include ( $detail->sFilename );
}
}
}
/**
* return all dashboards registered
* @return array
*/
function getDashboards( ) {
return $this->_aDashboards;
$dash = array ();
foreach ( $this->_aDashboards as $row=>$detail ) {
$sClassName = str_replace ( 'plugin', 'class', $this->_aPluginDetails[ $detail ]->sClassName);
$dash[] = $sClassName;
}
return $dash;
}
/**
* this function returns all reports registered
* @return array
*/
function getReports( ) {
return $this->_aReports;
$report = array ();
foreach ( $this->_aReports as $row=>$detail ) {
$sClassName = str_replace ( 'plugin', 'class', $this->_aPluginDetails[ $detail ]->sClassName);
$report[] = $sClassName;
}
return $report;
}
/**
* This function returns all dashboards registered
* @ array
*/
function getPmFunctions( ) {
return $this->_aPmFunctions;
$dash = array ();
foreach ( $this->_aPmFunctions as $row=>$detail ) {
$sClassName = str_replace ( 'plugin', 'class', $this->_aPluginDetails[ $detail ]->sClassName);
$dash[] = $sClassName;
}
return $dash;
}
/**
* This function returns all steps registered
*
* @return string
*/
function getSteps( ) {
return $this->_aSteps;
}
/**
* This function returns all redirect registered
* @return string
*/
function getRedirectLogins( ) {
return $this->_aRedirectLogin;
}
/**
* execute all triggers related to a triggerId
*
* @param unknown_type $menuId
* @return object
*/
function executeTriggers( $triggerId, $oData )
{
foreach ( $this->_aTriggers as $row=>$detail ) {
if ( $triggerId == $detail->sTriggerId ) {
//review all folders registered for this namespace
$found = false;
$classFile = '';
foreach ( $this->_aFolders as $row=>$folder ) {
$fname = PATH_PLUGINS . $folder->sFolderName . PATH_SEP . 'class.' . $folder->sFolderName .'.php';
if ( $detail->sNamespace == $folder->sNamespace && file_exists ( $fname ) ) {
$found = true;
$classFile = $fname;
}
}
if ( $found ) {
require_once ( $classFile );
$sClassName = substr($this->_aPluginDetails[ $detail->sNamespace ]->sClassName,0,1) . str_replace ( 'plugin', 'class', substr($this->_aPluginDetails[ $detail->sNamespace ]->sClassName,1));
$obj = new $sClassName( );
$methodName = $detail->sTriggerName;
$response = $obj->{$methodName}( $oData );
if (PEAR::isError($response) ) {
print $response->getMessage(); return;
}
return $response;
}
else
print "error in call method " . $detail->sTriggerName;
}
}
}
/**
* verify if exists triggers related to a triggerId
*
* @param unknown_type $triggerId
*/
function existsTrigger( $triggerId) {
$found = false;
foreach ( $this->_aTriggers as $row=>$detail ) {
if ( $triggerId == $detail->sTriggerId ) {
//review all folders registered for this namespace
foreach ( $this->_aFolders as $row=>$folder ) {
$fname = PATH_PLUGINS . $folder->sFolderName . PATH_SEP . 'class.' . $folder->sFolderName .'.php';
if ( $detail->sNamespace == $folder->sNamespace && file_exists ( $fname ) ) {
$found = true;
}
}
}
}
return $found;
}
/**
* Return info related to a triggerId
*
* @param unknown_type $triggerId
* @return object
*/
function getTriggerInfo( $triggerId) {
$found = null;
foreach ( $this->_aTriggers as $row=>$detail ) {
if ( $triggerId == $detail->sTriggerId ) {
//review all folders registered for this namespace
foreach ( $this->_aFolders as $row=>$folder ) {
$fname = PATH_PLUGINS . $folder->sFolderName . PATH_SEP . 'class.' . $folder->sFolderName .'.php';
if ( $detail->sNamespace == $folder->sNamespace && file_exists ( $fname ) ) {
$found = $detail;
}
}
}
}
return $found;
}
/**
* Register a trigger in the Singleton
*
* @param unknown_type $sTriggerId
* @param unknown_type $sMethodFunction
* @return void
*/
function registerTrigger($sNamespace, $sTriggerId, $sTriggerName ) {
$found = false;
foreach ( $this->_aTriggers as $row=>$detail ) {
if ( $sTriggerId == $detail->sTriggerId && $sNamespace == $detail->sNamespace )
$found = true;
}
if ( !$found ) {
$triggerDetail = new triggerDetail ($sNamespace, $sTriggerId, $sTriggerName);
$this->_aTriggers[] = $triggerDetail;
}
}
/**
* get plugin
*
* @param unknown_type $sNamespace
* @return void
*/
function &getPlugin($sNamespace) {
if (array_key_exists($sNamespace, $this->_aPlugins)) {
return $this->_aPlugins[$sNamespace];
}
/*
$aDetails = KTUtil::arrayGet($this->_aPluginDetails, $sNamespace);
if (empty($aDetails)) {
return null;
}
$sFilename = $aDetails[2];
if (!empty($sFilename)) {
require_once($sFilename);
}
$sClassName = $aDetails[0];
$oPlugin =& new $sClassName($sFilename);
$this->_aPlugins[$sNamespace] =& $oPlugin;
return $oPlugin;
*/
}
/**
* set company logo
*
* @param unknown_type $sNamespace
* @param unknown_type $filename
* @return void
*/
function setCompanyLogo( $sNamespace, $filename ) {
$found = false;
foreach ( $this->_aPluginDetails as $row=>$detail ) {
if ( $sNamespace == $detail->sNamespace )
$this->_aPluginDetails[ $sNamespace ]->sCompanyLogo = $filename;
}
}
/**
* get company logo
*
* @param unknown_type $default
* @return void
*/
function getCompanyLogo( $default ) {
$sCompanyLogo = $default;
foreach ( $this->_aPluginDetails as $row=>$detail ) {
if ( trim($detail->sCompanyLogo) != '' )
$sCompanyLogo = $detail->sCompanyLogo;
}
return $sCompanyLogo;
}
/**
* get setup Plugins
*
* @param unknown_type $default
* @return void
*/
function setupPlugins() {
try {
$iPlugins = 0;
G::LoadClass ( 'serverConfiguration' );
$oServerConf = & serverConf::getSingleton ();
$oServerConf->addPlugin ( SYS_SYS,$this->_aPluginDetails );
foreach ( $this->_aPluginDetails as $namespace=>$detail ) {
if ( isset($detail->enabled ) && $detail->enabled ) {
if ( !empty( $detail->sFilename) && file_exists ($detail->sFilename) ) {
if (strpos($detail->sFilename, PATH_SEP) !== false) {
$aux = explode ( PATH_SEP, $detail->sFilename );
}
else {
$aux = explode ( chr(92), $detail->sFilename );
}
$sFilename = PATH_PLUGINS . $aux[ count($aux) -1];
if (! file_exists($sFilename) ) continue;
require_once( $sFilename);
$oPlugin =& new $detail->sClassName( $detail->sNamespace, $detail->sFilename );
$this->_aPlugins[$detail->sNamespace] =& $oPlugin;
$iPlugins++;
//print ( "$iPlugins $namespace <br>");
$oPlugin->setup();
}
}
}
$this->eevalidate();
return $iPlugins;
}
catch ( Exception $e ) {
global $G_PUBLISH;
$aMessage['MESSAGE'] = $e->getMessage();
$G_PUBLISH = new Publisher;
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'login/showMessage', '', $aMessage );
G::RenderPage( 'publish' );
die;
}
}
/**
* this function execute a Method
*
* @param string $sNamespace
* @param string $methodName
* @param object $oData
* @return object
*/
function executeMethod( $sNamespace, $methodName, $oData ) {
$response = null;
try {
$details = $this->_aPluginDetails[$sNamespace];
$pluginFolder = $details->sPluginFolder;
$className = $details->sClassName;
$classFile = PATH_PLUGINS . $pluginFolder . PATH_SEP . 'class.' . $pluginFolder .'.php';
if ( file_exists ( $classFile ) ) {
require_once ( $classFile );
$sClassName=substr_replace($className,"class",-6,6);
//$sClassName = str_replace ( 'plugin', 'class', $className );
$obj = new $sClassName( );
if ( !in_array ( $methodName, get_class_methods ($obj) ) ) {
throw ( new Exception ( "The method '$methodName' doesn't exist in class '$sClassName' ") );
}
$obj->sNamespace = $details->sNamespace;
$obj->sClassName = $details->sClassName;
$obj->sFilename = $details->sFilename;
$obj->iVersion = $details->iVersion;
$obj->sFriendlyName = $details->sFriendlyName;
$obj->sPluginFolder = $details->sPluginFolder;
$response = $obj->{$methodName}( $oData );
}
return $response;
}
catch ( Exception $e ) {
throw ($e);
}
}
/**
* this function gets Fields For Page on Setup
*
* @param string $sNamespace
* @return object
*/
function getFieldsForPageSetup( $sNamespace ) {
$oData = NULL;
return $this->executeMethod ( $sNamespace, 'getFieldsForPageSetup', $oData);
}
/**
* this function updates Fields For Page on Setup
*
* @param string $sNamespace
* @return void
*/
function updateFieldsForPageSetup( $sNamespace, $oData ) {
if ( !isset ($this->_aPluginDetails[$sNamespace] ) ) {
throw ( new Exception ( "The namespace '$sNamespace' doesn't exist in plugins folder." ) );
};
return $this->executeMethod ( $sNamespace, 'updateFieldsForPageSetup', $oData);
}
function eevalidate(){
$fileL = PATH_DATA_SITE.'license.dat';
$fileS = PATH_DATA.'license.dat';
if((file_exists($fileL))||(file_exists($fileS))){//Found a License
if(class_exists('pmLicenseManager')){
$sSerializedFile = PATH_DATA_SITE . 'lmn.singleton';
$pmLicenseManagerO =& pmLicenseManager::getSingleton();
if ( file_exists ($sSerializedFile) ){
$pmLicenseManagerO->unSerializeInstance( file_get_contents ( $sSerializedFile ) );
}
}
}
}
/**
* Register a toolbar for dynaform editor in the singleton
*
* @param unknown_type $sNamespace
* @param unknown_type $sToolbarId
* @param unknown_type $sFilename
*/
function registerToolbarFile($sNamespace, $sToolbarId, $sFilename ) {
$found = false;
foreach ( $this->_aToolbarFiles as $row=>$detail ) {
if ( $sToolbarId == $detail->sToolbarId && $sNamespace == $detail->sNamespace )
$found = true;
}
if ( !$found ) {
$toolbarDetail = new toolbarDetail ($sNamespace, $sToolbarId, $sFilename);
$this->_aToolbarFiles[] = $toolbarDetail;
}
}
/**
* return all toolbar files related to a sToolbarId
*
* @param unknown_type $sToolbarId (NORMAL, GRID)
*/
function getToolbarOptions( $sToolbarId ) {
foreach ( $this->_aToolbarFiles as $row=>$detail ) {
if ( $sToolbarId == $detail->sToolbarId && file_exists ( $detail->sFilename ) ) {
include ( $detail->sFilename );
}
}
}
/**
* Register a Case Scheduler Plugin
*
*/
function registerCaseSchedulerPlugin($sNamespace, $sActionId, $sActionForm, $sActionSave, $sActionExecute, $sActionGetFields) {
$found = false;
foreach ( $this->_aCaseSchedulerPlugin as $row=>$detail )
if ( $sActionId == $detail->sActionId && $sNamespace == $detail->sNamespace )
$found = true;
if ( !$found ) {
$this->_aCaseSchedulerPlugin[] = new caseSchedulerPlugin ( $sNamespace, $sActionId, $sActionForm, $sActionSave, $sActionExecute, $sActionGetFields);
}
}
/**
* This function returns all Case Scheduler Plugins registered
*
* @return string
*/
function getCaseSchedulerPlugins( ) {
return $this->_aCaseSchedulerPlugin;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,632 @@
<?php
/**
* class.pmScript.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.
*
*/
////////////////////////////////////////////////////
// Execute and evaluate PMScripts
//
// Copyright (C) 2007 COLOSA
//
// License: LGPL, see LICENSE
////////////////////////////////////////////////////
/**
* PMScript - PMScript class
* @package ProcessMaker
* @author Julio Cesar Laura Avenda<64>o <juliocesar@colosa.com>
* @last modify 2008.08.13 by Erik Amaru Ortiz <erik@colosa.com>
* @last modify comment was added and adapted the catch errors
* @copyright 2007 COLOSA
*/
function __autoload($sClassName)
{
if (defined('SYS_SYS')) {
$sPath = PATH_DB . SYS_SYS . PATH_SEP . 'classes' . PATH_SEP;
if (file_exists($sPath . $sClassName . '.php')) {
require_once $sPath . $sClassName . '.php';
}
}
}
//Start - Custom functions
G::LoadClass('pmFunctions');
//End - Custom functions
//call plugin
if (class_exists('folderData')) {
//$folderData = new folderData($sProUid, $proFields['PRO_TITLE'], $sAppUid, $Fields['APP_TITLE'], $sUsrUid);
$oPluginRegistry = &PMPluginRegistry::getSingleton();
$aAvailablePmFunctions = $oPluginRegistry->getPmFunctions();
foreach ($aAvailablePmFunctions as $key => $class ) {
$filePlugin = PATH_PLUGINS . $class . PATH_SEP . 'classes' . PATH_SEP . 'class.pmFunctions.php';
if ( file_exists ( $filePlugin ) )
include_once( $filePlugin);
}
}
//end plugin
//Add External Triggers
$dir=G::ExpandPath( "classes" ).'triggers';
$filesArray=array();
if (file_exists($dir)){
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if(($file!=".")&&($file!="..")){
$extFile =explode(".",$file);
if($extFile[sizeof($extFile)-1] == 'php')
include_once( $dir.PATH_SEP.$file);
}
}
closedir($handle);
}
}
/**
* PMScript - PMScript class
* @copyright 2007 COLOSA
*/
class PMScript
{
/**
* Original fields
*/
var $aOriginalFields = array();
/**
* Fields to use
*/
var $aFields = array();
/**
* Script
*/
var $sScript = '';
/**
* Error has happened?
*/
var $bError = false;
/**
* Affected fields
*/
var $affected_fields;
/**
* Constructor of the class PMScript
* @return void
*/
function PMScript()
{
$this->aFields['__ERROR__'] = 'none';
}
/**
* Set the fields to use
* @param array $aFields
* @return void
*/
function setFields($aFields = array())
{
if (!is_array($aFields)) {
$aFields = array();
}
$this->aOriginalFields = $this->aFields = $aFields;
}
/**
* Set the current script
* @param string $sScript
* @return void
*/
function setScript($sScript = '')
{
$this->sScript = $sScript;
}
/**
* Verify the syntax
* @param string $sScript
* @return boolean
*/
function validSyntax($sScript)
{
return true;
}
function executeAndCatchErrors($sScript, $sCode) {
ob_start('handleFatalErrors');
set_error_handler('handleErrors');
$_SESSION['_CODE_'] = $sCode;
eval($sScript);
unset($_SESSION['_CODE_']);
ob_end_flush();
}
/**
* Execute the current script
* @return void
*/
function execute()
{
$sScript = "";
$iAux = 0;
$bEqual = false;
$iOcurrences = preg_match_all('/\@(?:([\@\%\#\?\$\=])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*(?:[\\\\][\w\W])?)*)\))((?:\s*\[[\'"]?\w+[\'"]?\])+)?/', $this->sScript, $aMatch, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
if ($iOcurrences){
for($i = 0; $i < $iOcurrences; $i++){
$sAux = substr($this->sScript, $iAux, $aMatch[0][$i][1] - $iAux);
if (!$bEqual){
if (strpos($sAux, '==') !== false){
$bEqual = false;
}
else {
if (strpos($sAux, '=') !== false){
$bEqual = true;
}
}
}
if ($bEqual){
if (strpos($sAux, ';') !== false){
$bEqual = false;
}
}
if ($bEqual) {
if (!isset($aMatch[5][$i][0])) {
eval("if (!isset(\$this->aFields['" . $aMatch[2][$i][0] . "'])) { \$this->aFields['" . $aMatch[2][$i][0] . "'] = null; }");
}
else {
eval("if (!isset(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")) { \$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . " = null; }");
}
}
$sScript .= $sAux;
$iAux = $aMatch[0][$i][1] + strlen($aMatch[0][$i][0]);
switch ($aMatch[1][$i][0])
{ case '@':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmToString(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmToString(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '%':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmToInteger(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmToInteger(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '#':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmToFloat(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmToFloat(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '?':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmToUrl(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmToUrl(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '$':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmSqlEscape(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmSqlEscape(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '=':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
}
$this->affected_fields[] = $aMatch[2][$i][0];
}
}
$sScript .= substr($this->sScript, $iAux);
$sScript = "try {\n" . $sScript . "\n} catch (Exception \$oException) {\n \$this->aFields['__ERROR__'] = utf8_encode(\$oException->getMessage());\n}";
//echo '<pre>-->'; print_r($this->aFields); echo '<---</pre>';
$this->executeAndCatchErrors($sScript, $this->sScript);
for($i=0; $i<count($this->affected_fields); $i++){
$_SESSION['TRIGGER_DEBUG']['DATA'][] = Array(
'key' => $this->affected_fields[$i],
'value' => isset($this->aFields[$this->affected_fields[$i]]) ? $this->aFields[$this->affected_fields[$i]] : ''
);
}
//echo '<pre>-->'; print_r($_SESSION['TRIGGER_DEBUG']['DATA']); echo '<---</pre>';
}
/**
* Evaluate the current script
* @return void
*/
function evaluate()
{
$bResult = null;
$sScript = '';
$iAux = 0;
$bEqual = false;
$variableIsDefined = true;
$iOcurrences = preg_match_all('/\@(?:([\@\%\#\?\$\=])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*(?:[\\\\][\w\W])?)*)\))((?:\s*\[[\'"]?\w+[\'"]?\])+)?/', $this->sScript, $aMatch, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
if ($iOcurrences){
for($i = 0; $i < $iOcurrences; $i++){
// if the variables for that condition has not been previously defined then $variableIsDefined is set to false
if (!isset($this->aFields[$aMatch[2][$i][0]])){
// $variableIsDefined = false;
$this->aFields[$aMatch[2][$i][0]] = '';
}
$sAux = substr($this->sScript, $iAux, $aMatch[0][$i][1] - $iAux);
if (!$bEqual){
if (strpos($sAux, '=') !== false){
$bEqual = true;
}
}
if ($bEqual){
if (strpos($sAux, ';') !== false)
{
$bEqual = false;
}
}
$sScript .= $sAux;
$iAux = $aMatch[0][$i][1] + strlen($aMatch[0][$i][0]);
switch ($aMatch[1][$i][0]){
case '@':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmToString(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmToString(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '%':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmToInteger(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmToInteger(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '#':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmToFloat(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmToFloat(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '?':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmToUrl(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmToUrl(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '$':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "pmSqlEscape(\$this->aFields['" . $aMatch[2][$i][0] . "'])";
}
else {
$sScript .= "pmSqlEscape(\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0] . ")";
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
case '=':
if ($bEqual){
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
else{
if (!isset($aMatch[5][$i][0])) {
$sScript .= "\$this->aFields['" . $aMatch[2][$i][0] . "']";
}
else {
$sScript .= "\$this->aFields" . (isset($aMatch[2][$i][0]) ? "['" . $aMatch[2][$i][0] . "']" : '') . $aMatch[5][$i][0];
}
}
break;
}
}
}
$sScript .= substr($this->sScript, $iAux);
$sScript = '$bResult = ' . $sScript . ';';
// checks if the syntax is valid or if the variables in that condition has been previously defined
if ($this->validSyntax($sScript)&&$variableIsDefined){
$this->bError = false;
eval($sScript);
}
else{
// echo "<script> alert('".G::loadTranslation('MSG_CONDITION_NOT_DEFINED')."'); </script>";
G::SendTemporalMessage('MSG_CONDITION_NOT_DEFINED', 'error', 'labels');
$this->bError = true;
}
return $bResult;
}
}
//Start - Private functions
/**
* Convert to string
* @param variant $vValue
* @return string
*/
function pmToString($vValue)
{
return (string)$vValue;
}
/**
* Convert to integer
* @param variant $vValue
* @return integer
*/
function pmToInteger($vValue)
{
return (int)$vValue;
}
/**
* Convert to float
* @param variant $vValue
* @return float
*/
function pmToFloat($vValue)
{
return (float)$vValue;
}
/**
* Convert to Url
* @param variant $vValue
* @return url
*/
function pmToUrl($vValue)
{
return urlencode($vValue);
}
/**
* Convert to data base escaped string
* @param variant $vValue
* @return string
*/
function pmSqlEscape($vValue)
{
return G::sqlEscape($vValue);
}
//End - Private functions
/***************************************************************************
* Error handler
* @author: Julio Cesar Laura Avenda<64>o <juliocesar@colosa.com>
* @date: 2009-10-01
***************************************************************************/
/*
* Convert to data base escaped string
* @param string $errno
* @param string $errstr
* @param string $errfile
* @param string $errline
* @return void
*/
function handleErrors($errno, $errstr, $errfile, $errline)
{
if ($errno != '' && ($errno != 8) && ($errno != 2048)) {
if( isset($_SESSION['_CODE_']) ){
$sCode = $_SESSION['_CODE_'];
unset($_SESSION['_CODE_']);
registerError(1, $errstr, $errline - 1, $sCode);
}
}
}
/*
* Handle Fatal Errors
* @param variant $buffer
* @return buffer
*/
function handleFatalErrors($buffer)
{
if (ereg('(error</b>:)(.+)(<br)', $buffer, $regs)) {
$err = preg_replace('/<.*?>/', '', $regs[2]);
$aAux = explode(' in ', $err);
$sCode = $_SESSION['_CODE_'];
unset($_SESSION['_CODE_']);
registerError(2, $aAux[0], 0, $sCode);
if (strpos($_SERVER['REQUEST_URI'], '/cases/cases_Step') !== false) {
if (strpos($_SERVER['REQUEST_URI'], '&ACTION=GENERATE') !== false) {
G::LoadClass('case');
$oCase = new Cases();
$aNextStep = $oCase->getNextStep($_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['INDEX'], $_SESSION['STEP_POSITION']);
if($_SESSION['TRIGGER_DEBUG']['ISSET']) {
$_SESSION['TRIGGER_DEBUG']['TIME'] = 'AFTER';
$_SESSION['TRIGGER_DEBUG']['BREAKPAGE'] = $aNextStep['PAGE'];
$aNextStep['PAGE'] = $aNextStep['PAGE'].'&breakpoint=triggerdebug';
}
G::header('Location: ' . $aNextStep['PAGE']);
die;
}
$_SESSION['_NO_EXECUTE_TRIGGERS_'] = 1;
G::header('Location: ' . $_SERVER['REQUEST_URI']);
die;
}
else {
G::LoadClass('case');
$oCase = new Cases();
$aNextStep = $oCase->getNextStep($_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['INDEX'], $_SESSION['STEP_POSITION']);
if($_SESSION['TRIGGER_DEBUG']['ISSET']) {
$_SESSION['TRIGGER_DEBUG']['TIME'] = 'AFTER';
$_SESSION['TRIGGER_DEBUG']['BREAKPAGE'] = $aNextStep['PAGE'];
$aNextStep['PAGE'] = $aNextStep['PAGE'].'&breakpoint=triggerdebug';
}
if (strpos($aNextStep['PAGE'], 'TYPE=ASSIGN_TASK&UID=-1') !== false) {
G::SendMessageText('Fatal error in trigger', 'error');
}
G::header('Location: ' . $aNextStep['PAGE']);
die;
}
}
return $buffer;
}
/*
* Register Error
* @param string $iType
* @param string $sError
* @param string $iLine
* @param string $sCode
* @return void
*/
function registerError($iType, $sError, $iLine, $sCode)
{
$sType = ($iType == 1 ? 'ERROR' : 'FATAL');
$_SESSION['TRIGGER_DEBUG']['ERRORS'][][$sType] = $sError . ($iLine > 0 ? ' (line ' . $iLine . ')' : '') . ':<br /><br />' . $sCode;
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* class.popupMenu.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.
*
*/
/**
* popupMenu - popupMenu class
* @package ProcessMaker
* @copyright COLOSA
*/
class popupMenu extends form
{
var $type = 'popupMenu';
var $theme = 'processmaker';
/**
* Print the popup
* @param string $tableId
* @param array $tableFields
* @return array
*/
function renderPopup( $tableId, $tableFields )
{
$this->name =$tableId;
$fields = array_keys( $tableFields);
foreach( $fields as $f ) {
switch ( strtolower($tableFields[$f]['Type'])) {
case 'javascript':
case 'button':
case 'private':
case 'hidden':
case 'cellmark':
break;
default:
$label = ($tableFields[$f]['Label'] !='' ) ? $tableFields[$f]['Label'] : $f;
$label = str_replace("\n", ' ', $label);
$pmXmlNode = new Xml_Node( $f,
'complete',
'',
array ( 'label' => $label,
'type' => 'popupOption',
'launch' => $tableId . '.showHideField("' . $f . '")'
)
);
$this->fields[$f] = new XmlForm_Field_popupOption( $pmXmlNode );
$this->values[$f]='';
}
}
$scTemp = '';
$this->values['PAGED_TABLE_ID'] = $tableId;
print( parent::render( PATH_CORE . 'templates/popupMenu.html', $scTemp));
$sc = "<script type=\"text/javascript\">\n$scTemp\n loadPopupMenu_$tableId(); \n</script>" ;
return $sc;
}
}
/**
* XmlForm_Field_popupOption - XmlForm_Field_popupOption class
* @package ProcessMaker
* @copyright COLOSA
*/
class XmlForm_Field_popupOption extends XmlForm_Field
{
var $launch = '';
/**
* Get Events
* @return string
*/
function getEvents( )
{
$script = '{name:"' . $this->name . '",text:"' . addcslashes($this->label,'\\"') .
'", launch:leimnud.closure({Function:function(target){' . $this->launch . '}, args:target})}';
return $script;
}
}
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,783 @@
<?php
/**
* class.propelTable.php
*
* ProcessMaker Open Source Edition
* Copyright (C) 2004 - 2008 Colosa Inc.
*
* 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.
*
*/
G::LoadClass('filterForm');
G::LoadClass('xmlMenu');
G::LoadClass("BasePeer" );
G::LoadClass("ArrayPeer" );
/**
* Class pagedTable
* @author David S. Callizaya S. <davidsantos@colosa.com>
* @package gulliver.system
* @access public
* @dependencies TemplatePower Form XmlForm
*/
class propelTable
{
var $xmlFormFile;
var $currentPage;
var $orderBy = '';
var $filter = array();
var $filterType = array();
var $searchBy = '';
var $fastSearch='';
var $order = '';
var $template='templates/paged-table.html';
var $tpl;
var $style = array();
var $rowsPerPage=25;
var $ownerPage;
var $popupPage;
var $popupSubmit;
var $popupWidth=450;
var $popupHeight=200;
var $ajaxServer;
var $fields;
var $query;
var $totPages;
var $totRows;
//SQL QUERIES
var $criteria;
var $sql='';
var $sqlWhere='';
var $sqlGroupBy='';
var $sqlSelect='SELECT 1';
var $sqlDelete='';
var $sqlInsert='';
var $sqlUpdate='';
var $fieldDataList='';
//Configuration
var $xmlPopup='';
var $addRow=false;
var $deleteRow=false;
var $editRow=false;
var $notFields=' title button linknew begingrid2 endgrid2 '; // These are not considered to build the sql queries (update,insert,delete)
//JavaScript Object attributes
var $onUpdateField="";
var $onDeleteField="";
var $afterDeleteField="";
var $onInsertField="";
//New gulliver
var $xmlForm;
var $menu='';
var $filterForm='';
var $filterForm_Id='';
var $name='pagedTable';
var $id='A1';
var $disableFooter = false;
//This attribute is used to set STYLES to groups of TD, using the field type "cellMark" (see XmlForm_Field_cellMark)
var $tdStyle='';
var $tdClass='';
//Config Save definition
var $__Configuration='orderBy,filter,fastSearch,style/*/showInTable';//order,rowsPerPage,disableFooter';
//Variable for MasterDetail feature
var $masterdetail='';
var $title;
/**
* Function prepareQuery
* @author David S. Callizaya S. <davidsantos@colosa.com>
* @access public
* @param string $limitPage
* @return string
*/
function prepareQuery( $limitPage = false )
{
// process the QuickSearch string and add the fields and expression needed to run the search
if ( $this->searchBy !== '' ) {
$aSB = explode('|', $this->searchBy); //fields are separated by pipes
//subfilter
$subFilter='';
foreach($aSB as $sBy) {
$subFilter .= ($subFilter !== '') ? ' OR ' : '';
//TODO: Get DATABASE type from Criteria, I think sql delimeter is needed too
$subFilter .= $sBy . ' LIKE "%'.
G::sqlEscape($this->fastSearch ).'%"';
}
if ($subFilter !=='' ) {
//Get the first defined table in Criteria.
$aCurrentTables = $this->criteria->getTables();
if ( isset($aCurrentTables[0])) {
$this->criteria->add ( $aCurrentTables[0] . ".*", '('. $subFilter. ')' , Criteria::CUSTOM );
}
}
}
//Merge sort array defined by USER with the array defined by SQL
parse_str($this->order, $orderFields);
parse_str($this->orderBy, $orderFields2);
//User sort is more important (first in merge).
$orderFields3 = array_merge($orderFields2, $orderFields);
//User sort is overwrites XMLs definition.
$orderFields = array_merge($orderFields3, $orderFields2);
//Order (BY SQL DEFINITION AND USER'S DEFINITION)
$this->aOrder = array();
$order='';
foreach ($orderFields as $field => $fieldOrder) {
$field = G::getUIDName($field,'');
$fieldOrder = strtoupper($fieldOrder);
if ($fieldOrder==='A')
$fieldOrder = 'ASC';
if ($fieldOrder==='D')
$fieldOrder = 'DESC';
switch ( $fieldOrder ) {
case 'ASC':
case 'DESC':
if ( $order !== '' )
$order.=', ';
$order .= $field . ' '. $fieldOrder;
$this->aOrder[$field] = $fieldOrder;
}
}
//master detail :O
if(count($this->masterdetail) > 0){
$this->criteria->clearOrderByColumns();
foreach($this->masterdetail as $idMasterDetail => $fieldMasterDetail){
$this->criteria->addAscendingOrderByColumn( $fieldMasterDetail );
}
}
if (!empty($this->aOrder)) {
if(count($this->masterdetail) <= 0) {
$this->criteria->clearOrderByColumns();
}
foreach ($this->aOrder as $field => $ascending ) {
if ( $ascending == 'ASC' )
$this->criteria->addAscendingOrderByColumn ( $field );
else
$this->criteria->addDescendingOrderByColumn( $field );
}
}
/** Add limits */
$this->criteria->setLimit( 0 );
$this->criteria->setOffset( 0 );
if ( $this->criteria->getDbName() == 'dbarray' ) {
$this->totRows = ArrayBasePeer::doCount( $this->criteria );
}
else {
$this->totRows = GulliverBasePeer::doCount( $this->criteria );
}
$this->totPages = ceil( $this->totRows / $this->rowsPerPage);
if ( $limitPage ) {
$this->criteria->setLimit ( $this->rowsPerPage );
$this->criteria->setOffset( ($this->currentPage-1) * $this->rowsPerPage );
}
return;
}
/**
* Function setupFromXmlform
*
* @author David S. Callizaya S. <davidsantos@colosa.com>
* @editedby Hugo Loza <hugo@colosa.com>
* @access public
* @parameter string xmlForm
* @return string
*/
function setupFromXmlform($xmlForm)
{
$this->xmlForm = $xmlForm;
//Config
$this->name = $xmlForm->name;
$this->id = $xmlForm->id;
//$this->sqlConnection=((isset($this->xmlForm->sqlConnection))?$this->xmlForm->sqlConnection:'');
if ( isset($_GET['page']))
$this->currentPage = $_GET['page']; else $this->currentPage = 1;
if ( isset($_GET['order']))
$this->orderBy = urldecode($_GET['order']); else $this->orderBy = "";
if ( isset($_GET['filter']))
$this->filter = urldecode($_GET['filter']); else $this->filter = "";
if ($xmlForm->ajaxServer != '') {
$this->ajaxServer = G::encryptLink( $xmlForm->ajaxServer );
}
else {
$this->ajaxServer = G::encryptLink( '../gulliver/propelTableAjax' );
}
$this->ownerPage = G::encryptLink( SYS_CURRENT_URI );
// Config attributes from XMLFORM file
$myAttributes = get_class_vars(get_class($this));
foreach ($this->xmlForm->xmlform->tree->attribute as $atrib => $value)
if (array_key_exists( $atrib, $myAttributes)) {
eval('settype($value, gettype($this->' . $atrib.'));');
if ($value !== '')
eval( '$this->' . $atrib . '=$value;');
}
if($this->masterdetail!=""){
$this->masterdetail=explode(",",$this->masterdetail);
foreach($this->masterdetail as $keyMasterDetail => $valueMasterDetail){
$this->masterdetail[$keyMasterDetail]=trim($valueMasterDetail);
}
}
else{
$this->masterdetail=array();
}
//Prepare the fields
$this->style=array();$this->gridWidth="";$this->gridFields="";
$this->fieldsType=array();
foreach ($this->xmlForm->fields as $f => $v) {
$r=$f;
$this->fields[$r]['Name'] =$this->xmlForm->fields[$f]->name;
$this->fields[$r]['Type'] =$this->xmlForm->fields[$f]->type;
if (isset($this->xmlForm->fields[$f]->size))
$this->fields[$r]['Size'] = $this->xmlForm->fields[$f]->size;
$this->fields[$r]['Label']=$this->xmlForm->fields[$f]->label;
}
//Set the default settings
$this->defaultStyle();
//continue with the setup
$this->gridWidth=''; $this->gridFields='';
foreach($this->xmlForm->fields as $f => $v){
$r=$f;
//Parse the column properties
foreach ($this->xmlForm->fields[$f] as $attribute => $value){
if (!is_object($value)) {
$this->style[$r][$attribute] = $value;
}
}
//Needed for javascript
//only the visible columns's width and name are stored
if ($this->style[$r]['showInTable']!='0'){
$this->gridWidth.=','.$this->style[$r]['colWidth'];
$this->gridFields.=',"form['.$this->fields[$r]['Name'].']"';
}
}
$totalWidth=0;
foreach($this->fields as $r => $rval)
if ($this->style[$r]['showInTable']!='0')
$totalWidth += $this->style[$r]['colWidth'];
$this->totalWidth = $totalWidth;
}
/**
* Function count
* @author David S. Callizaya S. <davidsantos@colosa.com>
* @access public
* @return string
*/
function count()
{
$this->prepareQuery();
return $this->totRows;
}
/**
* Function renderTitle
* @author David S. Callizaya S. <davidsantos@colosa.com>
* @access public
* @return string
*/
function renderTitle()
{
//fix the bug about showing hidden fields in propel table.
foreach($this->fields as $r => $rval) {
if ( $this->style[$r]['type'] == 'hidden') $this->style[$r]['showInTable'] = '0';
}
//Render headers
$this->colCount=0;
$this->shownFields='[';
foreach($this->fields as $r => $rval)
if (($this->style[$r]['showInTable'] != '0' )&&(!(in_array($this->fields[$r]['Name'],$this->masterdetail)))){
//if (($this->style[$r]['showInTable'] != '0' ))
$this->tpl->newBlock( "headers" );
$sortOrder = (((isset($this->aOrder[$this->fields[$r]['Name']])) && ($this->aOrder[$this->fields[$r]['Name']]==='ASC'))?'DESC':'ASC');
$sortOrder = (((isset($this->aOrder[$this->fields[$r]['Name']])) && ($this->aOrder[$this->fields[$r]['Name']]==='DESC'))?'':$sortOrder);
$this->style[$r]['href'] = $this->ownerPage . '?order=' .
( $sortOrder !=='' ? ( G::createUID('',$this->fields[$r]['Name'] ) . '=' . $sortOrder):'')
. '&page=' . $this->currentPage;
$this->style[$r]['onsort'] = $this->id . '.doSort("'.G::createUID('',$this->fields[$r]['Name']).'" , "' . $sortOrder.'");return false;';
if (isset($this->style[$r]['href']))
$this->tpl->assign( "href" , $this->style[$r]['href']);
if (isset($this->style[$r]['onsort']))
$this->tpl->assign( "onsort" , htmlentities( $this->style[$r]['onsort'] , ENT_QUOTES, 'UTF-8' ) );
if (isset($this->style[$r]['onclick']))
$this->tpl->assign( "onclick" , htmlentities( $this->style[$r]['onclick'] , ENT_QUOTES, 'UTF-8' ) );
if (isset($this->style[$r]['colWidth']))
$this->tpl->assign( "width" , $this->style[$r]['colWidth'] );
if (isset($this->style[$r]['colWidth']))
$this->tpl->assign( "widthPercent" , ($this->style[$r]['colWidth']*100 / $this->totalWidth) . "%" );
//Hook for special skin with RTL languajes
if( defined('SYS_LANG_DIRECTION') && SYS_LANG_DIRECTION == 'R') {
$this->style[$r]['titleAlign'] = 'right';
}
if (isset($this->style[$r]['titleAlign']))
$this->tpl->assign( "align" , 'text-align:'.$this->style[$r]['titleAlign'].';');
if ($this->style[$r]['titleVisibility']!='0') {
$sortOrder = (((isset($this->aOrder[$this->fields[$r]['Name']])) && ($this->aOrder[$this->fields[$r]['Name']]==='ASC'))?'<img src="/images/arrow-up.gif">':'');
$sortOrder = (((isset($this->aOrder[$this->fields[$r]['Name']])) && ($this->aOrder[$this->fields[$r]['Name']]==='DESC'))?'<img src="/images/arrow-down.gif">':$sortOrder);
$this->tpl->assign( "header" , $this->fields[$r]['Label'] . $sortOrder );
$this->tpl->assign('displaySeparator',
(($this->colCount==0)||(!isset($this->fields[$r]['Label']))||($this->fields[$r]['Label']===''))?'display:none;':'');
} else {
$this->tpl->assign('displaySeparator','display:none;');
}
$this->colCount+=2;
$this->shownFields.=($this->shownFields!=='[')?',':'';
$this->shownFields.='"'.$r.'"';
}
$this->shownFields.=']';
}
/**
* Function renderField
* @author David S. Callizaya S. <davidsantos@colosa.com>
* @access public
* @parameter string row
* @parameter string r
* @parameter string result
* @return string
*/
function renderField( $row, $r, $result)
{
global $G_DATE_FORMAT;
//to do: special content??
//$result['row__'] = $row; //Special content:
$styleData = $this->style[$r];
$fielDataName = $styleData['data'];
$fieldClassName = isset( $styleData['colClassName']) && ($styleData['colClassName']) ? $styleData['colClassName'] : $this->tdClass;
if ( $fielDataName != '' )
$value = ((isset($result[ $fielDataName ])) ? $result[ $fielDataName ] : '' );
else
$value = $this->fields[$r]['Label'];
$this->tpl->newBlock( "field" );
$this->tpl->assign('width', $this->style[$r]['colWidth']);
$classAttr = ( trim($fieldClassName) != '' ) ? " class=\"$fieldClassName\"" : '';
$this->tpl->assign('classAttr', $classAttr );
//to do: style is needed or not?
//$this->tpl->assign('style', $this->tdStyle);
$alignAttr = ( isset($this->style[$r]['align']) && strlen($this->style[$r]['align']>0) ) ? " align=\"" . $this->style[$r]['align'] . "\"" : '';
$this->tpl->assign( "alignAttr" , $alignAttr);
$fieldName = $this->fields[$r]['Name'];
$fieldClass = get_class( $this->xmlForm->fields[ $fieldName ] );
/*** BEGIN : Reeplace of @@, @%,... in field's attributes like onclick, link, */
if (isset($this->xmlForm->fields[ $this->fields[$r]['Name'] ]->link)) {
$this->xmlForm->fields[ $this->fields[$r]['Name'] ]->link
= G::replaceDataField($this->style[$r]['link'],$result);
}
if (isset($this->xmlForm->fields[ $fieldName ]->value)) {
$this->xmlForm->fields[ $fieldName ]->value = G::replaceDataField($styleData['value'],$result);
}
/*** END : Reeplace of @@, @%,... */
/*** Rendering of the field */
$this->xmlForm->fields[ $fieldName ]->mode = 'view';
$this->xmlForm->setDefaultValues();
$this->xmlForm->setValues( $result );
//var_dump($fieldName, $fieldClass );echo '<br /><br />';
if ( array_search( 'renderTable', get_class_methods( $fieldClass ) )!== FALSE ) {
$htmlField = $this->xmlForm->fields[ $fieldName ]->renderTable( $value, $this->xmlForm, true );
if(is_object($value)){
$value = '';
}
$this->tpl->assign( "value" , (eregi('^[[:space:]]', $value) && (substr($fieldName,0,3)!="PRO"))? str_ireplace(" ","&nbsp;",$htmlField):$htmlField );
}
return $this->fields[$r]['Type'];
}
/**
* Function defaultStyle
* @author David S. Callizaya S. <davidsantos@colosa.com>
* @access public
* @return string
*/
function defaultStyle()
{
foreach($this->fields as $r => $rval) {
$this->style[$r]=array( 'showInTable' => '1',
'titleVisibility' => '1',
'colWidth' => '150',
'onclick' => '',
'event' => '' );
//Some widths
if (!(strpos(' date linknew ', ' ' . $this->fields[$r]['Type']. ' ')===FALSE))
$this->style[$r]['colWidth']='70';
//Data source:
if (!(strpos(' title button linknew image-text jslink ', ' ' . $this->fields[$r]['Type']. ' ')===FALSE))
$this->style[$r]['data']=''; //If the control is a link it shows the label
else
$this->style[$r]['data']=$this->fields[$r]['Name']; //ELSE: The data value for that field
//Hidden fields
if (!isset($this->style[$r]['showInTable'])) {
if (!(strpos(' title button endgrid2 submit password ', ' ' . $this->fields[$r]['Type']. ' ')===FALSE)){
$this->style[$r]['showInTable']='0';
}
else{
$this->style[$r]['showInTable']='1';
}
}
//Hidden titles
if (!(strpos(' linknew button endgrid2 ', ' ' . $this->fields[$r]['Type']. ' ')===FALSE)) {
$this->style[$r]['titleVisibility']='0';
}
//Align titles
$this->style[$r]['titleAlign']='center';
//Align fields
if (defined('SYS_LANG_DIRECTION') && SYS_LANG_DIRECTION == 'R')
$this->style[$r]['align']='right';
else
$this->style[$r]['align']='left';
if (!(strpos(' linknew date ', ' ' . $this->fields[$r]['Type']. ' ')===FALSE)) {
$this->style[$r]['align']='center';
}
}
// Adjust the columns width to prevent overflow the page width
//Render headers
$totalWidth=0;
foreach($this->fields as $r => $rval)
if ($this->style[$r]['showInTable']!='0')
$totalWidth += $this->style[$r]['colWidth'];
$this->totalWidth = $totalWidth;
$maxWidth=1800;
$proportion=$totalWidth/$maxWidth;
if ($proportion>1)
$this->totalWidth = 1800;
if ($proportion>1)
foreach($this->fields as $r => $rval)
if ($this->style[$r]['showInTable']!='0')
$this->style[$r]['colWidth']=$this->style[$r]['colWidth']/$proportion;
}
/**
* Function renderTable
* @author David S. Callizaya S. <davidsantos@colosa.com>
* @parameter $block : = 'content'(Prints contentBlock only)
* @access public
* @return string
*/
function renderTable( $block = '', $fields = '' )
{
//Render Title
$thereisnotitle=true;
foreach($this->fields as $r => $rval)
if ($this->fields[$r]['Type']==='title'){
$this->title = $this->fields[$r]['Label'];
unset($this->fields[$r]);
$thereisnotitle=false;
}
if ($thereisnotitle){
$this->title = '';
}
$oHeadPublisher =& headPublisher::getSingleton();
$oHeadPublisher->addInstanceModule('leimnud', 'panel');
$time_start = microtime(true);
$this->prepareQuery( true );
$time_end = microtime(true); $time = $time_end - $time_start;
// verify if there are templates folders registered, template and method folders are the same
$folderTemplate = explode ( '/',$this->template );
$oPluginRegistry =& PMPluginRegistry::getSingleton();
if ( $oPluginRegistry->isRegisteredFolder( $folderTemplate[0] ) )
$templateFile = PATH_PLUGINS . $this->template. '.html';
else
$templateFile = PATH_TPL . $this->template. '.html';
// Prepare the template
$this->tpl = new TemplatePower( $templateFile );
$this->tpl->prepare();
if(is_array($fields)) {
foreach ( $fields as $key =>$val ) {
$this->tpl->assignGlobal( $key , $val ); //Changed to Global by JHL on Dec 14,2009.. then thes fields are available for all Blocks
}
}
/********** HEAD BLOCK ***************/
if (($block ==='') || ($block==='head')) {
$this->tpl->newBlock('headBlock');
$this->tpl->assign( 'pagedTable_Id' , $this->id );
$this->tpl->assign( 'pagedTable_Name' , $this->name );
$this->tpl->assign( 'pagedTable_Height' , $this->xmlForm->height );
$this->tpl->assign( "title", $this->title);
if (file_exists($this->xmlForm->home . $this->filterForm . '.xml')) {
$filterForm = new filterForm( $this->filterForm , $this->xmlForm->home );
if ($this->menu==='')
$this->menu= 'gulliver/pagedTable_Options';
}
if (file_exists($this->xmlForm->home . $this->menu . '.xml')) {
$menu = new xmlMenu( $this->menu , $this->xmlForm->home );
$this->tpl->newBlock('headerBlock');
$template = PATH_CORE . 'templates' . PATH_SEP . $menu->type . '.html';
$menu->setValues($this->xmlForm->values);
$menu->setValues(array( 'PAGED_TABLE_ID' => $this->id ));
$menu->setValues(array( 'PAGED_TABLE_FAST_SEARCH' => $this->fastSearch ));
if (isset($filterForm->name)) {
$menu->setValues(array('SEARCH_FILTER_FORM' => $filterForm->name));
}
$this->tpl->assign( 'content' , $menu->render( $template , $scriptCode ) );
$oHeadPublisher->addScriptFile( $menu->scriptURL );
$oHeadPublisher->addScriptCode( $scriptCode );
}
if (file_exists($this->xmlForm->home . $this->filterForm . '.xml')) {
$this->tpl->newBlock('headerBlock');
$this->filterForm_Id = $filterForm->id;
$filterForm->type = 'filterform';
$filterForm->ajaxServer = '../gulliver/defaultAjax';
$template = PATH_CORE . 'templates/' . $filterForm->type . '.html';
$filterForm->setValues($this->xmlForm->values);
$filterForm->setValues(array('PAGED_TABLE_ID' => $this->id ));
$filterForm->setValues(array( 'PAGED_TABLE_FAST_SEARCH' => $this->fastSearch ));
$this->tpl->assign( 'content' , $filterForm->render( $template , $scriptCode ) );
$oHeadPublisher->addScriptFile( $filterForm->scriptURL );
$oHeadPublisher->addScriptCode( $scriptCode );
if (isset($_SESSION))
$_SESSION[$filterForm->id]=$filterForm->values;
}
}
/********** CONTENT BLOCK ***************/
if (($block ==='') || ($block==='content')) {
$this->tpl->newBlock('contentBlock');
$this->tpl->assign('gridWidth','=['. substr($this->gridWidth,1) .']');
$this->tpl->assign('fieldNames','=['. substr($this->gridFields,1) .']');
$this->tpl->assign('ajaxUri','="'. addslashes($this->ajaxServer) . '"');
$this->tpl->assign('currentUri','="'. addslashes($this->ownerPage) . '"');
$this->tpl->assign('currentOrder','="'. addslashes($this->orderBy) . '"');
$this->tpl->assign('currentPage','='. $this->currentPage );
$this->tpl->assign('currentFilter','="' . '"');
$this->tpl->assign('totalRows','=' . $this->totRows );
$this->tpl->assign('rowsPerPage','='.$this->rowsPerPage);
$this->tpl->assign('popupPage','="'. addslashes($this->popupPage) . '"');
$this->tpl->assign('popupWidth','='.$this->popupWidth);
$this->tpl->assign('popupHeight','='.$this->popupHeight);
$this->tpl->assign('pagedTable_Id', $this->id );
$this->tpl->assign('pagedTable_Name', $this->name );
$this->tpl->assign("pagedTable_JS" , "{$this->id}.element=document.getElementById('pagedtable[{$this->id}]');");
$this->renderTitle();
//Render rows
if ( $this->criteria->getDbName() == 'dbarray' ) {
$rs = ArrayBasePeer::doSelectRs ( $this->criteria);
}
else {
$rs = GulliverBasePeer::doSelectRs ( $this->criteria);
}
$rs->setFetchmode (ResultSet::FETCHMODE_ASSOC);
/*
print "<div class='pagedTableDefault'><table class='default'>";
$rs->next();
$row = $rs->getRow();
while ( is_array ( $row ) ) {
print "<tr class='Row1'>";
foreach ( $row as $k=>$v ) print "<td>$v</td>";
print "</tr>";
$rs->next();
$row = $rs->getRow();
}
print "</table></div>"; die;*/
$gridRows=0;
$rs->next();
//Initialize the array of breakFields for Master Detail View
foreach($this->masterdetail as $keyMasterDetail => $fieldMasterDetail){
$breakField[$fieldMasterDetail]="novaluehere";
}
$breakFieldKeys=array_flip($this->masterdetail);
for($j=0;$j< $rs->getRecordCount() ;$j++) {
$result = $rs->getRow();
$rs->next();
$gridRows++;
$this->tpl->newBlock( "row" );
$this->tpl->assign( "class" , "Row".(($j%2)+1));
$this->tdStyle='';
$this->tdClass='';
//Start Master Detail: This enable the MasterDEtail view. By JHL November 2008
if(count($this->masterdetail)>0){
//TODO: Validate if there is a Field that not exists
//TODO: Style
//TODO: Improve Collapse function....
foreach($this->masterdetail as $keyMasterDetail => $fieldMasterDetail){
if($breakField[$fieldMasterDetail]!=$result[$fieldMasterDetail]){
$this->tpl->newBlock( "rowMaster" );
$this->tpl->newBlock( "fieldMaster" );
$this->tpl->assign( "alignAttr" , " colspan=".(count($this->fields)*2));
$this->tpl->assign( "value" ,$this->fields[$fieldMasterDetail]['Label']==""?"": $this->fields[$fieldMasterDetail]['Label'].": ".$this->xmlForm->fields[ $fieldMasterDetail ]->renderTable( $result[$fieldMasterDetail], $this->xmlForm, true ));
$breakField[$fieldMasterDetail]=$result[$fieldMasterDetail];
for($i=$breakFieldKeys[$fieldMasterDetail]+1;$i<count($breakField);$i++){
$breakField[$this->masterdetail[$i]]="novaluehere";
}
$rowName=array();
foreach($breakField as $key => $value){
if($value!="novaluehere"){
$rowName[$key]=$key."_".$value;
}
}
$this->tpl->assign( "masterRowName" , implode(",",$rowName));
$this->tpl->assign( 'pagedTable_Name' , $this->name );
$many="";
$this->tpl->assign( "value1" ,str_pad($many, count($rowName)-1 , "-") );
$this->tpl->gotoblock("rowMaster");
$this->tpl->assign( "masterRowName" , "_MD_".implode(",",$rowName));
$this->tpl->assign( "masterRowClass" , $keyMasterDetail==0?"masterDetailMain":"masterDetailOther");
}
}
$this->tpl->gotoblock("row");
if ( !isset($rowName) ) $rowName = array();
$this->tpl->assign( "rowName" , implode(",",$rowName));
}
//End Master Detail: This enable the MasterDEtail view
//Merge $result with $xmlForm values (for default valuesSettings)
if ( is_array ( $this->xmlForm->values ) )
$result = array_merge($this->xmlForm->values, $result);
foreach($this->fields as $r => $rval){
if (strcasecmp($this->fields[$r]['Type'],'cellMark')==0){
$result1 = $result;
$result1['row__'] = $j+1;
$result1 = array_merge($this->xmlForm->values, $result1);
$this->xmlForm->setDefaultValues();
$this->xmlForm->setValues( $result1 );
$this->tdStyle = $this->xmlForm->fields[ $this->fields[$r]['Name'] ]->tdStyle( $result1 , $this->xmlForm );
$this->tdClass = $this->xmlForm->fields[ $this->fields[$r]['Name'] ]->tdClass( $result1 , $this->xmlForm );
}
elseif ($this->style[$r]['showInTable'] != '0' ){
if (($this->style[$r]['showInTable'] != '0' )&&(!(in_array($this->fields[$r]['Name'],$this->masterdetail))))
$this->renderField($j+1,$r,$result);
}
}
}
$this->tpl->assign('_ROOT.gridRows','='. $gridRows); //number of rows in the current page
$this->tpl->newBlock('rowTag');
$this->tpl->assign('rowId','insertAtLast');
if( $this->currentPage > 1 ) {
$firstUrl = $this->ownerPage . '?order=' . $this->orderBy . '&page=1';
$firstAjax = $this->id . ".doGoToPage(1);return false;";
$prevpage = $this->currentPage - 1;
$prevUrl = $this->ownerPage . '?order=' . $this->orderBy . '&page=' . $prevpage;
$prevAjax = $this->id . ".doGoToPage(".$prevpage.");return false;";
$first = "<a href=\"" . htmlentities( $firstUrl , ENT_QUOTES , 'utf-8' ) . "\" onclick=\"".$firstAjax."\" class='firstPage'>&nbsp;</a>";
$prev = "<a href=\"" . htmlentities( $prevUrl , ENT_QUOTES , 'utf-8' ) . "\" onclick=\"".$prevAjax."\" class='previousPage'>&nbsp;</a>";
}
else{
$first = "<a class='noFirstPage'>&nbsp;</a>";
$prev = "<a class='noPreviousPage'>&nbsp;</a>";
}
if( $this->currentPage < $this->totPages ) {
$lastUrl = $this->ownerPage . '?order=' . $this->orderBy . '&page=' . $this->totPages;
$lastAjax = $this->id . ".doGoToPage(" .$this->totPages.");return false;";
$nextpage = $this->currentPage + 1;
$nextUrl = $this->ownerPage . '?order=' . $this->orderBy . '&page=' . $nextpage;
$nextAjax = $this->id . ".doGoToPage(" .$nextpage.");return false;";
$next = "<a href=\"" . htmlentities( $nextUrl , ENT_QUOTES , 'utf-8' ) . "\" onclick=\"".$nextAjax."\" class='nextPage'>&nbsp;</a>";
$last = "<a href=\"" . htmlentities( $lastUrl , ENT_QUOTES , 'utf-8' ) . "\" onclick=\"".$lastAjax."\" class='lastPage'>&nbsp;</a>";
}
else{
$next = "<a class='noNextPage'>&nbsp;</a>";
$last = "<a class='noLastPage'>&nbsp;</a>";
}
$pagesEnum='';
for ($r=1;$r<=$this->totPages;$r++)
if (($r>=($this->currentPage-5))&&($r<=($this->currentPage+5))){
$pageAjax = $this->id . ".doGoToPage(" .$r.");return false;";
if ($r!=$this->currentPage)
$pagesEnum.="&nbsp;<a href=\"" . htmlentities( $this->ownerPage . '?order=' . $this->orderBy . '&page=' . $r , ENT_QUOTES , 'utf-8' ) . "\" onclick=\"".$pageAjax."\">".$r."</a>";
else
$pagesEnum.="&nbsp;<a>".$r."</a>";
}
if ($this->totRows === 0) {
$this->tpl->newBlock( 'norecords' );
$this->tpl->assign( "columnCount", $this->colCount);
$noRecordsFound='ID_NO_RECORDS_FOUND';
if (G::LoadTranslation($noRecordsFound)) $noRecordsFound = G::LoadTranslation($noRecordsFound);
$this->tpl->assign( "noRecordsFound", $noRecordsFound);
}
if (!$this->disableFooter) {
$this->tpl->newBlock( "bottomFooter" );
$this->tpl->assign( "columnCount", $this->colCount);
$this->tpl->assign( "pagedTableId" , $this->id );
if (($this->totRows !== 0)) {
if ($this->totPages>1){
$this->tpl->assign( "first" , $first );
$this->tpl->assign( "prev" , $prev );
$this->tpl->assign( "next" , $next );
$this->tpl->assign( "last" , $last );
}
$this->tpl->assign( "currentPage" , $this->currentPage );
$this->tpl->assign( "totalPages" , $this->totPages );
$firstRow = ($this->currentPage-1) * $this->rowsPerPage+1;
$lastRow = $firstRow+$rs->getRecordCount()-1;
$this->tpl->assign( "firstRow" , $firstRow );
$this->tpl->assign( "lastRow" , $lastRow );
$this->tpl->assign( "totalRows" , $this->totRows );
} else {
$this->tpl->assign( "indexStyle", 'visibility:hidden;');
}
if ($this->searchBy) {
$this->tpl->assign( "fastSearchValue" , $this->fastSearch );
} else {
$this->tpl->assign( "fastSearchStyle" , 'visibility:hidden;' );
}
if ($this->addRow)
if($this->sqlInsert!='')
$this->tpl->assign( "insert" , '<a href="#" onclick="pagedTable.event=\'Insert\';popup(\''.$this->popupPage.'\');return false;">'./*G::LoadXml('labels','ID_ADD_NEW')*/ 'ID_ADD_NEW' .'</a>' );
$this->tpl->assign("pagesEnum", $pagesEnum);
}
?>
<script language='JavaScript' >
var <?=$this->id?><?=($this->name != '' ? '='.$this->name : '')?>=new G_PagedTable();
<?=$this->id?>.id<?='="'. addslashes($this->id) . '"'?>;
<?=$this->id?>.name<?='="'. addslashes($this->name) . '"'?>;
<?=$this->id?>.ajaxUri<?='="'. addslashes($this->ajaxServer) . '?ptID='.$this->id.'"'?>;
<?=$this->id?>.currentOrder<?='="'. addslashes($this->orderBy) . '"'?>;
<?=$this->id?>.currentFilter;
<?=$this->id?>.currentPage<?='='. $this->currentPage?>;
<?=$this->id?>.totalRows<?='='.$this->totRows ?>;
<?=$this->id?>.rowsPerPage<?='='.$this->rowsPerPage?>;
<?=$this->id?>.popupPage<?='="'. addslashes($this->popupPage) . '?ptID='.$this->id.'"'?>;
<?=$this->id?>.onUpdateField<?='="'. addslashes($this->onUpdateField) . '"'?>;
<?=$this->id?>.shownFields<?='='.$this->shownFields ?>;
var panelPopup;
var popupWidth<?='='.$this->popupWidth?>;
var popupHeight<?='='.$this->popupHeight?>;
</script>
<?php
}
/********** CLOSE BLOCK ***************/
if (($block ==='') || ($block==='close')) {
$this->tpl->newBlock( "closeBlock" );
}
//By JHL
//Put the content of the table in a variable to be used for other puposes
//Like rendering as PDF
global $_TABLE_CONTENT_;
$_TABLE_CONTENT_=$this->tpl->getOutputContent();
$this->tpl->printToScreen();
unset($this->tpl);
//unset($this->dbc);
//unset($this->ses);
$_SESSION['pagedTable['.$this->id.']']= serialize($this);
return;
}
/**
* Function printForm
* @param string $filename
* @param array $data
* @return void
*/
function printForm($filename,$data=array())
{ global $G_PUBLISH;
$G_PUBLISH = new Publisher();
$G_PUBLISH->AddContent('xmlform', 'xmlform', $filename, '', $data , $this->popupSubmit);
G::RenderPage( "publish" , "blank" );
}
}

View File

@@ -0,0 +1,101 @@
<?php
/**
* class.replacementLogo.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.
*
*/
class replacementLogo {
//var $dir='';
/**
* This function is the constructor of the replacementLogo class
* @param
* @return void
*/
function replacementLogo() {
}
/**
* This function upload a file
*
*
* @name upLoadFile
*
* @param string $dirUpload
* @param string $namefile
* @param string $typefile
* @param string $errorfile
* @param string $tpnfile
* @param string $formf
* @return string
*/
function upLoadFile($dirUpload, $namefile, $typefile, $errorfile, $tpnfile, $formf) {
//we are cheking the extension for file
$aExt = explode ( ".", $namefile );
$infoupload = ''; //|| ($formf["type"]['uploadfile'] == "application/octet-stream")image/png
if (($typefile == "image/jpeg") || ($typefile == "image/png")) {
if ($errorfile > 0) {
$infoupload = "Return Code: " . $errorfile . "<br />";
} else {
if (file_exists ( $dirUpload . $namefile )) {
$infoupload = $namefile . " already exists. ";
} else {
move_uploaded_file ( $tpnfile, $dirUpload . $namefile );
$infoupload = "Stored in: " . $dirUpload . $namefile;
}
}
} else {
$infoupload = "- " . $typefile . " Invalid file your file should be jpeg";
}
return $infoupload;
}
/**
* This function gets the logos' names
*
*
* @name getNameLogo
*
* @param
* @return array
*/
function getNameLogo() {
require_once 'classes/model/Configuration.php';
$oCriteria = new Criteria ( 'workflow' );
$oCriteria->addSelectColumn ( ConfigurationPeer::CFG_VALUE );
$oCriteria->add ( ConfigurationPeer::CFG_UID, 'USER_LOGO_REPLACEMENT' );
$oDataset = ConfigurationPeer::doSelectRS ( $oCriteria );
$oDataset->next ();
$aRow = $oDataset->getRow ();
if (isset ( $aRow [0] ))
$ainfoLogo = @unserialize ( $aRow [0] );
else
$ainfoLogo = NULL;
return ($ainfoLogo);
}
} // end class

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,588 @@
<?php
/**
* class.reportTables.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.
*
*/
G::LoadClass('case');
/**
* ReportTables - Report tables class
* @package ProcessMaker
* @author Julio Cesar Laura Avenda<64>o
* @copyright 2007 COLOSA
*/
class ReportTables
{
private $aDef = array('mysql' => array('number' => 'DOUBLE',
'char' => 'VARCHAR(255)',
'text' => 'TEXT',
'date' => 'DATETIME'),
'pgsql' => array('number' => 'DOUBLE',
'char' => 'VARCHAR(255)',
'text' => 'TEXT',
'date' => 'DATETIME'));
//private $sPrefix = 'REP_';
private $sPrefix = '';
/**
* Function deleteAllReportVars
* This function delete all reports
* @access public
* @param string $$sRepTabUid
* @return void
*/
public function deleteAllReportVars($sRepTabUid = '')
{
try {
$oCriteria = new Criteria('workflow');
$oCriteria->add(ReportVarPeer::REP_TAB_UID, $sRepTabUid);
ReportVarPeer::doDelete($oCriteria);
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Function prepareQuery
* This function removes the table
* @access public
* @param string $sTableName Table name
* @param string $sConnection Conexion
* @return void
*/
public function dropTable($sTableName, $sConnection = 'report')
{
$sTableName = $this->sPrefix . $sTableName;
//we have to do the propel connection
$PropelDatabase=$this->chooseDB($sConnection);
$con = Propel::getConnection($PropelDatabase);
$stmt = $con->createStatement();
try {
switch (DB_ADAPTER) {
case 'mysql':
$rs = $stmt->executeQuery( 'DROP TABLE IF EXISTS `' . $sTableName . '`');
break;
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Function createTable
* This Function creates the table
* @access public
* @param string $sTableName Table name
* @param string $sConnection Connection name
* @param string $sType
* @param array $aFields
* @param string $bDefaultFields
* @return void
*/
public function createTable($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $bDefaultFields = true)
{
$sTableName = $this->sPrefix . $sTableName;
//we have to do the propel connection
$PropelDatabase=$this->chooseDB($sConnection);
$con = Propel::getConnection($PropelDatabase);
$stmt = $con->createStatement();
try {
switch (DB_ADAPTER) {
case 'mysql':
$sQuery = 'CREATE TABLE IF NOT EXISTS `' . $sTableName . '` (';
if ($bDefaultFields) {
$sQuery .= "`APP_UID` VARCHAR(32) NOT NULL DEFAULT '',`APP_NUMBER` INT NOT NULL,";
if ($sType == 'GRID') {
$sQuery .= "`ROW` INT NOT NULL,";
}
}
foreach ($aFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '0',";
break;
case 'char':
$sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '',";
break;
case 'text':
$sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " ,";
break;
case 'date':
$sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '0000-00-00 00:00:00',";
break;
}
}
if ($bDefaultFields) {
$sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) ';
}
$sQuery .= ' DEFAULT CHARSET=utf8;';
$rs = $stmt->executeQuery( $sQuery );
break;
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Function populateTable
* This Function fills the table
* @access public
* @param string $sTableName Table name
* @param string $sConnection Connection name
* @param string $sType
* @param array $aFields
* @param string $sProcessUid
* @param string $sGrid
* @return void
*/
public function populateTable($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $sProcessUid = '', $sGrid = '')
{
$sTableName = $this->sPrefix . $sTableName;
//we have to do the propel connection
$PropelDatabase=$this->chooseDB($sConnection);
$con = Propel::getConnection($PropelDatabase);
$stmt = $con->createStatement();
if ($sType == 'GRID') {
$aAux = explode('-', $sGrid);
$sGrid = $aAux[0];
}
try {
switch (DB_ADAPTER) {
case 'mysql':
//select cases for this Process, ordered by APP_NUMBER
$oCriteria = new Criteria('workflow');
$oCriteria->add(ApplicationPeer::PRO_UID, $sProcessUid);
$oCriteria->addAscendingOrderByColumn(ApplicationPeer::APP_NUMBER);
$oDataset = ApplicationPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aData = unserialize($aRow['APP_DATA']);
//delete previous record from this report table ( previous records in case this is a grid )
$deleteSql = 'DELETE FROM `' . $sTableName . "` WHERE APP_UID = '" . $aRow['APP_UID'] . "'";
$rsDel = $stmt->executeQuery( $deleteSql );
if ($sType == 'NORMAL') {
$sQuery = 'INSERT INTO `' . $sTableName . '` (';
$sQuery .= '`APP_UID`,`APP_NUMBER`';
foreach ($aFields as $aField) {
$sQuery .= ',`' . $aField['sFieldName'] . '`';
}
$sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER'];
foreach ($aFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset($aData[$aField['sFieldName']]) ? (float)str_replace(',', '', $aData[$aField['sFieldName']]) : '0');
break;
case 'char':
case 'text':
if (!isset($aData[$aField['sFieldName']])) {
$aData[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset($aData[$aField['sFieldName']]) ? mysql_real_escape_string($aData[$aField['sFieldName']]) : '') . "'";
break;
case 'date':
$sQuery .= ",'" . (isset($aData[$aField['sFieldName']]) ? $aData[$aField['sFieldName']] : '') . "'";
break;
}
}
$sQuery .= ')';
$rs = $stmt->executeQuery( $sQuery );
}
else {
if (isset($aData[$sGrid])) {
foreach ($aData[$sGrid] as $iRow => $aGridRow) {
$sQuery = 'INSERT INTO `' . $sTableName . '` (';
$sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`';
foreach ($aFields as $aField) {
$sQuery .= ',`' . $aField['sFieldName'] . '`';
}
$sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER'] . ',' . $iRow;
foreach ($aFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0');
break;
case 'char':
case 'text':
if (!isset($aGridRow[$aField['sFieldName']])) {
$aGridRow[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'";
break;
case 'date':
$sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? $aGridRow[$aField['sFieldName']] : '') . "'";
break;
}
}
$sQuery .= ')';
$rs = $stmt->executeQuery( $sQuery );
}
}
}
$oDataset->next();
}
break;
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Function getTableVars
* @access public
* @param string $sRepTabUid
* @param boolean $bWhitType
* @return void
*/
public function getTableVars($sRepTabUid, $bWhitType = false)
{
try {
$oCriteria = new Criteria('workflow');
$oCriteria->add(ReportVarPeer::REP_TAB_UID, $sRepTabUid);
$oDataset = ReportVarPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aVars = array();
while ($aRow = $oDataset->getRow()) {
if ($bWhitType) {
$aVars[] = array('sFieldName' => $aRow['REP_VAR_NAME'], 'sType' => $aRow['REP_VAR_TYPE']);
}
else {
$aVars[] = $aRow['REP_VAR_NAME'];
}
$oDataset->next();
}
return $aVars;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Function deleteReportTable
* This Function deletes report table
* @access public
* @param string $sRepTabUid
* @return void
*/
public function deleteReportTable($sRepTabUid)
{
try {
$oReportTable = new ReportTable();
$aFields = $oReportTable->load($sRepTabUid);
$this->dropTable($aFields['REP_TAB_NAME'], $aFields['REP_TAB_CONNECTION']);
$oCriteria = new Criteria('workflow');
$oCriteria->add(ReportVarPeer::REP_TAB_UID, $sRepTabUid);
$oDataset = ReportVarPeer::doDelete($oCriteria);
$oReportTable->remove($sRepTabUid);
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Function getSplitDate
* This function gets the split date
* @access public
* @param date $date
* @param string $mask
* @return array
*/
function getSplitDate($date, $mask)
{
$sw1 = false;
for($i=0; $i<3; $i++){
$item = substr($mask, $i*2, 1);
switch($item){
case 'Y':
switch($i){
case 0:
$d1 = substr($date, 0, 4);
break;
case 1:
$d1 = substr($date, 3, 4);
break;
case 2:
$d1 = substr($date, 6, 4);
break;
}
$sw1 = true;
break;
case 'y':
switch($i){
case 0:
$d1 = substr($date, 0, 2);
break;
case 1:
$d1 = substr($date, 3, 2);
break;
case 2:
$d1 = substr($date, 6, 2);
break;
}
break;
case 'm':
switch($i){
case 0:
$d2 = substr($date, 0, 2);
break;
case 1:
$d2 = ($sw1)? substr($date, 5, 2): substr($date, 3, 2);
break;
case 2:
$d2 = ($sw1)? substr($date, 8, 2): substr($date, 5, 2);
break;
}
break;
case 'd':
switch($i){
case 0:
$d3 = substr($date, 0, 2);
break;
case 1:
$d3 = ($sw1)? substr($date, 5, 2): substr($date, 3, 2);
break;
case 2:
$d3 = ($sw1)? substr($date, 8, 2): substr($date, 5, 2);
break;
}
break;
}
}
return Array(isset($d1)?$d1:'', isset($d2)?$d2:'', isset($d3)?$d3:'');
}
/**
* Function getFormatDate
* This function returns the date formated
* @access public
* @param date $sDate
* @param date $sMask
* @return date
*/
function getFormatDate($sDate, $sMask)
{
//print $sDate." *** ". $sMask."<BR>";
$dateTime = explode(" ",$sDate); //To accept the Hour part
$aDate = explode ( '-', str_replace("/", "-", $dateTime[0]) );
$bResult = true;
foreach($aDate as $sDate){
if( !is_numeric($sDate) ){
$bResult = false;
break;
}
}
if( $sMask != '' ){
$aDate = $this->getSplitDate($dateTime[0], $sMask);
$aDate[0] = ($aDate[0] == '')? date('Y'): $aDate[0];
$aDate[1] = ($aDate[1] == '')? date('m'): $aDate[1];
$aDate[2] = ($aDate[2] == '')? date('d'): $aDate[2];
if( checkdate($aDate[1], $aDate[2], $aDate[0]) ){
} else {
return false;
}
}
$sDateC='';
for($i=0;$i< count($aDate);$i++){
$sDateC.= (($i==0)?"":"-") .$aDate[$i];
}
return ($sDateC);
}
/**
* Function updateTables
* This function updated the Report Tables
* @access public
* @param string $sProcessUid
* @param string $sApplicationUid
* @param string $iApplicationNumber
* @param string $aFields
* @return void
*/
public function updateTables($sProcessUid, $sApplicationUid, $iApplicationNumber, $aFields)
{
try {
//get all Active Report Tables
$oCriteria = new Criteria('workflow');
$oCriteria->add(ReportTablePeer::PRO_UID, $sProcessUid);
$oCriteria->add(ReportTablePeer::REP_TAB_STATUS, 'ACTIVE');
$oDataset = ReportTablePeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aVars = array();
while ($aRow = $oDataset->getRow()) {
$aRow['REP_TAB_NAME'] = $this->sPrefix . $aRow['REP_TAB_NAME'];
$PropelDatabase=$this->chooseDB($aRow['REP_TAB_CONNECTION']);
$con = Propel::getConnection($PropelDatabase);
$stmt = $con->createStatement();
switch (DB_ADAPTER) {
case 'mysql':
$aTableFields = $this->getTableVars($aRow['REP_TAB_UID'], true);
if ($aRow['REP_TAB_TYPE'] == 'NORMAL') {
$sqlExists = "SELECT * FROM `" . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'";
$rsExists = $stmt->executeQuery( $sqlExists, ResultSet::FETCHMODE_ASSOC);
$rsExists->next();
$aRow2 = $rsExists->getRow();
if ( is_array( $aRow2) ) {
$sQuery = 'UPDATE `' . $aRow['REP_TAB_NAME'] . '` SET ';
foreach ($aTableFields as $aField) {
$sQuery .= '`' . $aField['sFieldName'] . '` = ';
switch ($aField['sType']) {
case 'number':
$sQuery .= (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0') . ',';
break;
case 'char':
case 'text':
if (!isset($aFields[$aField['sFieldName']])) {
$aFields[$aField['sFieldName']] = '';
}
$sQuery .= "'" . (isset($aFields[$aField['sFieldName']]) ? mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . "',";
break;
case 'date':
$sQuery .= "'" . (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : '') . "',";
break;
}
}
$sQuery = substr($sQuery, 0, -1);
$sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'";
}
else {
$sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` (';
$sQuery .= '`APP_UID`,`APP_NUMBER`';
foreach ($aTableFields as $aField) {
$sQuery .= ',`' . $aField['sFieldName'] . '`';
}
$sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber;
foreach ($aTableFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0');
break;
case 'char':
case 'text':
if (!isset($aFields[$aField['sFieldName']])) {
$aFields[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset($aFields[$aField['sFieldName']]) ? mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . "'";
break;
case 'date':
$sQuery .= ",'" . (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : '') . "'";
break;
}
}
$sQuery .= ')';
}
$rs = $stmt->executeQuery( $sQuery );
}
else {
//remove old rows from database
$sqlDelete = 'DELETE FROM `' . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'";
$rsDelete = $stmt->executeQuery( $sqlDelete );
$aAux = explode('-', $aRow['REP_TAB_GRID']);
if (isset($aFields[$aAux[0]])) {
foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) {
$sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` (';
$sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`';
foreach ($aTableFields as $aField) {
$sQuery .= ',`' . $aField['sFieldName'] . '`';
}
$sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber . ',' . $iRow;
foreach ($aTableFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0');
break;
case 'char':
case 'text':
if (!isset($aGridRow[$aField['sFieldName']])) {
$aGridRow[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'";
break;
case 'date':
$sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? $aGridRow[$aField['sFieldName']] : '') . "'";
break;
}
}
$sQuery .= ')';
$rs =$stmt->executeQuery( $sQuery );
}
}
}
break;
}
$oDataset->next();
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Function tableExist
* Check if table exists
* @access public
* @return boolean
*/
function tableExist()
{
$bExists = true;
$oConnection = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$oDataset = mysql_query('SELECT COUNT(*) FROM REPORT_TABLE') || ($bExists = false);
return $bExists;
}
/**
* Function chooseDB
* Choose the database to connect
* @access public
* @param string $TabConnectionk
* @return string
*/
function chooseDB($TabConnectionk)
{
$repTabConnection = trim( strtoupper( $TabConnectionk ) );
$PropelDatabase = 'rp';
if ( $repTabConnection == '' || $repTabConnection == 'REPORT' )
$PropelDatabase = 'rp';
if ( $repTabConnection == 'RBAC' )
$PropelDatabase = 'rbac';
if ( $repTabConnection == 'WF' )
$PropelDatabase = 'workflow';
return ($PropelDatabase);
}
}

View File

@@ -0,0 +1,404 @@
<?php
/**
* class.serverConfiguration.php
*
* ProcessMaker Open Source Edition
* Copyright (C) 2004 - 2008 Colosa Inc.
*
* 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.
*
*/
/**
* ServerConfiguration - serverConf class
* @author Hugo Loza
* @copyright 2010 COLOSA
* @license GNU Affero General Public License
*/
class serverConf {
private $_aProperties = array ();
private $_aHeartbeatConfig = array ();
private $_aWSapces = array ();
private $aWSinfo = array ();
private $pluginsA = array ();
private $errors = array ();
private static $instance = NULL;
private $haveSetupData = false;
private $beatType = 'starting';
private $ip;
private $index = 0;
private $os;
private $webserver;
private $host;
private $php;
private $mysql;
private $pmVersion;
private $pmProduct = 'PMCE';
private $nextBeatDate;
var $logins;
private $lanDirection;
private $lanLanguage;
private function __construct() {
$this->filePath = PATH_DATA . 'srvConf.singleton';
}
/**
* This function is instancing to this object
* @param
* @return object
*/
function &getSingleton() {
if (self::$instance == NULL) {
self::$instance = new serverConf ( );
if ((file_exists ( self::$instance->filePath ))&&(filesize(self::$instance->filePath)>0)){
self::$instance->unSerializeInstance ( file_get_contents ( self::$instance->filePath ) );
}
}
return self::$instance;
}
/**
* This function generates a storable representation of this obejct
* @param
* @return void
*/
function serializeInstance() {
return serialize ( self::$instance );
}
/**
* This function takes a single serialized object and converts it back a object
* @param string $serialized
* @return void
*/
function unSerializeInstance($serialized) {
if (self::$instance == NULL) {
self::$instance = new serverConf ( );
}
if($instance = @unserialize ( $serialized )){
self::$instance = $instance;
}
}
/**
* This will save the object in the specified file (defined as a property of this class)
* @param
* @return void
*/
function saveSingleton() {
$this->filePath = PATH_DATA . 'srvConf.singleton';
$size = file_put_contents ( $this->filePath, $this->serializeInstance () );
}
/**
* With this is possible to save a property that will be saved in the properties
* array of this class.
* @param string $propertyName
* @param string $propertyValue
*/
function setProperty($propertyName, $propertyValue) {
$this->_aProperties [$propertyName] = $propertyValue;
$this->saveSingleton ();
}
/**
* To unset a defined property. If it doesn't exist then it does nothing.
* @param string $propertyName
* @return void
*/
function unsetProperty($propertyName) {
if (isset ( $this->_aProperties [$propertyName] )) {
unset ( $this->_aProperties [$propertyName] );
$this->saveSingleton ();
}
}
/**
* Returns the value of a defined property. If it doesn't exist then returns null
* @param string $propertyName
* @return string/null
*/
function getProperty($propertyName) {
if (isset ( $this->_aProperties [$propertyName] )) {
return $this->_aProperties [$propertyName];
}
else {
return null;
}
}
/**
* Used to have a record of succesful logins to the system (total and by WS)
* @param
* @return void
*/
function sucessfulLogin() {
$this->logins ++;
if ( isset ($this->workspaces[SYS_SYS]) && isset ($this->workspaces[SYS_SYS]['WSP_LOGINS']) )
$this->workspaces[SYS_SYS]['WSP_LOGINS'] ++;
if ( isset ($this->workspaces[SYS_SYS]) && !isset ($this->workspaces[SYS_SYS]['WSP_LOGINS']) )
$this->workspaces[SYS_SYS]['WSP_LOGINS'] = 1;
$this->saveSingleton ();
}
function setWsInfo($wsname,$info){
$this->aWSinfo[$wsname]=$info;
}
/**
* This will togle the status of a workspace (enabled,disabled)
* @param string $wsName
* @return void
*/
function changeStatusWS($wsName) {
if (isset ( $this->_aWSapces [$wsName] )) { //Enable WS
unset ( $this->_aWSapces [$wsName] );
}
else {
$this->_aWSapces [$wsName] = 'disabled';
}
$this->saveSingleton ();
}
/**
* Return the status of a WS. If is disabled will return 1 otherwise 0
* @param $wsname
* @return boolean
*/
function isWSDisabled($wsName) {
return isset ( $this->_aWSapces [$wsName] );
}
/**
* Check only if the server address or server name has changed,
* to send another beat in next minute.
* @param
* @return boolean
*/
function checkIfHostNameHasChanged() {
//removed the PM_VERSION control, because when an upgrade is done, the haveSetupData has to be changed.
if ($this->ip != getenv ( 'SERVER_ADDR' ))
return false;
if ($this->host != getenv ( 'SERVER_NAME' ))
return false;
return $this->haveSetupData;
}
/**
* Will return a list of all WS in this system and their related information.
* @uses getWorkspaceInfo
* @param
* @return array
*/
function getWSList() {
$dir = PATH_DB;
$wsArray = array ();
if (file_exists ( $dir )) {
if ($handle = opendir ( $dir )) {
while ( false !== ($file = readdir ( $handle )) ) {
if (($file != ".") && ($file != "..")) {
if (file_exists ( PATH_DB . $file . '/db.php' )) { //print $file."/db.php <hr>";
$statusl = ($this->isWSDisabled ( $file )) ? 'DISABLED' : 'ENABLED';
//$wsInfo = $this->getWorkspaceInfo ( $file );
if(isset($this->aWSinfo[$file])){
$wsInfo = $this->aWSinfo[$file];
}else{
$wsInfo ['num_processes'] = "not gathered yet";
$wsInfo ['num_cases'] = "not gathered yet";;
$wsInfo ['num_users'] = "not gathered yet";
}
$wsArray [$file] = array ('WSP_ID' => $file, 'WSP_NAME' => $file, 'WSP_STATUS' => $statusl, 'WSP_PROCESS_COUNT' => $wsInfo ['num_processes'], 'WSP_CASES_COUNT' => $wsInfo ['num_cases'], 'WSP_USERS_COUNT' => isset($wsInfo ['num_users'])?$wsInfo ['num_users']:"" );
if (isset ( $this->workspaces [$file] ['WSP_LOGINS'] ))
$wsArray [$file] ['WSP_LOGINS'] = $this->workspaces [$file] ['WSP_LOGINS'];
}
}
}
closedir ( $handle );
}
}
return $wsArray;
}
/**
* Will return all the information of a WS.
* - Status
* - # of cases
* - # of processes
* - # of users
* @param string $wsName
* @return array
*/
function getWorkspaceInfo($wsName) {
$aResult = Array ('num_processes' => '0', 'num_cases' => '0' );
$result = array();
require_once 'classes/model/Process.php';
require_once 'classes/model/Application.php';
require_once 'classes/model/Users.php';
$Criteria = new Criteria('workflow');
$Criteria->add (ProcessPeer::PRO_STATUS, 'ACTIVE' , CRITERIA::EQUAL );
$aResult['num_processes'] = ProcessPeer::doCount($Criteria);
$Criteria = new Criteria('workflow');
$Criteria->add (ApplicationPeer::APP_STATUS, 'COMPLETED' , CRITERIA::NOT_EQUAL );
$aResult['num_cases'] = ApplicationPeer::doCount($Criteria);
$Criteria = new Criteria('workflow');
$Criteria->add (UsersPeer::USR_STATUS, array('DELETED','DISABLED') , CRITERIA::NOT_IN );
$aResult['num_users'] = UsersPeer::doCount($Criteria);
return $aResult;
}
/**
* Will list the plugins of the system
* @param
* @retun array
*/
function getPluginsList() {
return $this->pluginsA;
}
/***
* Register a PLugin
*/
function addPlugin($workspace,$info){
$this->pluginsA[$workspace]=$info;
}
function getDBVersion(){
$sMySQLVersion = '?????';
if (defined ( "DB_HOST" )) {
G::LoadClass ( 'net' );
G::LoadClass ( 'dbConnections' );
$dbNetView = new NET ( DB_HOST );
$dbNetView->loginDbServer ( DB_USER, DB_PASS );
$dbConns = new dbConnections ( '' );
$availdb = '';
foreach ( $dbConns->getDbServicesAvailables () as $key => $val ) {
if ($availdb != '')
$availdb .= ', ';
$availdb .= $val ['name'];
}
try {
$sMySQLVersion = $dbNetView->getDbServerVersion ( 'mysql' );
}
catch ( Exception $oException ) {
$sMySQLVersion = '?????';
}
}
return $sMySQLVersion;
}
/**
* Will reset all the logins' count
* @param
* @return void
*/
function resetLogins() {
$this->logins = 0;
if(is_array($this->workspaces)){
foreach ( $this->workspaces as $wsName => $wsinfo ) {
$this->workspaces [$wsName] ['WSP_LOGINS'] = 0;
}
}
}
/**
* Get the value of language direction property
* @param void
* @return string
*/
function getLanDirection() {
if (!isset($this->lanDirection) ) {
$this->lanDirection = 'L';
}
if( defined('SYS_LANG') ) {
//if we already have the landirection for this language, just return from serverConf
if ( $this->lanLanguage == SYS_LANG )
return $this->lanDirection;
//if not , we need to query Database, in order to get the direction
$this->lanDirection = 'L'; //default value;
$this->lanLanguage = SYS_LANG;
require_once 'classes/model/Language.php';
$oLang = new Language();
try{
$aLang = $oLang->load(SYS_LANG);
if( isset($aLang['LAN_DIRECTION']) ){
$this->lanDirection = strtoupper($aLang['LAN_DIRECTION']);
}
$this->saveSingleton();
}
catch(Exception $e){
$this->lanDirection = 'L';
}
}
return $this->lanDirection;
}
/**
* With this is possible to save a property that will be saved in the properties
* array of this class.
* @param string $propertyName
* @param string $propertyValue
* @param string $workspace
*/
function setHeartbeatProperty($propertyName, $propertyValue, $workspace) {
$this->_aHeartbeatConfig [$workspace][$propertyName] = $propertyValue;
$this->saveSingleton ();
}
/**
* To unset a defined property. If it doesn't exist then it does nothing.
* @param string $propertyName
* @param string $workspace
* @return void
*/
function unsetHeartbeatProperty($propertyName,$workspace) {
if (isset ( $this->_aHeartbeatConfig [$workspace][$propertyName] ))
unset ( $this->_aHeartbeatConfig [$workspace][$propertyName] );
$this->saveSingleton ();
}
/**
* Returns the value of a defined property. If it doesn't exist then returns null
* @param string $propertyName
* @return string/null
*/
function getHeartbeatProperty($propertyName, $workspace) {
if (isset ( $this->_aHeartbeatConfig [$workspace][$propertyName] )) {
return $this->_aHeartbeatConfig [$workspace][$propertyName];
} else {
return null;
}
}
}

View File

@@ -0,0 +1,274 @@
<?php
/**
* class.Sessions.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.
*
*/
require_once 'classes/model/Session.php';
/**
* Sessions - Sessions class
* @package ProcessMaker
* @author Everth S. Berrios Morales
* @copyright 2008 COLOSA
*/
class Sessions {
protected $tmpfile;
private $sessionId;
private $globals;
/**
* This function is the constructor of the Sessions class
* @param string $sSessionId
* @return void
*/
public function __construct($sSessionId=NULL){
$this->sessionId = $sSessionId;
}
/**
* This function gets the user session
*
*
* @name getSessionUser
*
* @param string sSessionId
* @return array
*/
public function getSessionUser($sSessionId=NULL)
{
try
{
if($sSessionId != NULL){
$this->sessionId = $sSessionId;
} else if($this->sessionId == NULL){
throw new Exception('session id was not set.');
}
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(SessionPeer::USR_UID);
$oCriteria->addSelectColumn(SessionPeer::SES_STATUS);
$oCriteria->addSelectColumn(SessionPeer::SES_DUE_DATE);
$oCriteria->add(SessionPeer::SES_UID, $this->sessionId);
$oDataset = SessionPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
if( !is_array($aRow) ){
$this->deleteTmpfile();
}
return $aRow;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* This function checks the user session
*
*
* @name verifySession
*
* @param string sSessionId
* @return array
*/
public function verifySession($sSessionId=NULL)
{
try
{
if($sSessionId != NULL){
$this->sessionId = $sSessionId;
} else if($this->sessionId == NULL){
throw new Exception('session id was not set.');
}
$date=date('Y-m-d H:i:s');
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(SessionPeer::USR_UID);
$oCriteria->addSelectColumn(SessionPeer::SES_STATUS);
$oCriteria->addSelectColumn(SessionPeer::SES_DUE_DATE);
$oCriteria->add(SessionPeer::SES_UID, $this->sessionId);
$oCriteria->add(SessionPeer::SES_STATUS, 'ACTIVE');
$oCriteria->add(SessionPeer::SES_DUE_DATE, $date, Criteria::GREATER_EQUAL);
$oDataset = SessionPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
if( !is_array($aRow) ){
$this->deleteTmpfile();
}
return $aRow;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* This function registers into globals variables
*
*
* @name registerGlobal
*
* @param string $name
* @param string $value
* @return void
*/
public function registerGlobal($name, $value)
{
$this->tmpfile = G::getSysTemDir() . PATH_SEP . "pm-rg-{$this->sessionId}";
if($this->sessionId == NULL){
throw new Exception('session id was not set.');
}
$tmpfile_content = '';
if( is_file($this->tmpfile) && trim(file_get_contents($this->tmpfile)) != '' ) {
$tmpfile_content = file_get_contents($this->tmpfile);
}
//getting the global array
if( $tmpfile_content != ''){
$this->globals = unserialize($tmpfile_content);
} else {
$this->globals = Array();
}
//registering the new global variable
$this->globals[$name] = $value;
//saving the global array
$tmpfile_content = serialize($this->globals);
file_put_contents($this->tmpfile, $tmpfile_content);
}
/**
* This function gets a global variable
*
*
* @name getGlobal
*
* @param string $name
* @return string
*/
public function getGlobal($name)
{
$this->tmpfile = G::getSysTemDir() . PATH_SEP . "pm-rg-{$this->sessionId}";
if($this->sessionId == NULL){
throw new Exception('session id was not set.');
}
$tmpfile_content = '';
if( is_file($this->tmpfile) && trim(file_get_contents($this->tmpfile)) != '' ) {
$tmpfile_content = file_get_contents($this->tmpfile);
}
//getting the global array
if( $tmpfile_content != ''){
$this->globals = unserialize($tmpfile_content);
} else {
$this->globals = Array();
}
//getting the new global variable
if( isset($this->globals[$name]) ){
return $this->globals[$name];
} else {
return '';
}
}
/**
* This function gets all globals variables
*
*
* @name getGlobals
*
* @param string $name
* @return array
*/
public function getGlobals()
{
$this->tmpfile = G::getSysTemDir() . PATH_SEP . "pm-rg-{$this->sessionId}";
if($this->sessionId == NULL){
throw new Exception('session id was not set.');
}
$tmpfile_content = '';
if( is_file($this->tmpfile) && trim(file_get_contents($this->tmpfile)) != '' ) {
$tmpfile_content = file_get_contents($this->tmpfile);
}
//getting the global array
if( $tmpfile_content != ''){
$this->globals = unserialize($tmpfile_content);
} else {
$this->globals = Array();
}
return $this->globals;
}
/**
* This function removes a temporal file
*
*
* @name deleteTmpfile
*
* @param
* @return void
*/
private function deleteTmpfile(){
if($this->sessionId == NULL){
throw new Exception('session id was not set.');
}
$this->tmpfile = G::getSysTemDir() . PATH_SEP . "pm-rg-{$this->sessionId}";
@unlink($this->tmpfile);
}
}

View File

@@ -0,0 +1,302 @@
<?php
/**
* @brief smtp class to send emails. Requires an email server.
*
* @package Tomahawk_Mail
* @author Ian K Armstrong <ika@[REMOVE_THESE_CAPITALS]openmail.cc>
* @copyright Copyright (c) 2007, Ian K Armstrong
* @license http://www.opensource.org/licenses/gpl-3.0.html GNU Public License
* @link http://www.openmail.cc
*
* @category web_mail
* @subpackage mail
* @filesource
* @version
*
* @file class.smtp.php
*
*/
//-------------------------------------------------------------
// smtp authentication
//-------------------------------------------------------------
// setSmtpAuthentication($sAuth)
// setUsername($sName)
// setPassword($sPass)
//-------------------------------------------------------------
class smtp
{
private $mail_server;
private $port;
private $return_path;
private $envelope_to;
private $status;
private $headers;
private $body;
private $log;
private $with_auth;
private $username;
private $password;
/**
* Function __construct
* Constructor of the class
* @return void
*/
function __construct()
{
$this->status = false;
$this->with_auth = false; // change to 'true' to use smtp authentication
$this->username = ''; // needed for smtp authentication
$this->password = ''; // needed for smtp authentication
$this->mail_server = @gethostbyaddr('127.0.0.1');
$this->port = 25;
$this->return_path = '';
$this->envelope_to = array();
$this->headers = '';
$this->body = '';
$this->log = array();
}
/**
* Function setServer
* This sets the server used for sending mail
* @param string $sServer
* @return void
*/
public function setServer($sServer)
{
if(($sAux = @gethostbyaddr($sServer)))
$sServer = $sAux;
$this->mail_server = $sServer;
}
/**
* Function setPort
* This sets the port used for sending mail
* @param string $iPort
* @return void
*/
public function setPort($iPort)
{
$this->port = ($iPort != '' ? (int)$iPort : 25);
}
/**
* Function setReturnPath
* This function sets the return path
* @param string $sReturnPath
* @return void
*/
public function setReturnPath($sReturnPath)
{
$this->return_path = $sReturnPath;
}
/**
* Function setHeaders
* This sets the headers of the mail to be sent
* @param string $sHeaders
* @return void
*/
public function setHeaders($sHeaders)
{
$this->headers = $sHeaders;
}
/**
* Function setBody
* This sets the mail body
* @param string $sBody
* @return void
*/
public function setBody($sBody)
{
$this->body = $sBody;
}
/**
* Function setSmtpAuthentication
* This function sets the Smtp Authentication
* @param string $sAuth
* @return void
*/
public function setSmtpAuthentication($sAuth)
{
$this->with_auth = $sAuth;
}
/**
* Function setUsername
* This function sets the user name
* @param string $sName
* @return void
*/
public function setUsername($sName)
{
$this->username = $sName;
}
/**
* Function setPassword
* This function sets the password
* @param string $sPass
* @return void
*/
public function setPassword($sPass)
{
$this->password = $sPass;
}
/**
* Function returnErrors
* This Function returns errors
* @return void
*/
public function returnErrors()
{
return $this->log;
}
/**
* Function returnStatus
* @return void
*/
public function returnStatus()
{
return $this->status;
}
/**
* Function setEnvelopeTo
* @param string $env_to
* @return void
*/
public function setEnvelopeTo($env_to)
{
if(count($env_to)>0){
foreach($env_to as $val){
(false !== ($p = strpos($val,'<')))
? $this->envelope_to[] = trim(substr($val,$p))
: $this->envelope_to[] = trim($val);
}
}
}
/**
* Function sendMessage
* This function is responsible for sending the message
* @return boolean
*/
public function sendMessage()
{
// connect
$errno = $errstr = '';
$cp = @fsockopen("$this->mail_server", $this->port, $errno, $errstr, 1);
if(!$cp){
$this->log[] = 'Failed to make a connection';
return false;
}
$res = fgets($cp,256);
if(substr($res,0,3) != '220'){
$this->log[] = $res.' Failed to connect';
fclose($cp);
return false;
}
if(false !== $this->with_auth){
// say EHLO - works with SMTP and ESMTP servers
fputs($cp, 'EHLO '."$this->mail_server\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '250'){
$this->log[] = $res.' Failed to say EHLO';
fclose($cp);
return false;
}
// Request Authentication
fputs($cp, 'AUTH LOGIN'."\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '334'){
$this->log[] = $res.' Auth Login Failed';
fclose($cp);
return false;
}
// Send Username
fputs($cp, base64_encode($this->username)."\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '334'){
$this->log[] = $res.' Username failed';
fclose($cp);
return false;
}
// Send Password
fputs($cp, base64_encode($this->password)."\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '235'){
$this->log[] = $res.' Password failed';
fclose($cp);
return false;
}
}
else{// without smtp authentication
// say HELO
fputs($cp, 'HELO '."$this->mail_server\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '250'){
$this->log[] = $res.' Failed to say HELO';
fclose($cp);
return false;
}
}
// mail from
fputs($cp, 'MAIL FROM: '."$this->return_path\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '250'){
$this->log[] = $res.' MAIL FROM failed';
fclose($cp);
return false;
}
// mail to
foreach($this->envelope_to as $val){
fputs($cp, 'RCPT TO: '."$val\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '250'){
$this->log[] = $res.' RCPT TO failed';
fclose($cp);
return false;
}
}
// data
fputs($cp, 'DATA'."\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '354'){
$this->log[] = $res.' DATA failed';
fclose($cp);
return false;
}
// send headers
fputs($cp, "$this->headers\r\n");
// send body
fputs($cp, "$this->body\r\n");
// end of message
fputs($cp, "\r\n.\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '250'){
$this->log[] = $res. ' Message failed';
fclose($cp);
return false;
}
// quit
fputs($cp, 'QUIT'."\r\n");
$res = fgets($cp,256);
if(substr($res,0,3) != '221'){
$this->log[] = $res.' QUIT failed';
fclose($cp);
return false;
}
fclose($cp);
$this->status = true;
}
} // end of class
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,432 @@
<?php
/**
* class.tasks.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.
*
*/
/**
* spoolRun - brief send email from the spool database, and see if we have all the addresses we send to.
* @package ProcessMaker
* @author Ian K Armstrong <ika@[REMOVE_THESE_CAPITALS]openmail.cc>
* @copyright Copyright (c) 2007, Ian K Armstrong
* @license http://www.opensource.org/licenses/gpl-3.0.html GNU Public License
* @link http://www.openmail.cc
*/
/**
* LOG FIXES
* =========
*
* 24-03-2010 Erik A.O. <erik@colosa.com>
* class: the $ExceptionCode and $aWarnings class attributes were added
* function handleFrom(): Validations for invalid data for {$this->fileData['from_email']} were added
* function resendEmails(): handler for warnings was added and fixes
* function getWarnings(): added
* function sendMail(): now is handling the exception
*/
require_once ('classes/model/AppMessage.php');
class spoolRun {
private $config;
private $fileData;
private $spool_id;
public $status;
public $error;
private $ExceptionCode = Array (); //Array to define the Expetion codes
private $aWarnings = Array (); //Array to store the warning that were throws by the class
private $longMailEreg;
private $mailEreg;
/**
* Class constructor - iniatilize default values
* @param none
* @return none
*/
function __construct() {
$this->config = array ();
$this->fileData = array ();
$this->spool_id = '';
$this->status = 'pending';
$this->error = '';
$this->ExceptionCode['FATAL'] = 1;
$this->ExceptionCode['WARNING'] = 2;
$this->ExceptionCode['NOTICE'] = 3;
$this->longMailEreg = '/([\"\w\W\s]*\s*)?(<([\w\-\.]+@[\.-\w]+\.\w{2,3})+>)/';
$this->mailEreg = '/^([\w\-_\.]+@[\.-\w]+\.\w{2,3}+)$/';
}
/**
* get all files into spool in a list
* @param none
* @return none
*/
public function getSpoolFilesList() {
$sql = "SELECT * FROM APP_MESSAGE WHERE APP_MSG_STATUS ='pending'";
$con = Propel::getConnection("workflow");
$stmt = $con->prepareStatement($sql);
$rs = $stmt->executeQuery();
while( $rs->next() ) {
$this->spool_id = $rs->getString('APP_MSG_UID');
$this->fileData['subject'] = $rs->getString('APP_MSG_SUBJECT');
$this->fileData['from'] = $rs->getString('APP_MSG_FROM');
$this->fileData['to'] = $rs->getString('APP_MSG_TO');
$this->fileData['body'] = $rs->getString('APP_MSG_BODY');
$this->fileData['date'] = $rs->getString('APP_MSG_DATE');
$this->fileData['cc'] = $rs->getString('APP_MSG_CC');
$this->fileData['bcc'] = $rs->getString('APP_MSG_BCC');
$this->fileData['template'] = $rs->getString('APP_MSG_TEMPLATE');
$this->fileData['attachments'] = array (); //$rs->getString('APP_MSG_ATTACH');
if( $this->config['MESS_ENGINE'] == 'OPENMAIL' ) {
if( $this->config['MESS_SERVER'] != '' ) {
if( ($sAux = @gethostbyaddr($this->config['MESS_SERVER'])) ) {
$this->fileData['domain'] = $sAux;
} else {
$this->fileData['domain'] = $this->config['MESS_SERVER'];
}
} else {
$this->fileData['domain'] = gethostbyaddr('127.0.0.1');
}
}
$this->sendMail();
}
}
/**
* create a msg record for spool
* @param array $aData
* @return none
*/
public function create($aData) {
G::LoadClass('insert');
$oInsert = new insert();
$sUID = $oInsert->db_insert($aData);
$aData['app_msg_date'] = isset($aData['app_msg_date']) ? $aData['app_msg_date'] : '';
if( isset($aData['app_msg_status']) ) {
$this->status = strtolower($aData['app_msg_status']);
}
$this->setData($sUID, $aData['app_msg_subject'], $aData['app_msg_from'], $aData['app_msg_to'], $aData['app_msg_body'], $aData['app_msg_date'], $aData['app_msg_cc'], $aData['app_msg_bcc'], $aData['app_msg_template']);
}
/**
* set configuration
* @param array $aConfig
* @return none
*/
public function setConfig($aConfig) {
$this->config = $aConfig;
}
/**
* set email parameters
* @param string $sAppMsgUid, $sSubject, $sFrom, $sTo, $sBody, $sDate, $sCC, $sBCC, $sTemplate
* @return none
*/
public function setData($sAppMsgUid, $sSubject, $sFrom, $sTo, $sBody, $sDate = '', $sCC = '', $sBCC = '', $sTemplate = '') {
$this->spool_id = $sAppMsgUid;
$this->fileData['subject'] = $sSubject;
$this->fileData['from'] = $sFrom;
$this->fileData['to'] = $sTo;
$this->fileData['body'] = $sBody;
$this->fileData['date'] = ($sDate != '' ? $sDate : date('Y-m-d H:i:s'));
$this->fileData['cc'] = $sCC;
$this->fileData['bcc'] = $sBCC;
$this->fileData['template'] = $sTemplate;
$this->fileData['attachments'] = array ();
if( $this->config['MESS_ENGINE'] == 'OPENMAIL' ) {
if( $this->config['MESS_SERVER'] != '' ) {
if( ($sAux = @gethostbyaddr($this->config['MESS_SERVER'])) ) {
$this->fileData['domain'] = $sAux;
} else {
$this->fileData['domain'] = $this->config['MESS_SERVER'];
}
} else {
$this->fileData['domain'] = gethostbyaddr('127.0.0.1');
}
}
}
/**
* send mail
* @param none
* @return boolean true or exception
*/
public function sendMail() {
try {
$this->handleFrom();
$this->handleEnvelopeTo();
$this->handleMail();
$this->updateSpoolStatus();
return true;
} catch( Exception $e ) {
throw $e;
}
}
/**
* update the status to spool
* @param none
* @return none
*/
private function updateSpoolStatus() {
$oAppMessage = AppMessagePeer::retrieveByPK($this->spool_id);
$oAppMessage->setappMsgstatus($this->status);
$oAppMessage->setappMsgsenddate(date('Y-m-d H:i:s'));
$oAppMessage->save();
}
/**
* handle the email that was set in "TO" parameter
* @param none
* @return boolean true or exception
*/
private function handleFrom() {
if( strpos($this->fileData['from'], '<') !== false ) {
//to validate complex email address i.e. Erik A. O <erik@colosa.com>
preg_match($this->longMailEreg, $this->fileData['from'], $matches);
if( isset($matches[1]) && $matches[1] != '' ) {
//drop the " characters if they exist
$this->fileData['from_name'] = trim(str_replace('"', '', $matches[1]));
} else { //if the from name was not set
$this->fileData['from_name'] = 'Processmaker';
}
if( ! isset($matches[3]) ) {
throw new Exception('Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING']);
}
$this->fileData['from_email'] = trim($matches[3]);
} else {
//to validate simple email address i.e. erik@colosa.com
preg_match($this->mailEreg, $this->fileData['from'], $matches);
if( ! isset($matches[0]) ) {
throw new Exception('Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING']);
}
$this->fileData['from_name'] = 'Processmaker Web boot';
$this->fileData['from_email'] = $matches[0];
}
}
/**
* handle all recipients to compose the mail
* @param none
* @return boolean true or exception
*/
private function handleEnvelopeTo() {
$hold = array ();
$text = trim($this->fileData['to']);
if( isset($this->fileData['cc']) && trim($this->fileData['cc']) != '' ) {
$text .= ',' . trim($this->fileData['cc']);
}
if( isset($this->fileData['bcc']) && trim($this->fileData['bcc']) != '' ) {
$text .= ',' . trim($this->fileData['bcc']);
}
if( false !== (strpos($text, ',')) ) {
$hold = explode(',', $text);
foreach( $hold as $val ) {
if( strlen($val) > 0 ) {
$this->fileData['envelope_to'][] = "$val";
}
}
} else {
$this->fileData['envelope_to'][] = "$text";
}
}
/**
* handle and compose the email content and parameters
* @param none
* @return none
*/
private function handleMail() {
if( count($this->fileData['envelope_to']) > 0 ) {
switch( $this->config['MESS_ENGINE'] ) {
case 'MAIL':
G::LoadThirdParty('phpmailer', 'class.phpmailer');
$oPHPMailer = new PHPMailer();
$oPHPMailer->Mailer = 'mail';
$oPHPMailer->SMTPAuth = (isset($this->config['SMTPAuth']) ? $this->config['SMTPAuth'] : '');
$oPHPMailer->Host = $this->config['MESS_SERVER'];
$oPHPMailer->Port = $this->config['MESS_PORT'];
$oPHPMailer->Username = $this->config['MESS_ACCOUNT'];
$oPHPMailer->Password = $this->config['MESS_PASSWORD'];
$oPHPMailer->From = $this->fileData['from_email'];
$oPHPMailer->FromName = utf8_decode($this->fileData['from_name']);
$oPHPMailer->Subject = utf8_decode($this->fileData['subject']);
$oPHPMailer->Body = utf8_decode($this->fileData['body']);
foreach( $this->fileData['envelope_to'] as $sEmail ) {
if( strpos($sEmail, '<') !== false ) {
preg_match($this->longMailEreg, $sEmail, $matches);
$sTo = trim($matches[3]);
$sToName = trim($matches[1]);
$oPHPMailer->AddAddress($sTo, $sToName);
} else {
$oPHPMailer->AddAddress($sEmail);
}
}
$oPHPMailer->IsHTML(true);
if( $oPHPMailer->Send() ) {
$this->error = '';
$this->status = 'sent';
} else {
$this->error = $oPHPMailer->ErrorInfo;
$this->status = 'failed';
}
break;
case 'PHPMAILER':
G::LoadThirdParty('phpmailer', 'class.phpmailer');
$oPHPMailer = new PHPMailer();
$oPHPMailer->Mailer = 'smtp';
$oPHPMailer->SMTPAuth = (isset($this->config['SMTPAuth']) ? $this->config['SMTPAuth'] : '');
$oPHPMailer->Host = $this->config['MESS_SERVER'];
$oPHPMailer->Port = $this->config['MESS_PORT'];
$oPHPMailer->Username = $this->config['MESS_ACCOUNT'];
$oPHPMailer->Password = $this->config['MESS_PASSWORD'];
$oPHPMailer->From = $this->fileData['from_email'];
$oPHPMailer->FromName = utf8_decode($this->fileData['from_name']);
$oPHPMailer->Subject = utf8_decode($this->fileData['subject']);
$oPHPMailer->Body = utf8_decode($this->fileData['body']);
foreach( $this->fileData['envelope_to'] as $sEmail ) {
$evalMail = strpos($sEmail, '<');
if( strpos($sEmail, '<') !== false ) {
preg_match($this->longMailEreg, $sEmail, $matches);
$sTo = trim($matches[3]);
$sToName = trim($matches[1]);
$oPHPMailer->AddAddress($sTo, $sToName);
} else {
$oPHPMailer->AddAddress($sEmail);
}
}
$oPHPMailer->IsHTML(true);
if( $oPHPMailer->Send() ) {
$this->error = '';
$this->status = 'sent';
} else {
$this->error = $oPHPMailer->ErrorInfo;
$this->status = 'failed';
}
break;
case 'OPENMAIL':
G::LoadClass('package');
G::LoadClass('smtp');
$pack = new package($this->fileData);
$header = $pack->returnHeader();
$body = $pack->returnBody();
$send = new smtp();
$send->setServer($this->config['MESS_SERVER']);
$send->setPort($this->config['MESS_PORT']);
$send->setUsername($this->config['MESS_ACCOUNT']);
$send->setPassword($this->config['MESS_PASSWORD']);
$send->setReturnPath($this->fileData['from_email']);
$send->setHeaders($header);
$send->setBody($body);
$send->setEnvelopeTo($this->fileData['envelope_to']);
if( $send->sendMessage() ) {
$this->error = '';
$this->status = 'sent';
} else {
$this->error = implode(', ', $send->returnErrors());
$this->status = 'failed';
}
break;
}
}
}
/**
* try resend the emails from spool
* @param none
* @return none or exception
*/
function resendEmails() {
require_once 'classes/model/Configuration.php';
$oConfiguration = new Configuration();
$aConfiguration = $oConfiguration->load('Emails', '', '', '', '');
$aConfiguration = unserialize($aConfiguration['CFG_VALUE']);
if( $aConfiguration['MESS_ENABLED'] == '1' ) {
$this->setConfig(array (
'MESS_ENGINE' => $aConfiguration['MESS_ENGINE'],
'MESS_SERVER' => $aConfiguration['MESS_SERVER'],
'MESS_PORT' => $aConfiguration['MESS_PORT'],
'MESS_ACCOUNT' => $aConfiguration['MESS_ACCOUNT'],
'MESS_PASSWORD' => $aConfiguration['MESS_PASSWORD']
));
require_once 'classes/model/AppMessage.php';
$oCriteria = new Criteria('workflow');
$oCriteria->add(AppMessagePeer::APP_MSG_STATUS, 'sent', Criteria::NOT_EQUAL);
$oDataset = AppMessagePeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
while( $oDataset->next() ) {
$aRow = $oDataset->getRow();
try {
$this->setData($aRow['APP_MSG_UID'], $aRow['APP_MSG_SUBJECT'], $aRow['APP_MSG_FROM'], $aRow['APP_MSG_TO'], $aRow['APP_MSG_BODY']);
$this->sendMail();
} catch( Exception $oException ) {
if( $oException->getCode() == $this->ExceptionCode['WARNING'] ) {
array_push($this->aWarnings, 'Spool::resendEmails(): Using ' . $aConfiguration['MESS_ENGINE'] . ' for APP_MGS_UID=' . $aRow['APP_MSG_UID'] . ' -> With message: ' . $oException->getMessage());
continue;
} else {
throw $oException;
}
}
}
}
}
/**
* gets all warnings
* @param none
* @return string $this->aWarnings
*/
function getWarnings() {
if( sizeof($this->aWarnings) != 0 ) {
return $this->aWarnings;
}
return false;
}
}
?>

View File

@@ -0,0 +1,521 @@
<?php
/**
* upgrade_System.php
*
* ProcessMaker Open Source Edition
* Copyright (C) 2004 - 2008 Colosa Inc.
*
* 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.
*
*/
/**
* class system for workflow mantanance routines
*
* @uthor Erik A.O.<erik@colosa.com>
* @date May 12th, 2010
*
*/
class System {
var $sFilename;
var $sFilesList;
var $sUpgradeFileList;
var $aErrors;
var $aWorkspaces;
var $sRevision;
var $sPath;
var $newSystemClass;
/**
* This function checks files to do updated to pm
*
*
* @name verifyFileForUpgrade
*
* @param
* @return boolean
*/
function verifyFileForUpgrade()
{
$upgradeFilename = isset($_FILES['form']['name']['UPGRADE_FILENAME']) ? $_FILES['form']['name']['UPGRADE_FILENAME'] : '';
$tempFilename = isset($_FILES['form']['tmp_name']['UPGRADE_FILENAME']) ? $_FILES['form']['tmp_name']['UPGRADE_FILENAME'] : '';
$this->sRevision = str_replace('.tar.gz', '', str_replace('pmos-patch-', '', $upgradeFilename));
$sTemFilename = $tempFilename;
$this->sFilename = PATH_DATA . 'upgrade' . PATH_SEP . $upgradeFilename;
$this->sPath = dirname($this->sFilename) . PATH_SEP;
G::mk_dir(PATH_DATA . 'upgrade');
if( ! move_uploaded_file($sTemFilename, $this->sFilename) ) {
return false;
}
return true;
}
/**
* This function gets files to do updated to pm
*
*
* @name getUpgradedFilesList
*
* @param
* @return void
*/
function getUpgradedFilesList()
{
G::LoadClass('archive');
$this->sFilesList = new gzip_file($this->sFilename);
$this->sFilesList->set_options(array (
'basedir' => dirname($this->sFilename),
'overwrite' => 1
));
$this->sFilesList->extract_files();
if( count($this->sFilesList->error) > 0 ) {
$msg = '';
foreach( $this->sFilesList->error as $key => $val ) {
$msg .= $val . "\n";
}
throw new Exception($msg);
}
if( count($this->sFilesList->files) == 0 ) {
throw new Exception('The uploaded file is an invalid patch file.');
}
}
/**
* This function checks to do updated for boot
*
*
* @name verifyForBootstrapUpgrade
*
* @param
* @return boolean
*/
function verifyForBootstrapUpgrade()
{
foreach( $this->sFilesList->files as $sFile ) {
if( basename($sFile) == 'schema.xml' ) {
$this->newSystemClass = $sFile;
return true;
}
}
return false;
}
/**
* This function updates to the files
*
*
* @name upgrade
*
* @param
* @return array
*/
function upgrade()
{
//get special files
$sListFile = '';
$sCheckListFile = '';
$sPatchVersionFile = '';
$sPoFile = '';
$sSchemaFile = '';
$sSchemaRBACFile = '';
foreach( $this->sFilesList->files as $sFile ) {
if( basename($sFile) == 'schema.xml' ) {
if( strpos($sFile, '/rbac/engine/') === false ) {
$sOldSchema = '';
$sSchemaFile = $sFile;
} else {
$sOldSchemaRBAC = '';
$sSchemaRBACFile = $sFile;
}
}
//files.lst
if( basename($sFile) == 'files.lst' ) {
$this->sUpgradeFileList = $sFile;
}
//files.lst
if( basename($sFile) == 'patch.version.txt' ) {
$sPatchVersionFile = $sFile;
}
//files.rev.txt
if( substr(basename($sFile), 0, 6) == 'files.' && substr(basename($sFile), - 4) == '.txt' ) {
$sCheckListFile = $sFile;
}
//po files
$sExtension = substr($sFile, strrpos($sFile, '.') + 1, strlen($sFile));
if( $sExtension == 'po' ) {
$sPoFile = $sFile;
}
}
//now getting the current version of PM
if( file_exists(PATH_METHODS . 'login/version-pmos.php') ) {
include (PATH_METHODS . 'login/version-pmos.php');
} else {
define('PM_VERSION', '1.6-0-development');
}
$pmVersion = explode('-', PM_VERSION);
array_shift($pmVersion);
$patchVersion = explode('-', $this->sRevision);
if( $sPatchVersionFile != '' && file_exists($sPatchVersionFile) ) {
$this->sRevision = file_get_contents($sPatchVersionFile);
$patchVersion = explode('-', $this->sRevision);
}
if( ! file_exists(PATH_DATA . 'log' . PATH_SEP) ) {
G::mk_dir(PATH_DATA . 'log' . PATH_SEP);
}
//empty query log
$sqlLog = PATH_DATA . 'log' . PATH_SEP . "query.log";
$fp = fopen($sqlLog, "w+");
fwrite($fp, "");
fclose($fp);
$aEnvironmentsUpdated = array ();
$aEnvironmentsDiff = array ();
$aErrors = array ();
//now will verify each folder and file has permissions to write and add files.
if( $this->sUpgradeFileList != '' ) {
$bCopySchema = true;
$oFile = fopen($this->sUpgradeFileList, 'r');
while( $sLine = trim(fgets($oFile)) ) {
$sLine = substr($sLine, 1);
$aAux = explode(PATH_SEP, $sLine);
array_shift($aAux);
$sFilePath = implode(PATH_SEP, $aAux);
$targetFileName = PATH_TRUNK . $sFilePath;
if( ! is_dir($this->sPath . 'processmaker' . PATH_SEP . $sFilePath) ) {
//if we are updating or deleting a file
if( file_exists($this->sPath . 'processmaker' . PATH_SEP . $sFilePath) ) {
if( file_exists($targetFileName) ) {
if( ! is_writable($targetFileName) ) {
throw (new Exception("File $targetFileName is not writable."));
}
} else {
//verify parent folder, and ask if that folder is writable
$auxDir = explode('/', $targetFileName);
array_pop($auxDir);
$parentDir = implode('/', $auxDir);
if( ! is_dir($parentDir) ) {
//throw (new Exception("File $parentDir is an invalid directory."));
G::mk_dir($parentDir);
}
if( ! is_writable($parentDir) ) {
throw (new Exception("Directory $parentDir is not writable."));
}
}
} else {
//delete unused files
if( file_exists($targetFileName) && ! is_writable($targetFileName) ) {
throw (new Exception("File $targetFileName is not writable."));
}
}
} else {
$dirName = PATH_TRUNK . $sFilePath;
if( $dirName[strlen($dirName) - 1] == '/' )
$dirName = substr($dirName, 0, strlen($dirName) - 1);
$auxDir = explode('/', $dirName);
array_pop($auxDir);
$parentDir = implode('/', $auxDir);
if( file_exists($dirName) ) {
if( is_writable($dirName) ) {
//print "e. ok $dirName <br>";
} else {
throw (new Exception("$dirName is not writable"));
}
} else {
if( is_writable($parentDir) ) {
mkdir($dirName, 0777);
} else {
throw (new Exception("$dirName does not exist and parent folder $parentDir is not writable"));
}
}
}
}
}
//processing list file files.lst
if( $this->sUpgradeFileList != '' ) {
$bCopySchema = true;
$oFile = fopen($this->sUpgradeFileList, 'r');
while( $sLine = trim(fgets($oFile)) ) {
$action = substr($sLine, 0, 1);
$sLine = substr($sLine, 1);
$aAux = explode(PATH_SEP, $sLine);
array_shift($aAux);
$sFilePath = implode(PATH_SEP, $aAux);
$targetFileName = PATH_TRUNK . $sFilePath;
if( strtoupper($action) != 'D'){
if( ! is_dir($this->sPath . 'processmaker' . PATH_SEP . $sFilePath) ) {
if( file_exists($this->sPath . 'processmaker' . PATH_SEP . $sFilePath) ) {
if( strpos($sFilePath, 'schema.xml') !== false && $bCopySchema ) {
$bCopySchema = false;
$sOldSchema = str_replace('schema.xml', 'schema_' . date('Ymd') . '.xml', PATH_TRUNK . $sFilePath);
$this->pm_copy(PATH_TRUNK . $sFilePath, $sOldSchema);
}
if( file_exists($targetFileName) ) {
if( is_writable($targetFileName) ) {
$this->pm_copy($this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName);
@chmod($targetFileName, 0666);
} else
throw (new Exception("Failed to open file: Permission denied in $targetFileName."));
} else {
$this->pm_copy($this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName);
@chmod($targetFileName, 0666);
}
} else { //delete unused files
if( file_exists($targetFileName) ) {
@unlink($targetFileName);
}
}
} else {
if( ! file_exists(PATH_TRUNK . $sFilePath) ) {
mkdir(PATH_TRUNK . $sFilePath, 0777);
}
}
} else if( file_exists(PATH_TRUNK . $sFilePath) && $sFilePath != 'workflow/engine/gulliver' ) {
@unlink(PATH_TRUNK . $sFilePath);
}
}
}
//end files copied.
$missedFiles = '';
$distinctFiles = '';
$missed = 0;
$distinct = 0;
//checking files of this installation server with the files in Repository Code.
if( $sCheckListFile != '' ) {
$fp = fopen($sCheckListFile, 'r');
while( ! feof($fp) ) {
$line = explode(' ', fgets($fp));
if( count($line) == 3 ) {
$file = PATH_TRUNK . trim($line[2]);
if( is_readable($file) ) {
$size = sprintf("%07d", filesize($file));
$checksum = sprintf("%010u", crc32(file_get_contents($file)));
if( ! ($line[0] == $size && $line[1] == $checksum) && substr($file, - 4) != '.xml' ) {
$distinctFiles .= $file . "\n";
$distinct ++;
}
} else {
$missedFiles .= $file . "\n";
$missed ++;
}
}
}
fclose($fp);
}
if( $missed > 0 )
$aErrors[] = "Warning: there are $missed missed files. ";
$aErrors[] = $missedFiles;
if( $distinct > 0 ) {
$aErrors[] = "Warning: there are $distinct files with differences. ";
$aErrors[] = $distinctFiles;
}
//now include the files and classes needed for upgrade databases, dont move this files, because we
//are getting the last files in this point. Even the files was in the patch we will take the new ones.
include PATH_METHODS . PATH_SEP . 'setup' . PATH_SEP . 'upgrade_RBAC.php';
G::LoadClass('languages');
G::LoadSystem('database_mysql');
$bForceXml = true;
$bParseSchema = true;
$bParseSchemaRBAC = true;
$oDirectory = dir(PATH_DB);
//count db.php files ( workspaces )
$aWorkspaces = array ();
while( ($sObject = $oDirectory->read()) ) {
if( is_dir(PATH_DB . $sObject) && substr($sObject, 0, 1) != '.' && file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php') ) {
$aWorkspaces[] = $sObject;
}
}
$aUpgradeData = array ();
$aUpgradeData['workspaces'] = $aWorkspaces;
$aUpgradeData['wsQuantity'] = count($aWorkspaces);
$aUpgradeData['sPoFile'] = $sPoFile;
$aUpgradeData['bForceXmlPoFile'] = true;
$aUpgradeData['sSchemaFile'] = $sSchemaFile;
$aUpgradeData['sSchemaRBACFile'] = $sSchemaRBACFile;
file_put_contents(PATH_DATA . 'log' . PATH_SEP . "upgrade.data.bin", serialize($aUpgradeData));
$sSchemaFile = '';
$sPoFile = '';
$sSchemaRBACFile = '';
$oDirectory = dir(PATH_DB);
while( ($sObject = $oDirectory->read()) ) {
if( is_dir(PATH_DB . $sObject) && substr($sObject, 0, 1) != '.' ) {
if( file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php') ) {
eval($this->getDatabaseCredentials(PATH_DB . $sObject . PATH_SEP . 'db.php'));
}
$aEnvironmentsUpdated[] = $sObject;
$aEnvironmentsDiff[] = $sObject;
}
}
$oDirectory->close();
@unlink(PATH_CORE . 'config/_databases_.php');
//clean up smarty directory
$oDirectory = dir(PATH_SMARTY_C);
while( $sFilename = $oDirectory->read() ) {
if( ($sFilename != '.') && ($sFilename != '..') ) {
@unlink(PATH_SMARTY_C . PATH_SEP . $sFilename);
}
}
//clean up xmlform folders
$sDir = PATH_C . 'xmlform';
if( file_exists($sDir) && is_dir($sDir) ) {
$oDirectory = dir($sDir);
while( $sObjectName = $oDirectory->read() ) {
if( ($sObjectName != '.') && ($sObjectName != '..') ) {
if( is_dir($sDir . PATH_SEP . $sObjectName) ) {
$this->rm_dir($sDir . PATH_SEP . $sObjectName);
}
}
}
$oDirectory->close();
}
//changing the PM_VERSION according the patch file name
$oFile = fopen(PATH_METHODS . 'login/version-pmos.php', 'w+');
if( isset($this->sRevision) && $this->sRevision != '' ) {
fwrite($oFile, "<?\n define ( 'PM_VERSION' , str_replace ( ' ','', '1.6-" . $this->sRevision . "' ));\n?>");
} else {
fwrite($oFile, "<?\n define ( 'PM_VERSION' , str_replace ( ' ','', 'unknow' ));\n?>");
}
fclose($oFile);
$ver = explode("-", $this->sRevision);
$this->aErrors = $aErrors;
$this->aWorkspaces = $aWorkspaces;
return $ver;
}
/**
* This function does to clean up to the upgrate directory
*
*
* @name cleanupUpgradeDirectory
*
* @param
* @return array
*/
function cleanupUpgradeDirectory()
{
$this->rm_dir(PATH_DATA . 'upgrade' . PATH_SEP . 'processmaker');
}
/**
* This function removes a directory
*
*
* @name rm_dir
*
* @param string $dirName
* @return void
*/
function rm_dir($dirName)
{
if( empty($dirName) ) {
return;
}
if( file_exists($dirName) ) {
if( ! is_readable($dirName) ) {
throw (new Exception("directory '$dirName' is not readable"));
}
$dir = dir($dirName);
while( $file = $dir->read() ) {
if( $file != '.' && $file != '..' ) {
if( is_dir($dirName . PATH_SEP . $file) ) {
$this->rm_dir($dirName . PATH_SEP . $file);
} else {
//@unlink($dirName. PATH_SEP .$file) or die('File '.$dirName. PATH_SEP .$file.' couldn\'t be deleted!');
@unlink($dirName . PATH_SEP . $file);
}
}
}
$folder = opendir($dirName . PATH_SEP . $file);
closedir($folder);
@rmdir($dirName . PATH_SEP . $file);
} else {
//
}
}
/**
* This function creates a directory
*
*
* @name pm_copy
*
* @param string $source
* @param string $target
* @return void
*/
function pm_copy($source, $target)
{
if( ! is_dir(dirname($target)) ) {
G::mk_dir(dirname($target));
}
if( ! copy($source, $target) ) {
krumo($source);
krumo($target);
}
}
/**
* This function gets info about db
*
*
* @name getDatabaseCredentials
*
* @param string $dbFile
* @return $sContent
*/
function getDatabaseCredentials($dbFile)
{
$sContent = file_get_contents($dbFile);
$sContent = str_replace('<?php', '', $sContent);
$sContent = str_replace('<?', '', $sContent);
$sContent = str_replace('?>', '', $sContent);
$sContent = str_replace('define', '', $sContent);
$sContent = str_replace("('", '$', $sContent);
$sContent = str_replace("',", '=', $sContent);
$sContent = str_replace(");", ';', $sContent);
return $sContent;
}
}// end System class

View File

@@ -0,0 +1,652 @@
<?php
/**
* class.tasks.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.
*
*/
require_once 'classes/model/GroupUser.php';
require_once 'classes/model/Groupwf.php';
require_once 'classes/model/ObjectPermission.php';
require_once 'classes/model/Process.php';
require_once 'classes/model/Route.php';
require_once 'classes/model/Step.php';
require_once 'classes/model/StepTrigger.php';
require_once 'classes/model/Task.php';
require_once 'classes/model/TaskUser.php';
require_once 'classes/model/Users.php';
/**
* Tasks - Tasks class
* @package ProcessMaker
* @author Julio Cesar Laura Avenda<64>o
* @copyright 2007 COLOSA
*/
class Tasks
{
/**
* Get the assigned groups of a task
* @param string $sTaskUID
* @param integer $iType
* @return array
*/
public function getGroupsOfTask($sTaskUID, $iType)
{
try {
$aGroups = array();
$oCriteria = new Criteria('workflow');
$oCriteria->addJoin(GroupwfPeer::GRP_UID, TaskUserPeer::USR_UID, Criteria::LEFT_JOIN);
$oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID);
$oCriteria->add(TaskUserPeer::TU_TYPE, $iType);
$oCriteria->add(TaskUserPeer::TU_RELATION, 2);
$oCriteria->add(GroupwfPeer::GRP_STATUS, 'ACTIVE');
$oDataset = GroupwfPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aGroups[] = $aRow;
$oDataset->next();
}
return $aGroups;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Get all tasks for any Process
* @param string $sProUid
* @return array
*/
public function getAllTasks($sProUid)
{
try {
$aTasks = array();
$oCriteria = new Criteria('workflow');
$oCriteria->add(TaskPeer::PRO_UID, $sProUid);
$oDataset = TaskPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oTask = new Task();
$aTasks[] = $oTask->Load($aRow['TAS_UID']);
$oDataset->next();
}
return $aTasks;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* creates row tasks from an Task Array
* @param string $aTasks
* @return array
*/
public function createTaskRows( $aTask )
{
foreach ( $aTask as $key => $row ) {
$oTask = new Task();
if($oTask->taskExists ($row['TAS_UID']))
$oTask->remove($row['TAS_UID']);
$res = $oTask->createRow($row);
}
return;
}
/**
* updates row tasks from an Task Array
* @param string $aTasks
* @return array
*/
public function updateTaskRows( $aTask )
{
foreach ( $aTask as $key => $row ) {
$oTask = new Task();
if($oTask->taskExists ($row['TAS_UID']))
$oTask->remove($row['TAS_UID']);
else
$res = $oTask->update($row);
}
return;
}
/**
* Get all Routes for any Process
* @param string $sProUid
* @return array
*/
public function getAllRoutes($sProUid)
{
try {
$aRoutes = array();
$oCriteria = new Criteria('workflow');
$oCriteria->add(RoutePeer::PRO_UID, $sProUid);
$oDataset = RoutePeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aRoutes[] = $aRow;
$oDataset->next();
}
return $aRoutes;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* creates row tasks from an Route Array
* @param string $aTasks
* @return array
*/
public function createRouteRows( $aRoutes )
{
foreach ( $aRoutes as $key => $row ) {
$oRoute = new Route();
//unset ($row['ROU_UID']);
if($oRoute->routeExists($row['ROU_UID']))
$oRoute->remove($row['ROU_UID']);
$res = $oRoute->create($row);
}
return;
}
/**
* updates row tasks from an Route Array
* @param string $aTasks
* @return array
*/
public function updateRouteRows( $aRoutes )
{
foreach ( $aRoutes as $key => $row ) {
$oRoute = new Route();
//krumo ($row);
if(is_array($oRoute->load($row['ROU_UID'])))
$oRoute->remove($row['ROU_UID']);
else
$res = $oRoute->update($row);
}
return;
}
/**
* Get the assigned users of a task
* @param string $sTaskUID
* @param integer $iType
* @return array
*/
public function getUsersOfTask($sTaskUID, $iType)
{
try {
$aUsers = array();
$oCriteria = new Criteria('workflow');
$oCriteria->addJoin(UsersPeer::USR_UID, TaskUserPeer::USR_UID, Criteria::LEFT_JOIN);
$oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID);
$oCriteria->add(TaskUserPeer::TU_TYPE, $iType);
$oCriteria->add(TaskUserPeer::TU_RELATION, 1);
$oDataset = UsersPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aUsers[] = $aRow;
$oDataset->next();
}
return $aUsers;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Delete a task
* @param string $sTaskUID
* @return void
*/
function deleteTask($sTaskUID = '')
{
try {
//Instance classes
$oTask = new Task();
$oTasks = new Tasks();
$oTaskUser = new TaskUser();
$oStep = new Step();
$oStepTrigger = new StepTrigger();
//Get task information
$aFields = $oTask->load($sTaskUID);
//Delete routes
$oTasks->deleteAllRoutesOfTask($aFields['PRO_UID'], $sTaskUID, true);
//Delete the users assigned to task
$oCriteria = new Criteria('workflow');
$oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID);
$oDataset1 = TaskUserPeer::doSelectRS($oCriteria);
$oDataset1->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset1->next();
while ($aRow1 = $oDataset1->getRow()) {
$oTaskUser->remove($aRow1['TAS_UID'], $aRow1['USR_UID'], $aRow1['TU_TYPE'], $aRow1['TU_RELATION']);
$oDataset1->next();
}
//Delete the steps of task
$oCriteria = new Criteria('workflow');
$oCriteria->add(StepPeer::TAS_UID, $sTaskUID);
$oDataset1 = StepPeer::doSelectRS($oCriteria);
$oDataset1->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset1->next();
while ($aRow1 = $oDataset1->getRow()) {
//Delete the triggers assigned to step
/*$oCriteria = new Criteria('workflow');
$oCriteria->add(StepTriggerPeer::STEP_UID, $aRow1['STEP_UID']);
$oDataset2 = StepTriggerPeer::doSelectRS($oCriteria);
$oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset2->next();
while ($aRow2 = $oDataset2->getRow()) {
$oStepTrigger->remove($aRow2['STEP_UID'], $aRow2['TAS_UID'], $aRow2['TRI_UID'], $aRow2['ST_TYPE']);
$oDataset2->next();
}*/
$oStep->remove($aRow1['STEP_UID']);
$oDataset1->next();
}
//Delete step triggers
$oCriteria = new Criteria('workflow');
$oCriteria->add(StepTriggerPeer::TAS_UID, $sTaskUID);
StepTriggerPeer::doDelete($oCriteria);
//Delete permissions
$oCriteria = new Criteria('workflow');
$oCriteria->add(ObjectPermissionPeer::TAS_UID, $sTaskUID);
ObjectPermissionPeer::doDelete($oCriteria);
$oCriteria = new Criteria('workflow');
$oCriteria->add(ObjectPermissionPeer::OP_TASK_SOURCE, $sTaskUID);
ObjectPermissionPeer::doDelete($oCriteria);
//Delete task
$oTask->remove($sTaskUID);
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Delete all routes from a task
* @param string $sProcessUID
* @param string $sTaskUID
* @return boolean
*/
public function deleteAllRoutesOfTask($sProcessUID = '', $sTaskUID = '', $bAll = false)
{
try {
$oProcess = new Process();
$aFields = $oProcess->load($sProcessUID);
$oTask = new Task();
$aFields = $oTask->load($sTaskUID);
$oCriteria = new Criteria('workflow');
$oCriteria->add(RoutePeer::PRO_UID, $sProcessUID);
$oCriteria->add(RoutePeer::TAS_UID, $sTaskUID);
RoutePeer::doDelete($oCriteria);
if ($bAll) {
$oCriteria = new Criteria('workflow');
$oCriteria->add(RoutePeer::PRO_UID, $sProcessUID);
$oCriteria->add(RoutePeer::ROU_NEXT_TASK, $sTaskUID);
RoutePeer::doDelete($oCriteria);
}
return true;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Assign a user to task
* @param string $sTaskUID
* @param string $sUserUID
* @param string $iType
* @return integer
*/
public function assignUser($sTaskUID = '', $sUserUID = '', $iType = '')
{
try {
$oTaskUser = new TaskUser();
return $oTaskUser->create(array('TAS_UID' => $sTaskUID, 'USR_UID' => $sUserUID, 'TU_TYPE' => $iType, 'TU_RELATION' => 1));
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Assign a group to task
* @param string $sTaskUID
* @param string $sGroupUID
* @param string $iType
* @return integer
*/
public function assignGroup($sTaskUID = '', $sGroupUID = '', $iType = '')
{
try {
$oTaskUser = new TaskUser();
/*$oCriteria = new Criteria('workflow');
$oCriteria->add(GroupUserPeer::GRP_UID, $sGroupUID);
$oDataset = GroupUserPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aGroupUser = $oDataset->getRow()) {
$oCriteria = new Criteria('workflow');
$oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID);
$oCriteria->add(TaskUserPeer::USR_UID, $aGroupUser['USR_UID']);
$oDataset2 = TaskUserPeer::doSelectRS($oCriteria);
$oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset2->next();
$aRow = $oDataset2->getRow();
if (!is_array($aRow)) {
$this->assignUser($sTaskUID, $aGroupUser['USR_UID'], $iType);
}
$oDataset->next();
}*/
return $oTaskUser->create(array('TAS_UID' => $sTaskUID, 'USR_UID' => $sGroupUID, 'TU_TYPE' => $iType, 'TU_RELATION' => 2));
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* of the assign user of all the tasks
* @param string $sUserUID
* @return void
*/
public function ofToAssignUserOfAllTasks($sUserUID = '')
{
try {
$oCriteria = new Criteria('workflow');
$oCriteria->add(TaskUserPeer::USR_UID, $sUserUID);
TaskUserPeer::doDelete($oCriteria);
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Of to assign a user from a task
* @param string $sTaskUID
* @param string $sUserUID
* @param integer $iType
* @return boolean
*/
public function ofToAssignUser($sTaskUID = '', $sUserUID = '', $iType = 0)
{
try {
$oTaskUser = new TaskUser();
$oTaskUser->remove($sTaskUID, $sUserUID, $iType, 1);
return true;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Of to assign a group from a task
* @param string $sTaskUID
* @param string $sGroupUID
* @param integer $iType
* @return boolean
*/
public function ofToAssignGroup($sTaskUID = '', $sGroupUID = '', $iType = 0)
{
try {
$oTaskUser = new TaskUser();
$oCriteria = new Criteria('workflow');
$oCriteria->add(GroupUserPeer::GRP_UID, $sGroupUID);
$oDataset = GroupUserPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aGroupUser = $oDataset->getRow()) {
$oCriteria = new Criteria('workflow');
$oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID);
$oCriteria->add(TaskUserPeer::USR_UID, $aGroupUser['USR_UID']);
$oDataset2 = TaskUserPeer::doSelectRS($oCriteria);
$oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset2->next();
$aRow = $oDataset2->getRow();
if (is_array($aRow)) {
$this->ofToAssignUser($sTaskUID, $aGroupUser['USR_UID'], $iType);
}
$oDataset->next();
}
return $oTaskUser->remove($sTaskUID, $sGroupUID, $iType, 2);
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Get the assigned steps of a task
* @param string $sTaskUID
* @return array
*/
public function getStepsOfTask($sTaskUID)
{
try {
$aSteps = array();
$oCriteria = new Criteria('workflow');
$oCriteria->add(StepPeer::TAS_UID, $sTaskUID);
$oCriteria->addAscendingOrderByColumn(StepPeer::STEP_POSITION);
$oDataset = StepPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aSteps[] = $aRow;
$oDataset->next();
}
return $aSteps;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Return if exists building elements to add steps
* @param string $sProcessUID
* @return boolean
*/
public function existsBuildingElements($sProcessUID)
{
try {
$oCriteria = new Criteria('workflow');
//$oCriteria->add(StepPeer::PRO_UID, $sProcessUID);
//$oDataset = StepPeer::doSelectRS($oCriteria);
//$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
//$oDataset->next();
return true;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Get all tasks for any Process
* @param string $sProUid
* @return array
*/
public function getStartingTaskForUser($sProUid, $sUsrUid)
{
try {
$aTasks = array();
$oCriteria = new Criteria('workflow');
$oCriteria->add(TaskPeer::PRO_UID, $sProUid);
//$oCriteria->add(TaskPeer::TAS_USER, $sUsrUid);
$oCriteria->add(TaskPeer::TAS_START, 'TRUE');
$oDataset = TaskPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oTask = new Task();
$aTasks[] = $oTask->Load($aRow['TAS_UID']);
$oDataset->next();
}
return $aTasks;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Verify the user assig in any task
* @param string $sTaskUID
* @return array
*/
public function assignUsertoTask($sTaskUID)
{
try {
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(TaskUserPeer::USR_UID);
$oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID);
$oDataset = TaskUserPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
if(is_array($aRow))
return 1;
else
return 0;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Verify the user assig in task
* @param string $sUsrUid, $sTaskUID
* @return array
*/
public function verifyUsertoTask($sUsrUid, $sTaskUID)
{
try {
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(TaskUserPeer::USR_UID);
$oCriteria->addSelectColumn(TaskUserPeer::TAS_UID);
$oCriteria->addSelectColumn(TaskUserPeer::TU_RELATION);
$oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID);
$oCriteria->add(TaskUserPeer::USR_UID, $sUsrUid);
$oDataset = TaskUserPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
if(is_array($aRow))
return $aRow;
else
return $aRow;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Get tasks that the usser is assigned
* @param string $sUsrUID
* @return array
*/
public function getTasksThatUserIsAssigned($sUserUID)
{
try {
$aTasks = array();
$oCriteria = new Criteria('workflow');
$oCriteria->add(TaskUserPeer::USR_UID, $sUserUID);
$oCriteria->add(TaskUserPeer::TU_RELATION, 1);
$oDataset = TaskUserPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aTasks[] = $aRow['TAS_UID'];
$oDataset->next();
}
$aGroups = array();
$oCriteria = new Criteria();
$oCriteria->add(GroupwfPeer::GRP_UID, '', Criteria::NOT_EQUAL);
$oCriteria->add(GroupUserPeer::USR_UID, $sUserUID);
$oCriteria->add(GroupwfPeer::GRP_STATUS, 'ACTIVE');
$oCriteria->addJoin(GroupUserPeer::GRP_UID, GroupwfPeer::GRP_UID, Criteria::LEFT_JOIN);
$oDataset = GroupwfPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aGroups[] = $aRow['GRP_UID'];
$oDataset->next();
}
$oCriteria = new Criteria('workflow');
$oCriteria->add(TaskUserPeer::USR_UID, $aGroups, Criteria::IN);
$oCriteria->add(TaskUserPeer::TU_RELATION, 2);
$oDataset = TaskUserPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
if (!in_array($aRow['TAS_UID'], $aTasks)) {
$aTasks[] = $aRow['TAS_UID'];
}
$oDataset->next();
}
return $aTasks;
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Get Routes for any Process and any Task
* @param string $sProUid, $sTaskUid
* @return array
* by Everth
*/
public function getRoute($sProUid, $sTaskUid)
{
try {
$aRoutes = array();
$oCriteria = new Criteria('workflow');
$oCriteria->add(RoutePeer::PRO_UID, $sProUid);
$oCriteria->add(RoutePeer::TAS_UID, $sTaskUid);
$oDataset = RoutePeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aRoutes[] = $aRow;
$oDataset->next();
}
return $aRoutes;
}
catch (Exception $oError) {
throw($oError);
}
}
}
?>

View File

@@ -0,0 +1,159 @@
<?php
/**
* class.toolBar.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.
*
*/
/**
* ToolBar - ToolBar class
* @package ProcessMaker
*/
class ToolBar extends form
{
var $type = 'toolbar';
var $align = 'left';
}
/**
* XmlForm_Field_ToolBar - XmlForm_Field_ToolBar class
* @package ProcessMaker
*/
class XmlForm_Field_ToolBar extends XmlForm_Field
{
var $xmlfile = '';
var $type = 'toolbar';
var $toolBar;
var $home='';
var $withoutLabel = true;
/**
* Constructor of the class XmlForm_Field_ToolBar
* @param string $xmlNode
* @param string $lang
* @param string $home
* @param string $owner
* @return void
*/
function XmlForm_Field_ToolBar($xmlNode, $lang='en', $home='', $owner)
{
parent::XmlForm_Field($xmlNode, $lang, $home, $owner);
$this->home = $home;
}
/**
* Prints the ToolBar
* @param string $value
* @return string
*/
function render( $value )
{
$this->toolBar = new toolBar( $this->xmlfile , $this->home );
$template = PATH_CORE . 'templates/' . $this->type . '.html';
$out = $this->toolBar->render( $template , $scriptCode ) ;
$oHeadPublisher =& headPublisher::getSingleton();
$oHeadPublisher->addScriptFile( $this->toolBar->scriptURL );
$oHeadPublisher->addScriptCode( $scriptCode );
return $out;
}
}
/**
* XmlForm_Field_toolButton - XmlForm_Field_toolButton class
* @package ProcessMaker
*/
class XmlForm_Field_toolButton extends XmlForm_Field
{
var $file = '';
var $fileAlt = '';
var $url = '';
var $urlAlt = '';
var $home = 'public_html';
/* types of buttons:
* image
* text
* image/text
* text/image
*/
var $buttonType = 'image';
var $withoutLabel = false;
var $buttonStyle = '';
/*$hoverMethod : back | switch*/
var $hoverMethod='back';
/**
* Prints the components of the toolBar
* @param string $value
* @return string
*/
function render( $value )
{
$url = $this->file;
if ($this->home === "methods")
$url = G::encryptlink( SYS_URI . $url );
if ($this->home === "public_html")
$url ='/' . $url ;
$urlAlt = $this->fileAlt;
if ($this->fileAlt!=='') {
if ($this->home === "methods")
$urlAlt = G::encryptlink( SYS_URI . $urlAlt );
if ($this->home === "public_html")
$urlAlt ='/' . $urlAlt ;
}
$this->url=$url;
$this->urlAlt=$urlAlt;
switch($this->buttonType){
case 'image':
$html='';
if ($this->hoverMethod==='back') {
$html='<img src="'.htmlentities( $url, ENT_QUOTES, 'utf-8').'"'.
(($this->style)?' style="'.$this->style.'"':'').' onmouseover=\'backImage(this,"url('.htmlentities( $urlAlt, ENT_QUOTES, 'utf-8').') no-repeat")\' onmouseout=\'backImage(this,"")\' title=\'' . addslashes($this->label) . '\' />';
}
elseif($this->hoverMethod==='switch'){
$html='<img src="'.htmlentities( $url, ENT_QUOTES, 'utf-8').'"'.
(($this->style)?' style="'.$this->style.'"':'').' onmouseover=\'switchImage(this,"'.htmlentities( $url, ENT_QUOTES, 'utf-8').'","'.htmlentities( $urlAlt, ENT_QUOTES, 'utf-8').'")\' onmouseout=\'switchImage(this,"'.htmlentities( $url, ENT_QUOTES, 'utf-8').'","'.htmlentities( $urlAlt, ENT_QUOTES, 'utf-8').'")\'/>';
}
else {
$html='<img src="'.htmlentities( $url, ENT_QUOTES, 'utf-8').'"'.
(($this->style)?' style="'.$this->style.'"':'').'/>';
}
break;
case 'text':
$html=$this->htmlentities($this->label, ENT_QUOTES,'utf-8');
break;
case 'image/text':
$html='<img src="'.htmlentities( $url, ENT_QUOTES, 'utf-8').'"'.
(($this->style)?' style="'.$this->style.'"':'').'/><br/>'.
$this->htmlentities($this->label, ENT_QUOTES,'utf-8');
break;
case 'text/image':
$html=$this->htmlentities($this->label, ENT_QUOTES,'utf-8').
'<br/><img src="'.htmlentities( $url, ENT_QUOTES, 'utf-8').'"'.
(($this->style)?' style="'.$this->style.'"':'').'/>';
break;
}
return '<A class="toolButton" '.
(($this->buttonStyle)?' style="'.$this->buttonStyle.'"':'').
(($this->onclick)?' onclick="'. htmlentities($this->onclick, ENT_QUOTES,'utf-8').'"':'').
'>'.$html.'</A>';
}
}
?>

View File

@@ -0,0 +1,160 @@
<?php
/**
* @author Hugo Loza <hugo@colosa.com>
*
* This class Helps registering and implementing Wizard for Triggers
*
*/
G::LoadThirdParty ( 'html2ps_pdf/classes', 'include' );
G::LoadThirdParty ( 'html2ps_pdf/classes/org/active-link/doc', 'PHPClass' );
class triggerLibrary {
private $_aTriggerClasses_ = array ();
private static $instance = NULL;
/**
* __construct
*
* @return void
*/
function __construct()
{
//Initialize the Library and register the Default
$this->registerFunctionsFileToLibrary ( PATH_CORE . "classes" . PATH_SEP . "class.pmFunctions.php", "ProcessMaker Functions" );
//Register all registered PLugin Functions
if (class_exists ( 'folderData' )) {
//$folderData = new folderData($sProUid, $proFields['PRO_TITLE'], $sAppUid, $Fields['APP_TITLE'], $sUsrUid);
$oPluginRegistry = &PMPluginRegistry::getSingleton ();
$aAvailablePmFunctions = $oPluginRegistry->getPmFunctions ();
foreach ( $aAvailablePmFunctions as $key => $class ) {
$filePlugin = PATH_PLUGINS . $class . PATH_SEP . 'classes' . PATH_SEP . 'class.pmFunctions.php';
if (file_exists ( $filePlugin ))
$this->registerFunctionsFileToLibrary ( $filePlugin, "ProcessMaker Functions" );
}
}
//Add External Triggers
$dir=G::ExpandPath( "classes" ).'triggers';
$filesArray=array();
if (file_exists($dir)){
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if(($file!=".")&&($file!="..")){
$this->registerFunctionsFileToLibrary ($dir.PATH_SEP. $file, "ProcessMaker External Functions");
}
}
closedir($handle);
}
}
}
/**
* &getSingleton
*
* @return self::$instance;
*/
function &getSingleton()
{
if (self::$instance == NULL) {
self::$instance = new triggerLibrary ( );
}
return self::$instance;
}
/**
* serializeInstance
*
* @return serialize ( self::$instance );
*/
function serializeInstance()
{
return serialize ( self::$instance );
}
/**
* unSerializeInstance
*
* @param integer $serialized
* @return void
*/
function unSerializeInstance($serialized)
{
if (self::$instance == NULL) {
self::$instance = new PMPluginRegistry ( );
}
$instance = unserialize ( $serialized );
self::$instance = $instance;
}
/**
* registerFunctionsFileToLibrary
*
* @param string $filePath
* @param string $libraryName
* @return void
*/
function registerFunctionsFileToLibrary($filePath, $libraryName)
{
$aLibrary = $this->getMethodsFromLibraryFile ( $filePath );
$aLibrary->libraryFile = $filePath;
$aLibrary->libraryName = $libraryName;
if(isset($aLibrary->info['className'])){
$this->_aTriggerClasses_ [$aLibrary->info['className']] = $aLibrary;
}
}
/**
* getMethodsFromLibraryFile
*
* @param string $file
* @return object(PHPClass) $parsedLibrary
*/
function getMethodsFromLibraryFile($file)
{
// parse class comments from file
$parsedLibrary = new PHPClass ( );
//$success = $parsedLibrary->parseFromFile ( PATH_CORE . "classes" . PATH_SEP . $file );
$success = $parsedLibrary->parseFromFile ( $file );
return $parsedLibrary;
}
/**
* getRegisteredClasses
*
* @return array ($this->_aTriggerClasses_)
*/
function getRegisteredClasses()
{
return ($this->_aTriggerClasses_);
}
/**
* getLibraryDefinition
*
* @param string $libraryClassName
* @return array ($this->_aTriggerClasses_[$libraryClassName])
*/
function getLibraryDefinition($libraryClassName)
{
return ($this->_aTriggerClasses_[$libraryClassName]);
}
/**
* __destruct
*
* @return void
*/ function __destruct()
{
//TODO - Insert your code here
}
}
?>

View File

@@ -0,0 +1,992 @@
<?php
require_once "HTTP/WebDAV/Server.php";
require_once "System.php";
/**
* ProcessMaker Filesystem access using WebDAV
*
* @access public
*/
class ProcessMakerWebDav extends HTTP_WebDAV_Server
{
/**
* Root directory for WebDAV access
*
* Defaults to webserver document root (set by ServeRequest)
*
* @access private
* @var string
*/
var $base = "";
/**
* Serve a webdav request
*
* @access public
* @param string
*/
function ServeRequest($base = false) {
//$this->base = '/';
$this->uriBase = '/sys' . SYS_SYS . '/' . SYS_LANG . '/' . SYS_SKIN . '/services/webdav/';
// let the base class do all the work
parent::ServeRequest();
}
/**
* No authentication is needed here
*
* @access private
* @param string HTTP Authentication type (Basic, Digest, ...)
* @param string Username
* @param string Password
* @return bool true on successful authentication
*/
function check_auth($type, $user, $pass)
{
return true;
}
/**
* PROPFIND method handler
*
* @param array general parameter passing array
* @param array return array for file properties
* @return bool true on success
*/
function PROPFIND(&$options, &$files)
{
$paths = $this->paths;
// prepare property array
$files["files"] = array();
$pathClasses = PATH_DB . PATH_SEP . SYS_SYS . PATH_SEP . 'classes' . PATH_SEP;
if ( count($paths) == 0 && is_dir( $pathClasses ) ) {
$props = array ();
$props[] = $this->mkprop("displayname", 'Classes' );
$props[] = $this->mkprop("creationdate", filectime($pathClasses) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathClasses) );
$props[] = $this->mkprop("lastaccessed", filemtime($pathClasses) );
$props[] = $this->mkprop("resourcetype", 'collection' );
$props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' );
$files["files"][] = array ( 'path' => 'classes' , 'props' => $props);
}
if ( count($paths) > 0 && $paths[0] == 'classes' && is_dir( $pathClasses ) ) {
// try to open directory
$handle = @opendir($pathClasses);
if ($handle) {
while ($filename = readdir($handle)) {
$ext = array_pop ( explode ( '.', $filename) );
if ($filename != "." && $filename != ".." && !is_dir($pathClasses.$filename) && $ext == 'php' ) {
$props = array ();
$props[] = $this->mkprop("displayname", $filename );
$props[] = $this->mkprop("creationdate", filectime($pathClasses.$filename) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathClasses.$filename) );
$props[] = $this->mkprop("getetag", fileatime($pathClasses.$filename) );
$props[] = $this->mkprop("lastaccessed", filemtime($pathClasses.$filename) );
$props[] = $this->mkprop("resourcetype", '' );
$props[] = $this->mkprop("getcontenttype", 'text/plain' );
$props[] = $this->mkprop("getcontentlength", filesize($pathClasses.$filename) );
if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) )
$files["files"][] = array ( 'path' => "classes/$filename" , 'props' => $props);
}
}
}
}//path classes
$pathProcesses = PATH_DB . SYS_SYS . PATH_SEP ;
if ( count($paths) == 0 && is_dir( $pathProcesses ) ) {
$props = array ();
$props[] = $this->mkprop("displayname", 'Processes' );
$props[] = $this->mkprop("creationdate", filectime($pathProcesses) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathProcesses) );
$props[] = $this->mkprop("resourcetype", 'collection' );
$props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' );
$files["files"][] = array ( 'path' => 'processes' , 'props' => $props);
}
//list all active processes
if ( count($paths) == 1 && $paths[0] == 'processes' && is_dir( $pathProcesses ) ) {
// try to get the process directory list
G::LoadClass ( 'processMap');
G::LoadClass ( 'model/Process');
$oProcessMap = new processMap();
$oProcess = new Process();
$c = $oProcessMap->getConditionProcessList();
$oDataset = ProcessPeer::doSelectRS($c);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
if ($aRow['PRO_STATUS'] == 'ACTIVE' ) {
$aProcess = $oProcess->load($aRow['PRO_UID']);
$props = array ();
$props[] = $this->mkprop("displayname", $aProcess['PRO_TITLE'] );
$props[] = $this->mkprop("creationdate", filectime($pathProcesses) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathProcesses) );
$props[] = $this->mkprop("lastaccessed", filemtime($pathProcesses) );
$props[] = $this->mkprop("resourcetype", 'collection' );
$props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' );
$files["files"][] = array ( 'path' => "processes/". $aRow['PRO_UID'] , 'props' => $props);
}
$oDataset->next();
}
}//dir of processes
//content of any process ( the three major folders of Processes )
$pathXmlform = $pathProcesses . 'xmlForms' . PATH_SEP;
if ( count($paths) == 2 && $paths[0] == 'processes' && is_dir( $pathProcesses ) ) {
$props = array ();
$props[] = $this->mkprop("displayname", 'xmlforms' );
$props[] = $this->mkprop("creationdate", filectime($pathXmlform) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathXmlform) );
$props[] = $this->mkprop("lastaccessed", filemtime($pathXmlform) );
$props[] = $this->mkprop("resourcetype", 'collection' );
$props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' );
$files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/xmlforms' , 'props' => $props);
$props[] = $this->mkprop("displayname", 'mailTemplates' );
$props[] = $this->mkprop("creationdate", filectime($pathProcesses) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathProcesses) );
$props[] = $this->mkprop("lastaccessed", filemtime($pathProcesses) );
$props[] = $this->mkprop("resourcetype", 'collection' );
$props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' );
$files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/mailTemplates' , 'props' => $props);
$props[] = $this->mkprop("displayname", 'public_html' );
$props[] = $this->mkprop("creationdate", filectime($pathProcesses) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathProcesses) );
$props[] = $this->mkprop("lastaccessed", filemtime($pathProcesses) );
$props[] = $this->mkprop("resourcetype", 'collection' );
$props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' );
$files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/public_html' , 'props' => $props);
}//content of any processes
//list available xmlforms
if ( count($paths) == 3 && $paths[0] == 'processes' && $paths[2] == 'xmlforms' && is_dir( $pathXmlform ) ) {
$pathXmlform = $pathProcesses . 'xmlForms' . PATH_SEP . $paths[1] . PATH_SEP;
$handle = @opendir($pathXmlform);
if ($handle) {
while ($filename = readdir($handle)) {
$ext = array_pop ( explode ( '.', $filename) );
if ($filename != "." && $filename != ".." && !is_dir($pathXmlform.$filename) && ( $ext == 'xml' || $ext == 'html' ) ) {
$props = array ();
$props[] = $this->mkprop("displayname", $filename );
$props[] = $this->mkprop("creationdate", filectime($pathXmlform.$filename) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathXmlform.$filename) );
$props[] = $this->mkprop("getetag", fileatime($pathXmlform.$filename) );
$props[] = $this->mkprop("lastaccessed", filemtime($pathXmlform.$filename) );
$props[] = $this->mkprop("resourcetype", '' );
$props[] = $this->mkprop("getcontenttype", 'text/plain' );
$props[] = $this->mkprop("getcontentlength", filesize($pathXmlform.$filename) );
//if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) )
$files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/xmlforms/' . $filename , 'props' => $props);
}
}
}
}//content of xmlforms
//list available mailTemplates
$pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP;
if ( count($paths) == 3 && $paths[0] == 'processes' && $paths[2] == 'mailTemplates' && is_dir( $pathTemplates ) ) {
$pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP . $paths[1] . PATH_SEP;
$handle = @opendir($pathTemplates);
if ($handle) {
while ($filename = readdir($handle)) {
$ext = array_pop ( explode ( '.', $filename) );
if ($filename != "." && $filename != ".." && !is_dir($pathTemplates.$filename) /* && ( $ext == 'xml' || $ext == 'html' ) */ ) {
$props = array ();
$props[] = $this->mkprop("displayname", $filename );
$props[] = $this->mkprop("creationdate", filectime($pathTemplates.$filename) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathTemplates.$filename) );
$props[] = $this->mkprop("getetag", fileatime($pathTemplates.$filename) );
$props[] = $this->mkprop("lastaccessed", filemtime($pathTemplates.$filename) );
$props[] = $this->mkprop("resourcetype", '' );
$props[] = $this->mkprop("getcontenttype", 'text/plain' );
$props[] = $this->mkprop("getcontentlength", filesize($pathTemplates.$filename) );
//if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) )
$files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/mailTemplates/' . $filename , 'props' => $props);
}
}
}
}//content of mailTemplates
//list available public_html files
$pathPublic = $pathProcesses . 'public' . PATH_SEP;
if ( count($paths) == 3 && $paths[0] == 'processes' && $paths[2] == 'public_html' && is_dir( $pathTemplates ) ) {
$pathPublic = $pathProcesses . 'public' . PATH_SEP . $paths[1] . PATH_SEP;
$handle = @opendir($pathPublic);
if ($handle) {
while ($filename = readdir($handle)) {
$ext = array_pop ( explode ( '.', $filename) );
if ($filename != "." && $filename != ".." && !is_dir($pathPublic.$filename) /* && ( $ext == 'xml' || $ext == 'html' ) */ ) {
$props = array ();
$props[] = $this->mkprop("displayname", $filename );
$props[] = $this->mkprop("creationdate", filectime($pathPublic.$filename) );
$props[] = $this->mkprop("getlastmodified", filemtime($pathPublic.$filename) );
$props[] = $this->mkprop("getetag", fileatime($pathPublic.$filename) );
$props[] = $this->mkprop("lastaccessed", filemtime($pathPublic.$filename) );
$props[] = $this->mkprop("resourcetype", '' );
$props[] = $this->mkprop("getcontenttype", 'text/plain' );
$props[] = $this->mkprop("getcontentlength", filesize($pathPublic.$filename) );
//if ( count( $paths ) == 1 || ( count( $paths ) == 2 && $paths[1] == $filename ) )
$files["files"][] = array ( 'path' => 'processes/' . $paths[1] . '/public_html/' . $filename , 'props' => $props);
}
}
}
}//content of public_html files
/*
if ( 1 ) {
$props = array ();
$props[] = $this->mkprop("displayname", print_r ($pathPublic, 1) );
$props[] = $this->mkprop("creationdate", filectime( PATH_DB ) );
$props[] = $this->mkprop("getlastmodified", filemtime( PATH_DB ) );
$props[] = $this->mkprop("resourcetype", 'collection' );
$props[] = $this->mkprop("getcontenttype", 'httpd/unix-directory' );
$files["files"][] = array ( 'path' => '/' , 'props' => $props);
} */
// ok, all done
return true;
}
/**
* detect if a given program is found in the search PATH
*
* helper function used by _mimetype() to detect if the
* external 'file' utility is available
*
* @param string program name
* @param string optional search path, defaults to $PATH
* @return bool true if executable program found in path
*/
function _can_execute($name, $path = false)
{
// path defaults to PATH from environment if not set
if ($path === false) {
$path = getenv("PATH");
}
// check method depends on operating system
if (!strncmp(PHP_OS, "WIN", 3)) {
// on Windows an appropriate COM or EXE file needs to exist
$exts = array(".exe", ".com");
$check_fn = "file_exists";
} else {
// anywhere else we look for an executable file of that name
$exts = array("");
$check_fn = "is_executable";
}
// now check the directories in the path for the program
foreach (explode(PATH_SEPARATOR, $path) as $dir) {
// skip invalid path entries
if (!file_exists($dir)) continue;
if (!is_dir($dir)) continue;
// and now look for the file
foreach ($exts as $ext) {
if ($check_fn("$dir/$name".$ext)) return true;
}
}
return false;
}
/**
* try to detect the mime type of a file
*
* @param string file path
* @return string guessed mime type
*/
function _mimetype($fspath)
{
if (@is_dir($fspath)) {
// directories are easy
return "httpd/unix-directory";
} else if (function_exists("mime_content_type")) {
// use mime magic extension if available
$mime_type = mime_content_type($fspath);
} else if ($this->_can_execute("file")) {
// it looks like we have a 'file' command,
// lets see it it does have mime support
$fp = popen("file -i '$fspath' 2>/dev/null", "r");
$reply = fgets($fp);
pclose($fp);
// popen will not return an error if the binary was not found
// and find may not have mime support using "-i"
// so we test the format of the returned string
// the reply begins with the requested filename
if (!strncmp($reply, "$fspath: ", strlen($fspath)+2)) {
$reply = substr($reply, strlen($fspath)+2);
// followed by the mime type (maybe including options)
if (preg_match('/^[[:alnum:]_-]+/[[:alnum:]_-]+;?.*/', $reply, $matches)) {
$mime_type = $matches[0];
}
}
}
if (empty($mime_type)) {
// Fallback solution: try to guess the type by the file extension
// TODO: add more ...
// TODO: it has been suggested to delegate mimetype detection
// to apache but this has at least three issues:
// - works only with apache
// - needs file to be within the document tree
// - requires apache mod_magic
// TODO: can we use the registry for this on Windows?
// OTOH if the server is Windos the clients are likely to
// be Windows, too, and tend do ignore the Content-Type
// anyway (overriding it with information taken from
// the registry)
// TODO: have a seperate PEAR class for mimetype detection?
switch (strtolower(strrchr(basename($fspath), "."))) {
case ".html":
$mime_type = "text/html";
break;
case ".gif":
$mime_type = "image/gif";
break;
case ".jpg":
$mime_type = "image/jpeg";
break;
default:
$mime_type = "application/octet-stream";
break;
}
}
return $mime_type;
}
/**
* GET method handler
*
* @param array parameter passing array
* @return bool true on success
*/
function GET(&$options) {
$paths = $this->paths;
$pathClasses = PATH_DB . SYS_SYS . PATH_SEP . 'classes' . PATH_SEP;
if ( count($paths) > 0 && $paths[0] == 'classes' && is_dir( $pathClasses ) ) {
$fsFile = $pathClasses. $paths[1];
if ( count($paths) == 2 && file_exists( $fsFile ) ) {
$content = file_get_contents ($fsFile);
print $content;
header("Content-Type: " . mime_content_type($fsFile ) );
header("Last-Modified: " . date("D, j M Y H:m:s ", file_mtime($fsFile )) . "GMT");
header("Content-Length: ". filesize($fsFile));
return true;
}
}
$pathProcesses = PATH_DB . SYS_SYS . PATH_SEP;
if ( count($paths) > 0 && $paths[0] == 'processes' && is_dir( $pathProcesses ) ) {
if ( count($paths) == 4 && $paths[2] == 'xmlforms' ) {
$pathXmlform = $pathProcesses . 'xmlForms' . PATH_SEP . $paths[1] . PATH_SEP;
$fsFile = $pathXmlform. $paths[3];
if ( count($paths) == 4 && file_exists( $fsFile ) ) {
$content = file_get_contents ($fsFile);
print $content;
header("Content-Type: " . mime_content_type($fsFile ) );
header("Last-Modified: " . date("D, j M Y H:m:s ", file_mtime($fsFile )) . "GMT");
header("Content-Length: ". filesize($fsFile));
return true;
}
}
if ( count($paths) == 4 && $paths[2] == 'mailTemplates' ) {
$pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP . $paths[1] . PATH_SEP;
$fsFile = $pathTemplates. $paths[3];
if ( count($paths) == 4 && file_exists( $fsFile ) ) {
$content = file_get_contents ($fsFile);
print $content;
header("Content-Type: " . mime_content_type($fsFile ) );
header("Last-Modified: " . date("D, j M Y H:m:s ", file_mtime($fsFile )) . "GMT");
header("Content-Length: ". filesize($fsFile));
return true;
}
}
if ( count($paths) == 4 && $paths[2] == 'public_html' ) {
$pathPublic = $pathProcesses . 'public' . PATH_SEP . $paths[1] . PATH_SEP;
$fsFile = $pathPublic. $paths[3];
if ( count($paths) == 4 && file_exists( $fsFile ) ) {
$content = file_get_contents ($fsFile);
print $content;
header("Content-Type: " . mime_content_type($fsFile ) );
header("Last-Modified: " . date("D, j M Y H:m:s ", file_mtime($fsFile )) . "GMT");
header("Content-Length: ". filesize($fsFile));
return true;
}
}
}
print_r ( $paths );
return true;
if ( $options["path"] == '/' ) {
return $this->getRoot( $options );
}
//print_r ($options);
// get absolute fs path to requested resource
$fspath = $this->base . $options["path"];
// sanity check
if (!file_exists($fspath)) return false;
// is this a collection?
if (is_dir($fspath)) {
return $this->GetDir($fspath, $options);
}
// detect resource type
$options['mimetype'] = $this->_mimetype($fspath);
// detect modification time
// see rfc2518, section 13.7
// some clients seem to treat this as a reverse rule
// requiering a Last-Modified header if the getlastmodified header was set
$options['mtime'] = filemtime($fspath);
// detect resource size
$options['size'] = filesize($fspath);
// no need to check result here, it is handled by the base class
$options['stream'] = fopen($fspath, "r");
return true;
}
/**
* getRoot
*
* @param string &$options
* @return boolean false
*/
function getRoot (&$options)
{
$path = $this->_slashify($options["path"]);
// fixed width directory column format
$format = "%15s %-19s %-s\n";
echo "<html><head><title>Index of " . htmlspecialchars($options['path']) . "</title></head>\n";
echo "<h1>Index of " . htmlspecialchars($options['path']) . "</h1>\n";
echo "<pre>";
printf($format, "Size", "Last modified", "Filename");
echo "<hr>";
$pathRoot = array ( 'xmlforms', 'public_html', 'dir1', 'dir2' );
foreach ( $pathRoot as $key => $val ) {
$fullpath = $fspath."/".$filename;
$name = htmlspecialchars($val);
printf($format, number_format(filesize($fullpath)),
strftime("%Y-%m-%d %H:%M:%S", filemtime($fullpath)),
"<a href='$this->base_uri$path$name'>$name</a>");
}
echo "</pre>";
echo "</html>\n";
die;
$handle = @opendir($fspath);
if (!$handle) {
return false;
}
while ($filename = readdir($handle)) {
if ($filename != "." && $filename != "..") {
$fullpath = $fspath."/".$filename;
$name = htmlspecialchars($filename);
printf($format,
number_format(filesize($fullpath)),
strftime("%Y-%m-%d %H:%M:%S", filemtime($fullpath)),
"<a href='$this->base_uri$path$name'>$name</a>");
}
}
echo "</pre>";
closedir($handle);
echo "</html>\n";
exit;
}
/**
* GET method handler for directories
*
* This is a very simple mod_index lookalike.
* See RFC 2518, Section 8.4 on GET/HEAD for collections
*
* @param string directory path
* @return void function has to handle HTTP response itself
*/
function GetDir($fspath, &$options)
{
$path = $this->_slashify($options["path"]);
if ($path != $options["path"]) {
header("Location: ".$this->base_uri.$path);
exit;
}
// fixed width directory column format
$format = "%15s %-19s %-s\n";
$handle = @opendir($fspath);
if (!$handle) {
return false;
}
echo "<html><head><title>Index of ".htmlspecialchars($options['path'])."</title></head>\n";
echo "<h1>Index of ".htmlspecialchars($options['path'])."</h1>\n";
echo "<pre>";
printf($format, "Size", "Last modified", "Filename");
echo "<hr>";
while ($filename = readdir($handle)) {
if ($filename != "." && $filename != "..") {
$fullpath = $fspath."/".$filename;
$name = htmlspecialchars($filename);
printf($format,
number_format(filesize($fullpath)),
strftime("%Y-%m-%d %H:%M:%S", filemtime($fullpath)),
"<a href='$this->base_uri$path$name'>$name</a>");
}
}
echo "</pre>";
closedir($handle);
echo "</html>\n";
exit;
}
/**
* PUT method handler
*
* @param array parameter passing array
* @return bool true on success
*/
function PUT(&$options)
{
$paths = $this->paths;
$pathClasses = PATH_DB . PATH_SEP . 'classes' . PATH_SEP;
if ( count($paths) > 0 && $paths[0] == 'classes' && is_dir( $pathClasses ) ) {
$fsFile = $pathClasses. $paths[1];
if ( count($paths) == 2 && file_exists( $fsFile ) ) {
$fp = fopen($fsFile, "w");
if ( is_resource($fp) && is_resource($options["stream"])) {
while( !feof($options["stream"])) {
fwrite($fp, fread($options["stream"], 4096));
}
fclose($fp);
fclose($options["stream"]);
}
return "201 Created " . $fsFile;
}
}
$pathProcesses = PATH_DB . SYS_SYS . PATH_SEP ;
if ( count($paths) > 0 && $paths[0] == 'processes' && is_dir( $pathProcesses ) ) {
if ( $paths[2] == 'xmlforms' ) {
$pathTemplates = $pathProcesses . 'xmlForms' . PATH_SEP . $paths[1] . PATH_SEP;
$fsFile = $pathTemplates. $paths[3];
if ( count($paths) == 4 && file_exists( $fsFile ) ) {
$fp = fopen($fsFile, "w");
if ( is_resource($fp) && is_resource($options["stream"])) {
while( !feof($options["stream"])) {
fwrite($fp, fread($options["stream"], 4096));
}
fclose($fp);
fclose($options["stream"]);
}
return "201 Created " . $fsFile;
}
}
if ( $paths[2] == 'mailTemplates' ) {
$pathTemplates = $pathProcesses . 'mailTemplates' . PATH_SEP . $paths[1] . PATH_SEP;
$fsFile = $pathTemplates. $paths[3];
if ( count($paths) == 4 && file_exists( $fsFile ) ) {
$fp = fopen($fsFile, "w");
if ( is_resource($fp) && is_resource($options["stream"])) {
while( !feof($options["stream"])) {
fwrite($fp, fread($options["stream"], 4096));
}
fclose($fp);
fclose($options["stream"]);
}
return "201 Created " . $fsFile;
}
}
if ( $paths[2] == 'public_html' ) {
$pathPublic = $pathProcesses . 'public' . PATH_SEP . $paths[1] . PATH_SEP;
$fsFile = $pathPublic. $paths[3];
if ( count($paths) == 4 && file_exists( $fsFile ) ) {
$fp = fopen($fsFile, "w");
if ( is_resource($fp) && is_resource($options["stream"])) {
while( !feof($options["stream"])) {
fwrite($fp, fread($options["stream"], 4096));
}
fclose($fp);
fclose($options["stream"]);
}
return "201 Created " . $fsFile;
}
}
}
return "409 Conflict";
}
/**
* MKCOL method handler
*
* @param array general parameter passing array
* @return bool true on success
*/
function MKCOL($options)
{
$path = $this->base .$options["path"];
$parent = dirname($path);
$name = basename($path);
if (!file_exists($parent)) {
return "409 Conflict";
}
if (!is_dir($parent)) {
return "403 Forbidden";
}
if ( file_exists($parent."/".$name) ) {
return "405 Method not allowed";
}
if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
return "415 Unsupported media type";
}
$stat = mkdir ($parent."/".$name,0777);
if (!$stat) {
return "403 Forbidden";
}
return ("201 Created");
}
/**
* DELETE method handler
*
* @param array general parameter passing array
* @return bool true on success
*/
function DELETE($options)
{
$path = $this->base . "/" .$options["path"];
if (!file_exists($path)) {
return "404 Not found";
}
if (is_dir($path)) {
$query = "DELETE FROM properties WHERE path LIKE '".$this->_slashify($options["path"])."%'";
mysql_query($query);
System::rm("-rf $path");
} else {
unlink ($path);
}
$query = "DELETE FROM properties WHERE path = '$options[path]'";
mysql_query($query);
return "204 No Content";
}
/**
* MOVE method handler
*
* @param array general parameter passing array
* @return bool true on success
*/
function MOVE($options)
{
return "423 Locked";
//return $this->COPY($options, true);
}
/**
* COPY method handler
*
* @param array general parameter passing array
* @return bool true on success
*/
function COPY($options, $del=false)
{
// TODO Property updates still broken (Litmus should detect this?)
if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
return "415 Unsupported media type";
}
// no copying to different WebDAV Servers yet
if (isset($options["dest_url"])) {
return "502 bad gateway";
}
$source = $this->base .$options["path"];
if (!file_exists($source)) return "404 Not found";
$dest = $this->base . $options["dest"];
$new = !file_exists($dest);
$existing_col = false;
if (!$new) {
if ($del && is_dir($dest)) {
if (!$options["overwrite"]) {
return "412 precondition failed";
}
$dest .= basename($source);
if (file_exists($dest)) {
$options["dest"] .= basename($source);
} else {
$new = true;
$existing_col = true;
}
}
}
if (!$new) {
if ($options["overwrite"]) {
$stat = $this->DELETE(array("path" => $options["dest"]));
if (($stat{0} != "2") && (substr($stat, 0, 3) != "404")) {
return $stat;
}
} else {
return "412 precondition failed";
}
}
if (is_dir($source) && ($options["depth"] != "infinity")) {
// RFC 2518 Section 9.2, last paragraph
return "400 Bad request";
}
if ($del) {
if (!rename($source, $dest)) {
return "500 Internal server error";
}
$destpath = $this->_unslashify($options["dest"]);
if (is_dir($source)) {
$query = "UPDATE properties
SET path = REPLACE(path, '".$options["path"]."', '".$destpath."')
WHERE path LIKE '".$this->_slashify($options["path"])."%'";
mysql_query($query);
}
$query = "UPDATE properties
SET path = '".$destpath."'
WHERE path = '".$options["path"]."'";
mysql_query($query);
} else {
if (is_dir($source)) {
$files = System::find($source);
$files = array_reverse($files);
} else {
$files = array($source);
}
if (!is_array($files) || empty($files)) {
return "500 Internal server error";
}
foreach ($files as $file) {
if (is_dir($file)) {
$file = $this->_slashify($file);
}
$destfile = str_replace($source, $dest, $file);
if (is_dir($file)) {
if (!is_dir($destfile)) {
// TODO "mkdir -p" here? (only natively supported by PHP 5)
if (!mkdir($destfile)) {
return "409 Conflict";
}
} else {
error_log("existing dir '$destfile'");
}
} else {
if (!copy($file, $destfile)) {
return "409 Conflict";
}
}
}
$query = "INSERT INTO properties SELECT ... FROM properties WHERE path = '".$options['path']."'";
}
return ($new && !$existing_col) ? "201 Created" : "204 No Content";
}
/**
* PROPPATCH method handler
*
* @param array general parameter passing array
* @return bool true on success
*/
function PROPPATCH(&$options)
{
global $prefs, $tab;
$msg = "";
$path = $options["path"];
$dir = dirname($path)."/";
$base = basename($path);
foreach($options["props"] as $key => $prop) {
if ($prop["ns"] == "DAV:") {
$options["props"][$key]['status'] = "403 Forbidden";
} else {
if (isset($prop["val"])) {
$query = "REPLACE INTO properties SET path = '$options[path]', name = '$prop[name]', ns= '$prop[ns]', value = '$prop[val]'";
error_log($query);
} else {
$query = "DELETE FROM properties WHERE path = '$options[path]' AND name = '$prop[name]' AND ns = '$prop[ns]'";
}
mysql_query($query);
}
}
return "";
}
/**
* LOCK method handler
*
* @param array general parameter passing array
* @return bool true on success
*/
function LOCK(&$options)
{
if (isset($options["update"])) { // Lock Update
$query = "UPDATE locks SET expires = ".(time()+300);
mysql_query($query);
if (mysql_affected_rows()) {
$options["timeout"] = 300; // 5min hardcoded
return true;
} else {
return false;
}
}
$options["timeout"] = time()+300; // 5min. hardcoded
$query = "INSERT INTO locks
SET token = '$options[locktoken]'
, path = '$options[path]'
, owner = '$options[owner]'
, expires = '$options[timeout]'
, exclusivelock = " .($options['scope'] === "exclusive" ? "1" : "0") ;
mysql_query($query);
return mysql_affected_rows() ? "200 OK" : "409 Conflict";
}
/**
* UNLOCK method handler
*
* @param array general parameter passing array
* @return bool true on success
*/
function UNLOCK(&$options)
{
$query = "DELETE FROM locks
WHERE path = '$options[path]'
AND token = '$options[token]'";
mysql_query($query);
return mysql_affected_rows() ? "204 No Content" : "409 Conflict";
}
/**
* checkLock() helper
*
* @param string resource path to check for locks
* @return bool true on success
*/
function checkLock($path)
{
$result = false;
$query = "SELECT owner, token, expires, exclusivelock
FROM locks
WHERE path = '$path' ";
$res = mysql_query($query);
if ($res) {
$row = mysql_fetch_array($res);
mysql_free_result($res);
if ($row) {
$result = array( "type" => "write",
"scope" => $row["exclusivelock"] ? "exclusive" : "shared",
"depth" => 0,
"owner" => $row['owner'],
"token" => $row['token'],
"expires" => $row['expires']
);
}
}
return $result;
}
/**
* create database tables for property and lock storage
*
* @param void
* @return bool true on success
*/
function create_database()
{
// TODO
return false;
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,177 @@
<?php
/**
* class.wsResponse.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.
*
*/
class wsResponse
{
public $status_code = 0;
public $message = '';
public $timestamp = '';
/**
* Function __construct
* Constructor of the class
* @param string $status
* @param string $message
* @return void
*/
function __construct( $status, $message )
{
$this->status_code = $status;
$this->message = $message;
$this->timestamp = date('Y-m-d H:i:s');
}
/**
* Function getPayloadString
* @param string $operation
* @return string
*/
function getPayloadString ( $operation )
{
$res = "<$operation>\n";
$res .= "<status_code>" . $this->status_code . "</status_code>";
$res .= "<message>" . $this->message . "</message>";
$res .= "<timestamp>" . $this->timestamp . "</timestamp>";
// $res .= "<array>" . $this->timestamp . "</array>";
$res .= "<$operation>";
return $res;
}
/**
* Function getPayloadArray
* @return array
*/
function getPayloadArray()
{
return array("status_code" => $this->status_code , 'message'=> $this->message, 'timestamp' => $this->timestamp);
}
}
/**
* Class wsCreateUserResponse
*/
class wsCreateUserResponse
{
public $status_code = 0;
public $message = '';
public $userUID = '';
public $timestamp = '';
/**
* Function __construct
* Constructor of the class
* @param string $status
* @param string $message
* @param string $userUID
* @return void
*/
function __construct( $status, $message, $userUID )
{
$this->status_code = $status;
$this->message = $message;
$this->userUID = $userUID;
$this->timestamp = date('Y-m-d H:i:s');
}
}
/**
* Class wsCreateGroupResponse
*/
class wsCreateGroupResponse
{
public $status_code = 0;
public $message = '';
public $groupUID = '';
public $timestamp = '';
/**
* Function __construct
* Constructor of the class
* @param string $status
* @param string $message
* @param string $groupUID
* @return void
*/
function __construct( $status, $message, $groupUID ) {
$this->status_code = $status;
$this->message = $message;
$this->groupUID = $groupUID;
$this->timestamp = date('Y-m-d H:i:s');
}
}
/**
* Class wsCreateDepartmentResponse
*/
class wsCreateDepartmentResponse
{
public $status_code = 0;
public $message = '';
public $departmentUID = '';
public $timestamp = '';
/**
* Function __construct
* Constructor of the class
* @param string $status
* @param string $message
* @param string $departmentUID
* @return void
*/
function __construct( $status, $message, $departmentUID ) {
$this->status_code = $status;
$this->message = $message;
$this->departmentUID = $departmentUID;
$this->timestamp = date('Y-m-d H:i:s');
}
}
/**
* Class wsGetVariableResponse
*/
class wsGetVariableResponse
{
public $status_code = 0;
public $message = '';
public $variables = null;
public $timestamp = '';
/**
* Function __construct
* Constructor of the class
* @param string $status
* @param string $message
* @param string $variables
* @return void
*/
function __construct( $status, $message, $variables ) {
$this->status_code = $status;
$this->message = $message;
$this->variables = $variables;
$this->timestamp = date('Y-m-d H:i:s');
}
}
?>

View File

@@ -0,0 +1,370 @@
<?php
/**
* Utility functions to manage a workspace.
*
* @author Alexandre Rosenfeld
*/
class workspaceTools {
var $workspaceName = NULL;
var $dbFile = NULL;
var $dbInfoRegExp = "/( *define *\( *'(?P<key>.*?)' *, *\n* *')(?P<value>.*?)(' *\) *;.*)/";
/**
* Create a workspace tools object
*
* @author Alexandre Rosenfeld <alexandre@colosa.com>
* @access public
* @param string $workspaceName name of the workspace
* @return void
*/
function __construct($workspaceName)
{
$this->workspaceName = $workspaceName;
$this->dbFile = PATH_DB . $this->workspaceName . '/db.php';
}
function listWorkspaces() {
$oDirectory = dir(PATH_DB);
$aWorkspaces = array ();
while( ($sObject = $oDirectory->read()) ) {
if( is_dir(PATH_DB . $sObject) && substr($sObject, 0, 1) != '.' && file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php') ) {
$aWorkspaces[] = new workspaceTools($sObject);
}
}
return $aWorkspaces;
}
function getDBInfo() {
if( file_exists($this->dbFile) ) {
$sDbFile = file_get_contents($this->dbFile);
/* This regular expression will match any "define ('<key>', '<value>');"
* with any combination of whitespace between words.
* Each match will have these groups:
* ((define('(<key>)2', ')1 (<value>)3 (');)4 )0
*/
preg_match_all($this->dbInfoRegExp, $sDbFile, $matches, PREG_SET_ORDER);
$config = array();
foreach ($matches as $match) {
$config[$match['key']] = $match['value'];
}
return $config;
} else {
throw new Exception("Workspace db.php not found.");
}
}
function getSchema() {
$dbInfo = $this->getDBInfo();
$DB_ADAPTER = $dbInfo["DB_ADAPTER"];
$DB_HOST = $dbInfo["DB_HOST"];
$DB_USER = $dbInfo["DB_USER"];
$DB_PASS = $dbInfo["DB_PASS"];
$DB_NAME = $dbInfo["DB_NAME"];
try {
G::LoadSystem( 'database_' . strtolower($DB_ADAPTER));
$aOldSchema = array();
$oDataBase = new database($DB_ADAPTER, $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( !$oDataBase->isConnected() ) {
$oDataBase->logQuery ('Not exists an available connection!');
return NULL;
}
$oDataBase->iFetchType = MYSQL_NUM;
$oDataset1 = $oDataBase->executeQuery($oDataBase->generateShowTablesSQL());
} catch ( Exception $e ) {
$oDataBase->logQuery ( $e->getmessage() );
return NULL;
}
//going thru all tables in current WF_ database
while ($aRow1 = $oDataBase->getRegistry( $oDataset1) ) {
$aPrimaryKeys = array();
$sTable = strtoupper($aRow1[0]);
//get description of each table, ( column and primary keys )
//$oDataset2 = $oDataBase->executeQuery( $oDataBase->generateDescTableSQL($aRow1[0]) );
$oDataset2 = $oDataBase->executeQuery( $oDataBase->generateDescTableSQL($sTable ) );
$aOldSchema[ $sTable ] = array();
$oDataBase->iFetchType = MYSQL_ASSOC;
while ($aRow2 = $oDataBase->getRegistry($oDataset2)) {
$aOldSchema[$sTable][$aRow2['Field']]['Field'] = $aRow2['Field'];
$aOldSchema[$sTable][$aRow2['Field']]['Type'] = $aRow2['Type'];
$aOldSchema[$sTable][$aRow2['Field']]['Null'] = $aRow2['Null'];
$aOldSchema[$sTable][$aRow2['Field']]['Default'] = $aRow2['Default'];
}
//get indexes of each table SHOW INDEX FROM `ADDITIONAL_TABLES`; -- WHERE Key_name <> 'PRIMARY'
$oDataset2 = $oDataBase->executeQuery($oDataBase->generateTableIndexSQL($aRow1[0]));
$oDataBase->iFetchType = MYSQL_ASSOC;
while ($aRow2 = $oDataBase->getRegistry($oDataset2)) {
if ( !isset($aOldSchema[$sTable]['INDEXES']) ) {
$aOldSchema[$sTable]['INDEXES'] = array();
}
if (!isset($aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']] ) ) {
$aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']] = array();
}
$aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']][] = $aRow2['Column_name'];
}
$oDataBase->iFetchType = MYSQL_NUM; //this line is neccesary because the next fetch needs to be with MYSQL_NUM
}
//finally return the array with old schema obtained from the Database
if ( count($aOldSchema) == 0 ) $aOldSchema = null;
return $aOldSchema;
}
function getSchemaFromFile($sSchemaFile, $dbAdapter) {
$aSchema = array();
$oXml = new DomDocument();
$oXml->load($sSchemaFile);
$aTables = $oXml->getElementsByTagName('table');
foreach ($aTables as $oTable) {
$aPrimaryKeys = array();
$sTableName = $oTable->getAttribute('name');
$aSchema[$sTableName] = array();
$aColumns = $oTable->getElementsByTagName('column');
foreach ($aColumns as $oColumn) {
$sColumName = $oColumn->getAttribute('name');
$aSchema[$sTableName][$sColumName] = array();
$aVendors = $oColumn->getElementsByTagName('vendor');
foreach ($aVendors as $oVendor) {
if ($oVendor->getAttribute('type') == $dbAdapter) {
break;
}
}
$aParameters = $oColumn->getElementsByTagName('parameter');
foreach ($aParameters as $oParameter) {
$parameterName = ucwords($oParameter->getAttribute('name'));
if ( $parameterName == 'Key' && strtoupper($oParameter->getAttribute('value')) == 'PRI' ) {
$aPrimaryKeys[] = $oColumn->getAttribute('name');
}
if ( in_array ( $parameterName, array('Field','Type','Null','Default') ) ) {
$aSchema[$sTableName][$sColumName][$parameterName] = $oParameter->getAttribute('value');
}
}
}
if ( is_array($aPrimaryKeys) && count($aPrimaryKeys) > 0 ) {
$aSchema[$sTableName]['INDEXES']['PRIMARY'] = $aPrimaryKeys;
}
$aIndexes = $oTable->getElementsByTagName('index');
foreach ($aIndexes as $oIndex) {
$aIndex = array();
$aIndexesColumns = $oIndex->getElementsByTagName('index-column');
foreach ($aIndexesColumns as $oIndexColumn) {
$aIndex[] = $oIndexColumn->getAttribute('name');
}
$aSchema[$sTableName]['INDEXES'][ $oIndex->getAttribute('name') ] = $aIndex;
}
}
return $aSchema;
}
function getSchemaChanges($aOldSchema, $aNewSchema) {
//$aChanges = array('tablesToDelete' => array(), 'tablesToAdd' => array(), 'tablesToAlter' => array());
//Tables to delete, but this is disabled
//foreach ($aOldSchema as $sTableName => $aColumns) {
// if ( !isset($aNewSchema[$sTableName])) {
// if (!in_array($sTableName, array('KT_APPLICATION', 'KT_DOCUMENT', 'KT_PROCESS'))) {
// $aChanges['tablesToDelete'][] = $sTableName;
// }
// }
//}
$aChanges = array('tablesToAdd' => array(), 'tablesToAlter' => array(), 'tablesWithNewIndex' => array(), 'tablesToAlterIndex'=> array());
//new tables to create and alter
foreach ($aNewSchema as $sTableName => $aColumns) {
if (!isset($aOldSchema[$sTableName])) {
$aChanges['tablesToAdd'][$sTableName] = $aColumns;
}
else {
//drop old columns
foreach ($aOldSchema[$sTableName] as $sColumName => $aParameters) {
if (!isset($aNewSchema[$sTableName][$sColumName])) {
if (!isset($aChanges['tablesToAlter'][$sTableName])) {
$aChanges['tablesToAlter'][$sTableName] = array('DROP' => array(), 'ADD' => array(), 'CHANGE' => array());
}
$aChanges['tablesToAlter'][$sTableName]['DROP'][$sColumName] = $sColumName;
}
}
//create new columns
//foreach ($aNewSchema[$sTableName] as $sColumName => $aParameters) {
foreach ($aColumns as $sColumName => $aParameters) {
if ($sColumName != 'INDEXES') {
if (!isset($aOldSchema[$sTableName][$sColumName])) { //this column doesnt exist in oldschema
if (!isset($aChanges['tablesToAlter'][$sTableName])) {
$aChanges['tablesToAlter'][$sTableName] = array('DROP' => array(), 'ADD' => array(), 'CHANGE' => array());
}
$aChanges['tablesToAlter'][$sTableName]['ADD'][$sColumName] = $aParameters;
}
else { //the column exists
$newField = $aNewSchema[$sTableName][$sColumName];
$oldField = $aOldSchema[$sTableName][$sColumName];
//both are null, no change is required
if ( !isset($newField['Default']) && !isset($oldField['Default'])) $changeDefaultAttr = false;
//one of them is null, change IS required
if ( !isset($newField['Default']) && isset($oldField['Default']) && $oldField['Default']!= '') $changeDefaultAttr = true;
if ( isset($newField['Default']) && !isset($oldField['Default'])) $changeDefaultAttr = true;
//both are defined and they are different.
if ( isset($newField['Default']) && isset($oldField['Default']) ) {
if ( $newField['Default'] != $oldField['Default'] )
$changeDefaultAttr = true;
else
$changeDefaultAttr = false;
}
//special cases
// BLOB and TEXT columns cannot have DEFAULT values. http://dev.mysql.com/doc/refman/5.0/en/blob.html
if ( in_array(strtolower($newField['Type']), array('text','mediumtext') ) )
$changeDefaultAttr = false;
//#1067 - Invalid default value for datetime field
if ( in_array($newField['Type'], array('datetime')) && isset($newField['Default']) && $newField['Default']== '' )
$changeDefaultAttr = false;
//#1067 - Invalid default value for int field
if ( substr($newField['Type'], 0, 3 ) && isset($newField['Default']) && $newField['Default']== '' )
$changeDefaultAttr = false;
//if any difference exists, then insert the difference in aChanges
if ( $newField['Field'] != $oldField['Field'] ||
$newField['Type'] != $oldField['Type'] ||
$newField['Null'] != $oldField['Null'] ||
$changeDefaultAttr ) {
if (!isset($aChanges['tablesToAlter'][$sTableName])) {
$aChanges['tablesToAlter'][$sTableName] = array('DROP' => array(), 'ADD' => array(), 'CHANGE' => array());
}
$aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Field'] = $newField['Field'];
$aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Type'] = $newField['Type'];
$aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Null'] = $newField['Null'];
if ( isset($newField['Default']) )
$aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = $newField['Default'];
else
$aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = null;
}
}
} //only columns, no the indexes column
}//foreach $aColumns
//now check the indexes of table
if ( isset($aNewSchema[$sTableName]['INDEXES']) ) {
foreach ( $aNewSchema[$sTableName]['INDEXES'] as $indexName => $indexFields ) {
if (!isset( $aOldSchema[$sTableName]['INDEXES'][$indexName]) ) {
if (!isset($aChanges['tablesWithNewIndex'][$sTableName])) {
$aChanges['tablesWithNewIndex'][$sTableName] = array();
}
$aChanges['tablesWithNewIndex'][$sTableName][$indexName] = $indexFields;
}
else {
if ( $aOldSchema[$sTableName]['INDEXES'][$indexName] != $indexFields ) {
if (!isset($aChanges['tablesToAlterIndex'][$sTableName])) {
$aChanges['tablesToAlterIndex'][$sTableName] = array();
}
$aChanges['tablesToAlterIndex'][$sTableName][$indexName] = $indexFields;
}
}
}
}
} //for-else table exists
} //for new schema
return $aChanges;
}
function repairSchema($checkOnly = false, $progress = true) {
$dbInfo = $this->getDBInfo();
$DB_ADAPTER = $dbInfo["DB_ADAPTER"];
$DB_HOST = $dbInfo["DB_HOST"];
$DB_USER = $dbInfo["DB_USER"];
$DB_PASS = $dbInfo["DB_PASS"];
$DB_NAME = $dbInfo["DB_NAME"];
if (strcmp($DB_ADAPTER, "mysql") != 0) {
throw new Exception("Only MySQL is supported\n");
}
$currentSchema = $this->getSchemaFromFile(PATH_TRUNK . "workflow/engine/config/schema.xml", "mysql");
$workspaceSchema = $this->getSchema();
$changes = $this->getSchemaChanges($workspaceSchema, $currentSchema);
$changed = (count($changes['tablesToAdd']) > 0 ||
count($changes['tablesToAlter']) > 0 ||
count($changes['tablesWithNewIndex']) > 0 ||
count($changes['tablesToAlterIndex']) > 0);
if ($checkOnly || (!$changed)) {
if ($changed)
return $changes;
else
return $changed;
}
$oDataBase = new database($DB_ADAPTER, $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( !$oDataBase->isConnected() ) {
throw new Exception("Could not connect to the database");
}
$oDataBase->iFetchType = MYSQL_NUM;
$oDataBase->logQuery ( count ($changes ) );
if ($progress)
echo "Adding " . count($changes['tablesToAdd']) . " tables\n";
foreach ($changes['tablesToAdd'] as $sTable => $aColumns) {
$oDataBase->executeQuery($oDataBase->generateCreateTableSQL($sTable, $aColumns));
if (isset($changes['tablesToAdd'][$sTable]['INDEXES'])) {
foreach ($changes['tablesToAdd'][$sTable]['INDEXES'] as $indexName => $aIndex) {
$oDataBase->executeQuery($oDataBase->generateAddKeysSQL($sTable, $indexName, $aIndex ) );
}
}
}
if ($progress)
echo "Altering " . count($changes['tablesToAlter']) . " tables\n";
foreach ($changes['tablesToAlter'] as $sTable => $aActions) {
foreach ($aActions as $sAction => $aAction) {
foreach ($aAction as $sColumn => $vData) {
switch ($sAction) {
case 'DROP':
$oDataBase->executeQuery($oDataBase->generateDropColumnSQL($sTable, $vData));
break;
case 'ADD':
$oDataBase->executeQuery($oDataBase->generateAddColumnSQL($sTable, $sColumn, $vData));
break;
case 'CHANGE':
$oDataBase->executeQuery($oDataBase->generateChangeColumnSQL($sTable, $sColumn, $vData));
break;
}
}
}
}
if ($progress)
echo "Adding indexes to " . count($changes['tablesWithNewIndex']) . " tables\n";
foreach ($changes['tablesWithNewIndex'] as $sTable => $aIndexes) {
foreach ($aIndexes as $sIndexName => $aIndexFields ) {
$oDataBase->executeQuery($oDataBase->generateAddKeysSQL($sTable, $sIndexName, $aIndexFields ));
}
}
if ($progress)
echo "Altering indexes to " . count($changes['tablesWithNewIndex']) . " tables\n";
foreach ($changes['tablesToAlterIndex'] as $sTable => $aIndexes) {
foreach ($aIndexes as $sIndexName => $aIndexFields ) {
$oDataBase->executeQuery($oDataBase->generateDropKeySQL($sTable, $sIndexName ));
$oDataBase->executeQuery($oDataBase->generateAddKeysSQL($sTable, $sIndexName, $aIndexFields ));
}
}
$oDataBase->close();
return true;
}
}
?>

View File

@@ -0,0 +1,629 @@
<?php
/**
* class.xmlDb.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.
*
*/
/**
* XMLDB
*
* ProcessMaker Open Source Edition
*
* @copyright (C) 2004 - 2008 Colosa Inc.23
*/
class XMLDB
{
/**
* &connect
*
* @param string $dsn
* @return array $options
*/
function &connect ($dsn, $options = array())
{
//Needed for $mysql_real_escape_string
$mresdbc = new DBConnection();
if ( !file_exists( $dsn ) ) {
$err = new DB_Error( "File $dsn not found." );
return $err;
}
$dbc = new XMLConnection($dsn);
return $dbc;
}
/**
* isError
*
* @param string $result
* @return boolean is_a($result, 'DB_Error')
*/
function isError ( $result )
{
return is_a($result, 'DB_Error');
}
}
/**
* XMLConnection
*
* ProcessMaker Open Source Edition
*
* @copyright (C) 2004 - 2008 Colosa Inc.23
*/
class XMLConnection
{
var $phptype = 'myxml';
var $caseFolding = true;
var $xmldoc = NULL;
var $xmlFile = '';
/**
* XMLConnection
*
* @param string $file
* @return void
*/
function XMLConnection ( $file )
{
$this->xmldoc = new Xml_Document();
$this->xmldoc->parseXmlFile( $file );
$this->xmlFile = $file;
}
/**
* &query
* Actualy the only one supported query is simple SELECT.
*
* @param string $sql
* @return object(XMLResult) $result
*/
function &query( $sql )
{
if ( !isset( $this->xmldoc ) ) {
$err = new DB_Error( "Error: Closed xmlConnection." );
return $err;
}
if (1===preg_match('/^\s*SELECT\s+([\w\W]+?)(?:\s+FROM\s+`?([^`]+?)`?)(?:\s+WHERE\s+([\w\W]+?))?(?:\s+GROUP\s+BY\s+([\w\W]+?))?(?:\s+ORDER\s+BY\s+([\w\W]+?))?(?:\s+BETWEEN\s+([\w\W]+?)\s+AND\s+([\w\W]+?))?(?:\s+LIMIT\s+(\d+)\s*,\s*(\d+))?\s*$/im', $sql, $matches)) {
$sqlColumns = $matches[1];
$sqlFrom = isset($matches[2])?$matches[2]:'';
$sqlWhere = isset($matches[3])?$matches[3]:'';
$sqlGroupBy = isset($matches[4])?$matches[4]:'';
$sqlOrderBy = isset($matches[5])?$matches[5]:'';
$sqlLowLimit = isset($matches[8])?$matches[8]:'';
$sqlHighLimit = isset($matches[9])?$matches[9]:'';
/* Start Block: Fields list */
$count = preg_match_all('/\s*(\*|[\w\.]+)(?:\s+AS\s+([\w\.]+))?/im',$sqlColumns,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
$fieldsList = array();
for($r=0; $r< $count;$r++) {
$name = (is_array($match[2][$r]) && $match[2][$r][0]!=='') ? $match[2][$r][0] : $match[1][$r][0];
$fieldsList[$name] = $match[1][$r][0];
}
/* End Block */
/* Start Block: Order list */
$count=preg_match_all('/\s*(\*|[\w\.]+)(\s+ASC|\s+DESC)?\s*,?/im',$sqlOrderBy,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
$orderList = array();
for($r = $count-1; $r>=0; $r--) {
$direction = (is_array($match[2][$r]) && $match[2][$r][0]!=='') ? $match[2][$r][0] : 'ASC';
$direction = strtoupper( $direction );
$orderList[$match[1][$r][0]] = $direction;
}
/* End Block */
$xmlFrom = '/' . str_replace( '.','/' , $sqlFrom );
$node =& $this->xmldoc->findNode( $xmlFrom );
if (!isset($node)) {
//$err = new DB_Error( "$xmlFrom node not found in $dsn." );
throw new Exception( "$xmlFrom node not found in " . $this->xmlFile . "." );
return $err;
} else {
$res = $this->fetchChildren ( $node );
}
/* Start Block: WHERE*/
if ($sqlWhere!=='') {
/*Start Block: Replace the operator */
$blocks = preg_split('/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', $sqlWhere , -1 , PREG_SPLIT_DELIM_CAPTURE );
$sqlWhere = '';
for($r = 0 ; $r < sizeof($blocks) ; $r++ ){
if ( ($r % 2) === 0 ) {
$blocks[$r] = str_replace( '=' , '==', $blocks[$r]);
$blocks[$r] = str_replace( '<>' , '!=', $blocks[$r]);
$blocks[$r] = str_replace( 'AND' , '&&', $blocks[$r]);
$blocks[$r] = str_replace( 'and' , '&&', $blocks[$r]);
$blocks[$r] = str_replace( 'OR' , '||', $blocks[$r]);
$blocks[$r] = str_replace( 'or' , '||', $blocks[$r]);
$blocks[$r] = str_replace( 'NOT' , '!', $blocks[$r]);
$blocks[$r] = str_replace( 'not' , '!', $blocks[$r]);
$blocks[$r] = preg_replace('/\b[a-zA-Z_][\w\.]*\b/im', '$res[$r][\'$0\']', $blocks[$r] );
$blocks[$r] = preg_replace('/\$res\[\$r\]\[\'(like)\'\]/im', '$1', $blocks[$r] );
}
$sqlWhere .= $blocks[$r];
}
$sqlWhere = preg_replace_callback('/(.+)\s+like\s+("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im',
array('XMLConnection','sqlWhereLike'), $sqlWhere );
$sqlWhere = preg_replace_callback('/"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'/im',
array('XMLConnection','sqlString'), $sqlWhere );
$newRes = array();
for( $r=0 ; $r < sizeof($res) ; $r++ ) {
$evalWhere = false;
@eval('$evalWhere = '.$sqlWhere.';');
if ( $evalWhere ) $newRes[] = $res[$r];
}
$res = $newRes;
}
/* End Block */
/* Start Block: Expands the resultant data according to fill an array
* with the required fields in the query.
*/
for( $r=0 ; $r < sizeof($res) ; $r++ ) {
$res[$r] = $this->expandFields( $res[$r] , $fieldsList );
}
/* End Block */
/* Start Block: ORDER BY*/
foreach($orderList as $field => $direction ) {
for( $i=0 ; $i < sizeof($res) ; $i++ ) {
for( $j= $i+1 ; $j < sizeof($res) ; $j++ ) {
$condition = ($direction==='ASC')?
($res[$j] < $res[$i]) : ($res[$j] > $res[$i]);
if ( $condition ) {
$swap = $res[$i];
$res[$i] = $res[$j];
$res[$j] = $swap;
}
}
}
}
/* End Block */
/* Start Block: Apply limits */
if ($sqlLowLimit!='' && $sqlHighLimit!='')
{
$sqlLowLimit = (int) $sqlLowLimit;
$sqlHighLimit = (int) $sqlHighLimit;
$res = array_slice( $res , $sqlLowLimit , $sqlHighLimit );
}
/* End Block */
$result = new XMLResult( $res );
return $result;
}
elseif (1===preg_match('/^\s*DELETE\s+FROM\s+`?([^`]+?)`?(?:\s+WHERE\s+([\w\W]+?))?\s*$/im',$sql,$matches))
{
$sqlFrom = isset($matches[1])?$matches[1]:'';
$sqlWhere = isset($matches[2])?$matches[2]:'1';
/* Start Block: WHERE*/
/*Start Block: Replace the operator */
$blocks = preg_split('/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', $sqlWhere , -1 , PREG_SPLIT_DELIM_CAPTURE );
$sqlWhere = '';
for($r = 0 ; $r < sizeof($blocks) ; $r++ ){
if ( ($r % 2) === 0 ) {
$blocks[$r] = str_replace( '=' , '==', $blocks[$r]);
$blocks[$r] = str_replace( '<>' , '!=', $blocks[$r]);
$blocks[$r] = str_replace( 'AND' , '&&', $blocks[$r]);
$blocks[$r] = str_replace( 'and' , '&&', $blocks[$r]);
$blocks[$r] = str_replace( 'OR' , '||', $blocks[$r]);
$blocks[$r] = str_replace( 'or' , '||', $blocks[$r]);
$blocks[$r] = str_replace( 'NOT' , '!', $blocks[$r]);
$blocks[$r] = str_replace( 'not' , '!', $blocks[$r]);
$blocks[$r] = preg_replace('/\b[a-zA-Z_][\w\.]*\b/im', '$res[$r][\'$0\']', $blocks[$r] );
$blocks[$r] = preg_replace('/\$res\[\$r\]\[\'(like)\'\]/im', '$1', $blocks[$r] );
}
$sqlWhere .= $blocks[$r];
}
/* End Block */
$sqlWhere = preg_replace_callback('/(.+)\s+like\s+("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im',
array('XMLConnection','sqlWhereLike'), $sqlWhere );
$sqlWhere = preg_replace_callback('/"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'/im',
array('XMLConnection','sqlString'), $sqlWhere );
/*Start Block: Removing fields */
$xmlFrom = '/' . str_replace( '.','/' , $sqlFrom );
$node =& $this->xmldoc->findNode( $xmlFrom );
if (!isset($node)) {
$err = new DB_Error( "$xmlFrom node not found!." );
return $err;
} else {
$res = $this->fetchChildren ( $node );
}
$newRes = array();
for( $r=0 ; $r < sizeof($res) ; $r++ ) {
$evalWhere = false;
@eval('$evalWhere = '.$sqlWhere.';');
if ( $evalWhere ) {
unset($node->children[$r]);
$newRes[] = $res[$r];
}
}
//Re-index
$node->children = array_values( $node->children );
/* End Block */
$this->xmldoc->save( $this->xmlFile );
$result = new XMLResult( $newRes );
return $result;
}
elseif (1===preg_match('/^\s*INSERT\s+INTO\s+`?([^`]+?)`?\s*\(([\w\W]+?)\)\s+VALUES\s*\(([\w\W]+?)\)\s*$/im',$sql,$matches))
{
$sqlFrom = isset($matches[1])?$matches[1]:'';
$sqlColumns = isset($matches[2])?$matches[2]:'1';
$sqlValues = isset($matches[3])?$matches[3]:'1';
$xmlFrom = '/' . str_replace( '.','/' , $sqlFrom );
$node =& $this->xmldoc->findNode( $xmlFrom );
/* Start Block: Fields list */
$count = preg_match_all('/([\w\.]+)/im',$sqlColumns,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
$fieldsList = array();
for($r=0; $r< $count;$r++) {
$fieldsList[] = $match[1][$r][0];
}
/* End Block */
/* Start Block: Fields Values */
$count=preg_match_all('/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'|\d+)/im', $sqlValues,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
$fieldsValues = array();
for($r=0; $r< $count;$r++) {
if (substr($match[1][$r][0],0,1)==='"') {
$match[1][$r][0] = substr( $match[1][$r][0] ,1, -1 );
$match[1][$r][0] = str_replace('""', '"' , $match[1][$r][0] );
$match[1][$r][0] = str_replace("''", "'" , $match[1][$r][0] );
} if (substr($match[1][$r][0],0,1)==="'") {
$match[1][$r][0] = substr( $match[1][$r][0] ,1, -1 );
$match[1][$r][0] = str_replace("''", "'" , $match[1][$r][0] );
$match[1][$r][0] = str_replace('""', '"' , $match[1][$r][0] );
}
$fieldsValues[$fieldsList[$r]] = $match[1][$r][0];
}
/* End Block */
$AAA = getNames($this->xmldoc->children[0]->children);
$this->insertRow( $node , $fieldsValues );
$DDD = getNames($this->xmldoc->children[0]->children);
$this->xmldoc->save( $this->xmlFile );
$result = new XMLResult( array( $fieldsValues ) );
return $result;
}
elseif (1===preg_match('/^\s*UPDATE\s+`?([^`]+?)`?\s+SET\s+((?:(?:[a-z][\w\.]*)\s*=\s*(?:"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'|\d+)\s*(?:,\s*)?)+)(?:\s+WHERE\s+([\w\W]+?))?\s*$/im',$sql,$matches))
{
$sqlFrom = isset($matches[1])?$matches[1]:'';
$sqlColumns = isset($matches[2])?$matches[2]:'';
$sqlWhere = isset($matches[3])?$matches[3]:'1';
$count = preg_match_all('/([a-z][\w\.]*)\s*=\s*("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'|\d+)/im',$sqlColumns,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
$fieldsValues = array();
for($r=0; $r< $count;$r++) {
if (substr($match[2][$r][0],0,1)==='"') {
$match[2][$r][0] = substr( $match[2][$r][0] ,1, -1 );
$match[2][$r][0] = str_replace('""', '"' , $match[2][$r][0] );
$match[2][$r][0] = str_replace("''", "'" , $match[2][$r][0] );
} if (substr($match[2][$r][0],0,1)==="'") {
$match[2][$r][0] = substr( $match[2][$r][0] ,1, -1 );
$match[2][$r][0] = str_replace("''", "'" , $match[2][$r][0] );
$match[2][$r][0] = str_replace('""', '"' , $match[2][$r][0] );
}
$fieldsValues[$match[1][$r][0]] = $match[2][$r][0];
}
/* Start Block: WHERE*/
/*Start Block: Replace the operator */
$blocks = preg_split('/("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im', $sqlWhere , -1 , PREG_SPLIT_DELIM_CAPTURE );
$sqlWhere = '';
for($r = 0 ; $r < sizeof($blocks) ; $r++ ){
if ( ($r % 2) === 0 ) {
$blocks[$r] = str_replace( '=' , '==', $blocks[$r]);
$blocks[$r] = str_replace( '<>' , '!=', $blocks[$r]);
$blocks[$r] = str_replace( 'AND' , '&&', $blocks[$r]);
$blocks[$r] = str_replace( 'and' , '&&', $blocks[$r]);
$blocks[$r] = str_replace( 'OR' , '||', $blocks[$r]);
$blocks[$r] = str_replace( 'or' , '||', $blocks[$r]);
$blocks[$r] = str_replace( 'NOT' , '!', $blocks[$r]);
$blocks[$r] = str_replace( 'not' , '!', $blocks[$r]);
$blocks[$r] = preg_replace('/\b[a-zA-Z_][\w\.]*\b/im', '$res[$r][\'$0\']', $blocks[$r] );
$blocks[$r] = preg_replace('/\$res\[\$r\]\[\'(like)\'\]/im', '$1', $blocks[$r] );
}
$sqlWhere .= $blocks[$r];
}
/* End Block */
$sqlWhere = preg_replace_callback('/(.+)\s+like\s+("(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\')/im',
array('XMLConnection','sqlWhereLike'), $sqlWhere );
$sqlWhere = preg_replace_callback('/"(?:(?:[^"]|"")*)"|\'(?:(?:[^\']|\'\')*)\'/im',
array('XMLConnection','sqlString'), $sqlWhere );
/*Start Block: Removing fields */
$xmlFrom = '/' . str_replace( '.','/' , $sqlFrom );
$node =& $this->xmldoc->findNode( $xmlFrom );
if (!isset($node)) {
$err = new DB_Error( "$xmlFrom node not found in $dsn." );
return $err;
} else {
$res = $this->fetchChildren ( $node );
}
$newRes = array();
for( $r=0 ; $r < sizeof($res) ; $r++ ) {
$evalWhere = false;
@eval('$evalWhere = '.$sqlWhere.';');
if ( $evalWhere ) {
$this->updateRow( $node->children[$r] , $fieldsValues );
$newRes[] = array_merge( $res[$r] , $fieldsValues );
}
}
/* End Block */
$nodeTEST =& $this->xmldoc->findNode( $xmlFrom );
$this->xmldoc->save( $this->xmlFile );
$result = new XMLResult( $newRes );
return $result;
}
else
{
echo($sql);
$err = new DB_Error( "SQL Query is not well formed." );
return $err;
}
}
/**
* sqlLike
*
* @param string $a
* @return void $b
*/
function sqlLike( $a , $b )
{
$b = addcslashes( $b , '[]()\/{}.?' );
$b = str_replace( "%" , '.*' , $b );
$b = '/^'. $b . '$/im';
return preg_match( $b , $a );
}
/**
* expandFields
*
* @param string $resRow
* @param string $fieldsList
* @return array $res
*/
function expandFields( $resRow, $fieldsList )
{
$res = array();
foreach($fieldsList as $key => $value ) {
if ($key==='*') {
foreach( $resRow as $k => $v ) $res[$k] = $v;
} else {
$res[$key] = array_key_exists( $value , $resRow ) ? $resRow[$value] : NULL;
}
}
return $res;
}
/**
* fetchNode
*
* @param object &$node
* @return array $res
*/
function fetchNode( &$node )
{
$res = array (
'XMLNODE_NAME' => $node->name,
'XMLNODE_TYPE' => $node->type,
'XMLNODE_VALUE' => $node->value,
);
foreach( $node->attributes as $name => $value ) {
if ($this->caseFolding) $name = strtoupper( $name );
$res[$name] = $value;
}
return $res;
}
/**
* fetchChildren
*
* @param string &$node
* @return array $res
*/
function fetchChildren( &$node )
{
$res = array();
foreach( $node->children as $name => $child ) {
$res[] = $this->fetchNode( $child );
}
return $res;
}
/**
* disconnect
*
* @return void
*/
function disconnect()
{
unset( $this->xmldoc );
}
/**
*
*
* @param array $match
* @return object(DB_Error) $err
*/
function sqlWhereLike( $match )
{
switch (substr($match[2],0,1)) {
case '"':
return ' $this->sqlLike( '.$match[1].', '.$match[2].' ) ';
break;
case "'":
return ' $this->sqlLike( '.$match[1].', '.$match[2].' ) ';
break;
default:
$err = new DB_Error( "XMLDB: Syntax error on $match[0]" );
die;
return $err;
}
}
/**
* sqlString
*
* @param array $match
* @return object(DB_Error) $err
*/
function sqlString( $match )
{
switch (substr($match[0],0,1)) {
case '"':
$match[0] = substr( $match[0] ,1, -1 );
$match[0] = str_replace('""', '"' , $match[0] );
$match[0] = str_replace("''", "'" , $match[0] );
$match[0] = addcslashes( $match[0] , '\\\'' );
return "'$match[0]'";
break;
case "'":
$match[0] = substr( $match[0] ,1, -1 );
$match[0] = str_replace("''", "'" , $match[0] );
$match[0] = str_replace('""', '"' , $match[0] );
$match[0] = addcslashes( $match[0] , '\\\'' );
return "'$match[0]'";
break;
default:
$err = new DB_Error( "XMLDB: Syntax error on $match[0]" );
die;
return $err;
}
}
/**
* insertRow
*
* @param string &$node
* @param object $values
* @return void
*/
function insertRow( &$node , $values )
{
$attributes = array();
foreach( $values as $field => $value ) {
switch( $field ) {
case 'XMLNODE_NAME' :
case 'XMLNODE_TYPE' :
case 'XMLNODE_VALUE':
break;
default:
$attributes[strtolower($field)] = $value;
}
}
$values['XMLNODE_NAME'] = !isset($values['XMLNODE_NAME']) ?
'': $values['XMLNODE_NAME'];
$values['XMLNODE_TYPE'] = !isset($values['XMLNODE_TYPE']) ?
'open': $values['XMLNODE_TYPE'];
$values['XMLNODE_VALUE'] = !isset($values['XMLNODE_VALUE']) ?
'': $values['XMLNODE_VALUE'];
$node->addChildNode( new Xml_Node(
$values['XMLNODE_NAME'] , $values['XMLNODE_TYPE'] , $values['XMLNODE_VALUE'], $attributes ) );
}
/**
* updateRow
*
* @param string &$node
* @param object $values
* @return void
*/
function updateRow( &$node , $values )
{
foreach( $values as $field => $value ) {
switch( $field ) {
case 'XMLNODE_NAME' :
$node->name = $value;
break;
case 'XMLNODE_TYPE' :
$node->type = $value;
break;
case 'XMLNODE_VALUE':
$node->value = $value;
break;
default:
$node->attributes[strtolower($field)] = $value;
}
}
}
}
/**
* XMLResult
*
* ProcessMaker Open Source Edition
*
* @copyright (C) 2004 - 2008 Colosa Inc.23
*/
class XMLResult
{
var $result = array();
var $cursor = 0;
/**
* XMLResult
*
* @param array $result
* @return void
*/
function XMLResult( $result = array() )
{
$this->result = $result;
$this->cursor = 0;
}
/**
* numRows
*
* @return integer sizeof($this->result)
*/
function numRows()
{
return sizeof($this->result);
}
/**
* fetchRow
*
* @param string $const
* @return integer $this->result[ $this->cursor-1 ];
*/
function fetchRow ( $const )
{
if ($this->cursor>=$this->numRows())
return NULL;
$this->cursor++;
return $this->result[ $this->cursor-1 ];
}
}
/**
* getNames
*
* @param object $children
* @return array $names
*/
function getNames( $children )
{
$names = array();
$r = 0;
foreach($children as $child) {
$names[$r]=$child->name;
$r++;
}
return $names;
}
?>

View File

@@ -0,0 +1,43 @@
<?php
/**
* class.xmlfield_Image.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.
*
*/
// DEPRECATED this class is also part of the xmlform package this class will be also removed
// in future releases of pm, its discouraged the inclusion this class in the future from a
// external file like this
class XmlForm_Field_Image extends XmlForm_Field
{
var $file = '';
var $home = 'public_html';
var $withoutLabel = false;
function render( $value, $owner = null )
{
$url = G::replaceDataField($this->file, $owner->values);
if ($this->home === "methods") $url = G::encryptlink( SYS_URI . $url );
if ($this->home === "public_html") $url ='/' . $url ;
return '<img src="'.htmlentities( $url, ENT_QUOTES, 'utf-8').'" '.
(($this->style)?'style="'.$this->style.'"':'')
.' alt ="'.htmlentities($value,ENT_QUOTES,'utf-8').'"/>';
}
}
?>

View File

@@ -0,0 +1,463 @@
<?php
/**
* class.xmlfield_InputPM.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.
*
*/
class XmlForm_Field_TextPM extends XmlForm_Field_SimpleText
{
var $size=15;
var $maxLength=64;
var $validate='Any';
var $mask = '';
var $defaultValue='';
var $required=false;
var $dependentFields='';
var $linkField='';
//Possible values:(-|UPPER|LOWER|CAPITALIZE)
var $strTo='';
var $readOnly=false;
var $sqlConnection=0;
var $sql='';
var $sqlOption=array();
//Atributes only for grids
var $formula = '';
var $function = '';
var $replaceTags = 0;
var $showVars = 0;
var $process = '';
var $symbol = '@@';
/**
* Function render
* @author Julio Cesar Laura Avendano <juliocesar@colosa.com>
* @access public
* @parameter string value
* @parameter string owner
* @return string
*/
function render( $value = NULL , $owner = NULL )
{
//$this->executeSQL();
//if (isset($this->sqlOption)) {
// reset($this->sqlOption);
// $firstElement=key($this->sqlOption);
// if (isset($firstElement)) $value = $firstElement;
//}
//NOTE: string functions must be in G class
if ($this->strTo==='UPPER')
$value = strtoupper($value);
if ($this->strTo==='LOWER')
$value = strtolower($value);
//if ($this->strTo==='CAPITALIZE') $value = strtocapitalize($value);
$onkeypress = G::replaceDataField( $this->onkeypress, $owner->values );
if ($this->replaceTags == 1) {
$value = G::replaceDataField( $value, $owner->values );
}
if ($this->showVars == 1) {
$this->process = G::replaceDataField($this->process, $owner->values );
//$sShowVars = '&nbsp;<a href="#" onclick="showDynaformsFormVars(\'form['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;">' . $this->symbol . '</a>';
$sShowVars = '&nbsp;<input type="button" value="' . $this->symbol . '" onclick="showDynaformsFormVars(\'form['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;"/>';
}
else {
$sShowVars = '';
}
if ($this->mode==='edit') {
if ($this->readOnly)
return '<input class="module_app_input___gray" id="form['.$this->name.']" name="form['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value=\''.$this->htmlentities( $value , ENT_COMPAT, 'utf-8').'\' readOnly="readOnly" style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars;
else
return '<input class="module_app_input___gray" id="form['.$this->name.']" name="form['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value=\''.$this->htmlentities( $value , ENT_COMPAT, 'utf-8').'\' style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars;
} elseif ($this->mode==='view') {
return '<input class="module_app_input___gray" id="form['.$this->name.']" name="form['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value=\''.$this->htmlentities( $value , ENT_COMPAT, 'utf-8').'\' style="display:none;'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' .
$this->htmlentities( $value , ENT_COMPAT, 'utf-8');
} else {
return $this->htmlentities( $value , ENT_COMPAT, 'utf-8');
}
}
/**
* Function renderGrid
* @author Julio Cesar Laura Avendano <juliocesar@colosa.com>
* @access public
* @parameter array values
* @parameter string owner
* @return string
*/
function renderGrid( $values=array() , $owner )
{
$result=array();
$r=1;
foreach($values as $v) {
if ($this->replaceTags == 1) {
$v = G::replaceDataField( $v, $owner->values );
}
if ($this->showVars == 1) {
$this->process = G::replaceDataField($this->process, $owner->values );
//$sShowVars = '&nbsp;<a href="#" onclick="showDynaformsFormVars(\'form['.$owner->name .']['.$r.']['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;">' . $this->symbol . '</a>';
$sShowVars = '&nbsp;<input type="button" value="' . $this->symbol . '" onclick="showDynaformsFormVars(\'form['.$owner->name .']['.$r.']['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;"/>';
}
else {
$sShowVars = '';
}
if ($this->mode==='edit') {
if ($this->readOnly)
$result[] = '<input class="module_app_input___gray" id="form['. $owner->name .']['.$r.']['.$this->name.']" name="form['. $owner->name .']['.$r.']['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value="'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'" readOnly="readOnly" style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars;
else
$result[] = '<input class="module_app_input___gray" id="form['. $owner->name .']['.$r.']['.$this->name.']" name="form['. $owner->name .']['.$r.']['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value="'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'" style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars;
} elseif ($this->mode==='view') {
$result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8');
} else {
$result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8');
}
$r++;
}
return $result;
}
/**
* Function attachEvents
* @access public
* @parameter string $element
* @return string
*/
function attachEvents($element)
{
return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}');
myForm.aElements[i].setAttributes(" . $this->getAttributes() . ");";
}
}
/**
* Class XmlForm_Field_TextareaPM
*/
class XmlForm_Field_TextareaPM extends XmlForm_Field
{
var $rows = 12;
var $cols = 40;
var $required = false;
var $readOnly = false;
var $wrap = 'OFF';
var $showVars = 0;
var $process = '';
var $symbol = '@@';
/**
* Function render
* @author Julio Cesar Laura Avendao <juliocesar@colosa.com>
* @access public
* @parameter string value
* @parameter string owner
* @return string
*/
function render( $value = NULL, $owner )
{
if ($this->showVars == 1) {
$this->process = G::replaceDataField($this->process, $owner->values );
$sShowVars = '&nbsp;<input type="button" value="' . $this->symbol . '" onclick="showDynaformsFormVars(\'form['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;"/>';
}
else {
$sShowVars = '';
}
if ($this->mode==='edit') {
if ($this->readOnly)
return '<textarea id="form['.$this->name.']" name="form['.$this->name.']" cols="'.$this->cols.'" rows="'.$this->rows.'" style="'.$this->style.'" wrap="'.htmlentities($this->wrap,ENT_QUOTES,'UTF-8').'" class="FormTextPM" readOnly>'.$this->htmlentities( $value ,ENT_COMPAT,'utf-8').'</textarea>' . $sShowVars;
else
return '<textarea id="form['.$this->name.']" name="form['.$this->name.']" cols="'.$this->cols.'" rows="'.$this->rows.'" style="'.$this->style.'" wrap="'.htmlentities($this->wrap,ENT_QUOTES,'UTF-8').'" class="FormTextPM" >'.$this->htmlentities( $value ,ENT_COMPAT,'utf-8').'</textarea>' . $sShowVars;
} elseif ($this->mode==='view') {
return '<textarea id="form['.$this->name.']" name="form['.$this->name.']" cols="'.$this->cols.'" rows="'.$this->rows.'" readOnly style="border:0px;backgroud-color:inherit;'.$this->style.'" wrap="'.htmlentities($this->wrap,ENT_QUOTES,'UTF-8').'" class="FormTextPM" >'.$this->htmlentities( $value ,ENT_COMPAT,'utf-8').'</textarea>';
} else {
return '<textarea id="form['.$this->name.']" name="form['.$this->name.']" cols="'.$this->cols.'" rows="'.$this->rows.'" style="'.$this->style.'" wrap="'.htmlentities($this->wrap,ENT_QUOTES,'UTF-8').'" class="FormTextArea" >'.$this->htmlentities( $value ,ENT_COMPAT,'utf-8').'</textarea>';
}
}
/**
* Function renderGrid
* @author Julio Cesar Laura Avendano <juliocesar@colosa.com>
* @access public
* @parameter string values
* @parameter string owner
* @return string
*/
function renderGrid( $values = NULL , $owner )
{
$result=array();
$r=1;
foreach($values as $v) {
if ($this->showVars == 1) {
$this->process = G::replaceDataField($this->process, $owner->values );
//$sShowVars = '&nbsp;<a href="#" onclick="showDynaformsFormVars(\'form['.$owner->name .']['.$r.']['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;">' . $this->symbol . '</a>';
$sShowVars = '&nbsp;<input type="button" value="' . $this->symbol . '" onclick="showDynaformsFormVars(\'form['.$owner->name .']['.$r.']['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;"/>';
}
else {
$sShowVars = '';
}
if ($this->mode==='edit') {
if ($this->readOnly)
$result[] = '<input class="module_app_input___gray" id="form['. $owner->name .']['.$r.']['.$this->name.']" name="form['. $owner->name .']['.$r.']['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value=\''.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'\' readOnly="readOnly"/>' . $sShowVars;
else
$result[] = '<input class="module_app_input___gray" id="form['. $owner->name .']['.$r.']['.$this->name.']" name="form['. $owner->name .']['.$r.']['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value=\''.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'\' />' . $sShowVars;
} elseif ($this->mode==='view') {
if(stristr($_SERVER['HTTP_USER_AGENT'], 'iPhone')){
//$result[] = '<div style="overflow:hidden;height:25px;padding:0px;margin:0px;">'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'</div>';
$result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8');
}
else{
//$result[] = '<div style="overflow:hidden;width:inherit;height:2em;padding:0px;margin:0px;">'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'</div>';
$result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8');
}
} else{
$result[] = $this->htmlentities( $v , ENT_COMPAT, 'utf-8');
}
$r++;
}
return $result;
}
}
/**
* Class XmlForm_Field_hours
*/
class XmlForm_Field_hours extends XmlForm_Field_SimpleText
{
var $size = 15;
var $maxLength = 64;
var $validate = 'Any';
var $mask = '';
var $defaultValue = '';
var $required = false;
var $dependentFields= '';
var $linkField = '';
//Possible values:(-|UPPER|LOWER|CAPITALIZE)
var $strTo = '';
var $readOnly = false;
var $sqlConnection = 0;
var $sql = '';
var $sqlOption = array();
//Atributes only for grids
var $formula = '';
var $function = '';
var $replaceTags = 0;
var $showVars = 0;
var $process = '';
var $symbol = '@@';
/**
* Function render
* @author Julio Cesar Laura Avendano <juliocesar@colosa.com>
* @access public
* @parameter string value
* @parameter string owner
* @return string
*/
function render( $value = NULL , $owner = NULL )
{
if ($this->strTo==='UPPER')
$value = strtoupper($value);
if ($this->strTo==='LOWER')
$value = strtolower($value);
//if ($this->strTo==='CAPITALIZE') $value = strtocapitalize($value);
$onkeypress = G::replaceDataField( $this->onkeypress, $owner->values );
if ($this->replaceTags == 1) {
$value = G::replaceDataField( $value, $owner->values );
}
if ($this->showVars == 1) {
$this->process = G::replaceDataField($this->process, $owner->values );
//$sShowVars = '&nbsp;<a href="#" onclick="showDynaformsFormVars(\'form['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;">' . $this->symbol . '</a>';
$sShowVars = '&nbsp;<input type="button" value="' . $this->symbol . '" onclick="showDynaformsFormVars(\'form['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;"/>';
}
else {
$sShowVars = '';
}
if ($this->mode==='edit') {
if ($this->readOnly)
return '<input class="module_app_input___gray" id="form['.$this->name.']" name="form['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value=\''.$this->htmlentities( $value , ENT_COMPAT, 'utf-8').'\' readOnly="readOnly" style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars;
else
return '<input class="module_app_input___gray" id="form['.$this->name.']" name="form['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value=\''.$this->htmlentities( $value , ENT_COMPAT, 'utf-8').'\' style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars;
} elseif ($this->mode==='view') {
return '<input class="module_app_input___gray" id="form['.$this->name.']" name="form['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value=\''.$this->htmlentities( $value , ENT_COMPAT, 'utf-8').'\' style="display:none;'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'" onkeypress="'.htmlentities( $onkeypress , ENT_COMPAT, 'utf-8').'"/>' .
$this->htmlentities( $value , ENT_COMPAT, 'utf-8');
} else {
return $this->htmlentities( $value , ENT_COMPAT, 'utf-8');
}
}
/**
* Function renderGrid
* @author Julio Cesar Laura Avendano <juliocesar@colosa.com>
* @access public
* @parameter array values
* @parameter string owner
* @return string
*/
function renderGrid( $values=array() , $owner )
{
$result=array();
$r=1;
foreach($values as $v) {
if ($this->replaceTags == 1) {
$v = G::replaceDataField( $v, $owner->values );
}
if ($this->showVars == 1) {
$this->process = G::replaceDataField($this->process, $owner->values );
//$sShowVars = '&nbsp;<a href="#" onclick="showDynaformsFormVars(\'form['.$owner->name .']['.$r.']['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;">' . $this->symbol . '</a>';
$sShowVars = '&nbsp;<input type="button" value="' . $this->symbol . '" onclick="showDynaformsFormVars(\'form['.$owner->name .']['.$r.']['.$this->name.']\', \'../controls/varsAjax\', \'' . $this->process . '\', \'' . $this->symbol . '\');return false;"/>';
}
else {
$sShowVars = '';
}
if ($this->mode==='edit') {
if ($this->readOnly)
$result[] = '<input class="module_app_input___gray" id="form['. $owner->name .']['.$r.']['.$this->name.']" name="form['. $owner->name .']['.$r.']['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value="'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'" readOnly="readOnly" style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars;
else
$result[] = '<input class="module_app_input___gray" id="form['. $owner->name .']['.$r.']['.$this->name.']" name="form['. $owner->name .']['.$r.']['.$this->name.']" type ="text" size="'.$this->size.'" maxlength="'.$this->maxLength.'" value="'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'" style="'.htmlentities( $this->style , ENT_COMPAT, 'utf-8').'"/>' . $sShowVars;
} elseif ($this->mode==='view') {
$result[] = '<p align="'.$this->align.'">'.$this->htmlentities( number_format($v, 2), ENT_COMPAT, 'utf-8').'</p>';
} else {
$result[] = '<p align="'.$this->align.'">'.$this->htmlentities( number_format($v, 2), ENT_COMPAT, 'utf-8').'</p>';
}
$r++;
}
return $result;
}
/**
* Function attachEvents
* @access public
* @parameter string $element
* @return string
*/
function attachEvents($element)
{
return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}');
myForm.aElements[i].setAttributes(" . $this->getAttributes() . ");";
}
}
/**
* Function getDynaformsVars
* @access public
* @parameter string $sProcessUID
* @parameter boolean $bSystemVars
* @return array
*/
function getDynaformsVars($sProcessUID, $bSystemVars = true)
{
$aFields = array();
$aFieldsNames = array();
if ($bSystemVars) {
$aAux = G::getSystemConstants();
foreach ($aAux as $sName => $sValue) {
$aFields[] = array('sName' => $sName, 'sType' => 'system', 'sLabel'=> 'System variable');
}
}
require_once 'classes/model/Dynaform.php';
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(DynaformPeer::DYN_FILENAME);
$oCriteria->add(DynaformPeer::PRO_UID, $sProcessUID);
$oCriteria->add(DynaformPeer::DYN_TYPE, 'xmlform');
$oDataset = DynaformPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
if (file_exists(PATH_DYNAFORM . PATH_SEP . $aRow['DYN_FILENAME'] . '.xml')) {
$G_FORM = new Form($aRow['DYN_FILENAME'], PATH_DYNAFORM, SYS_LANG);
if (($G_FORM->type == 'xmlform') || ($G_FORM->type == '')) {
foreach($G_FORM->fields as $k => $v) {
if (($v->type != 'title') && ($v->type != 'subtitle') && ($v->type != 'link') &&
($v->type != 'file') && ($v->type != 'button') && ($v->type != 'reset') &&
($v->type != 'submit') && ($v->type != 'listbox') && ($v->type != 'checkgroup') &&
($v->type != 'grid') && ($v->type != 'javascript')) {
if (!in_array($k, $aFieldsNames)) {
$aFields[] = array('sName' => $k,
'sType' => $v->type,
'sLabel'=> $v->label
);
$aFieldsNames[] = $k;
}
}
}
}
}
$oDataset->next();
}
return $aFields;
}
/**
* Function getGridsVars
* @access public
* @parameter string $sProcessUID
* @return array
*/
function getGridsVars($sProcessUID)
{
$aFields = array();
$aFieldsNames = array();
require_once 'classes/model/Dynaform.php';
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(DynaformPeer::DYN_FILENAME);
$oCriteria->add(DynaformPeer::PRO_UID, $sProcessUID);
$oDataset = DynaformPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$G_FORM = new Form($aRow['DYN_FILENAME'], PATH_DYNAFORM, SYS_LANG);
if ($G_FORM->type == 'xmlform') {
foreach($G_FORM->fields as $k => $v) {
if ($v->type == 'grid') {
if (!in_array($k, $aFieldsNames)) {
$aFields[] = array('sName' => $k, 'sXmlForm' => str_replace($sProcessUID . '/', '', $v->xmlGrid));
$aFieldsNames[] = $k;
}
}
}
}
$oDataset->next();
}
return $aFields;
}
/**
* Class XmlForm_Field_CheckBoxTable
*/
class XmlForm_Field_CheckBoxTable extends XmlForm_Field_Checkbox
{
/**
* Function render
* @author The Answer
* @access public
* @parameter string value
* @parameter string owner
* @return string
*/
function render( $value = NULL , $owner = NULL )
{
//$optionName = $owner->values['USR_UID'];
$optionName = $value;
$onclick = (($this->onclick)? ' onclick="' . G::replaceDataField( $this->onclick, $owner->values ) . '" ' : '');
$html ='<input class="FormCheck" id="form['.$this->name.']['.$optionName.']" name="form['.$this->name.
']['.$optionName.']" type=\'checkbox\' value="'. $value . '"' . $onclick .
'> <span class="FormCheck"></span></input>';
return $html;
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseAdditionalTablesPeer.php';
// include object class
include_once 'classes/model/AdditionalTables.php';
/**
* Skeleton subclass for performing query and update operations on the 'ADDITIONAL_TABLES' 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 AdditionalTablesPeer extends BaseAdditionalTablesPeer {
} // AdditionalTablesPeer

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseAppCacheViewPeer.php';
// include object class
include_once 'classes/model/AppCacheView.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_CACHE_VIEW' 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 AppCacheViewPeer extends BaseAppCacheViewPeer {
} // AppCacheViewPeer

View File

@@ -0,0 +1,118 @@
<?php
require_once 'classes/model/om/BaseAppDelay.php';
/**
* Skeleton subclass for representing a row from the 'APP_DELAY' 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 AppDelay extends BaseAppDelay {
/**
* Create the application delay registry
* @param array $aData
* @return string
**/
public function create($aData)
{
$oConnection = Propel::getConnection(AppDelayPeer::DATABASE_NAME);
try {
if ( isset ( $aData['APP_DELAY_UID'] ) && $aData['APP_DELAY_UID']== '' )
unset ( $aData['APP_DELAY_UID'] );
if ( !isset ( $aData['APP_DELAY_UID'] ) )
$aData['APP_DELAY_UID'] = G::generateUniqueID();
$oAppDelay = new AppDelay();
$oAppDelay->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($oAppDelay->validate()) {
$oConnection->begin();
$iResult = $oAppDelay->save();
$oConnection->commit();
return $aData['APP_DELAY_UID'];
}
else {
$sMessage = '';
$aValidationFailures = $oAppDelay->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be created!<br />'.$sMessage));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
/**
* Update the application delay registry
* @param array $aData
* @return string
**/
public function update($aData)
{
$oConnection = Propel::getConnection(AppDelayPeer::DATABASE_NAME);
try {
$oAppDelay = AppDelayPeer::retrieveByPK($aData['APP_DELAY_UID']);
if (!is_null($oAppDelay))
{
$oAppDelay->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($oAppDelay->validate()) {
$oConnection->begin();
$iResult = $oAppDelay->save();
$oConnection->commit();
return $iResult;
}
else {
$sMessage = '';
$aValidationFailures = $oAppDelay->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be updated!<br />'.$sMessage));
}
}
else {
throw(new Exception('This row doesn\'t exists!'));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
function isPaused($appUid, $delIndex){
$oCriteria = new Criteria('workflow');
$oCriteria->add(AppDelayPeer::APP_UID, $appUid);
$oCriteria->add(AppDelayPeer::APP_DEL_INDEX, $delIndex);
$oCriteria->add(AppDelayPeer::APP_TYPE, 'PAUSE');
$oCriteria->add(AppDelayPeer::APP_DISABLE_ACTION_USER, null);
$oCriteria->add(
$oCriteria->getNewCriterion(
AppDelayPeer::APP_DISABLE_ACTION_USER,
null,
Criteria::ISNULL
)->addOr(
$oCriteria->getNewCriterion(AppDelayPeer::APP_DISABLE_ACTION_USER, 0)
)
);
$oDataset = AppDelayPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aRow = $oDataset->getRow();
if( $aRow )
return true;
else
return false;
}
} // AppDelay

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseAppDelayPeer.php';
// include object class
include_once 'classes/model/AppDelay.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_DELAY' 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 AppDelayPeer extends BaseAppDelayPeer {
} // AppDelayPeer

View File

@@ -0,0 +1,415 @@
<?php
/**
* AppDelegation.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.
*
*/
require_once 'classes/model/om/BaseAppDelegation.php';
require_once ( "classes/model/HolidayPeer.php" );
require_once ( "classes/model/TaskPeer.php" );
G::LoadClass("dates");
/**
* Skeleton subclass for representing a row from the 'APP_DELEGATION' 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 AppDelegation extends BaseAppDelegation {
/**
* create an application delegation
* @param $sProUid process Uid
* @param $sAppUid Application Uid
* @param $sTasUid Task Uid
* @param $sUsrUid User Uid
* @param $iPriority delegation priority
* @param $isSubprocess is a subprocess inside a process?
* @return delegation index of the application delegation.
*/
function createAppDelegation ($sProUid, $sAppUid, $sTasUid, $sUsrUid, $sAppThread, $iPriority = 3, $isSubprocess=false, $sPrevious=-1 ) {
if (!isset($sProUid) || strlen($sProUid) == 0 ) {
throw ( new Exception ( 'Column "PRO_UID" cannot be null.' ) );
}
if (!isset($sAppUid) || strlen($sAppUid ) == 0 ) {
throw ( new Exception ( 'Column "APP_UID" cannot be null.' ) );
}
if (!isset($sTasUid) || strlen($sTasUid ) == 0 ) {
throw ( new Exception ( 'Column "TAS_UID" cannot be null.' ) );
}
if (!isset($sUsrUid) /*|| strlen($sUsrUid ) == 0*/ ) {
throw ( new Exception ( 'Column "USR_UID" cannot be null.' ) );
}
if (!isset($sAppThread) || strlen($sAppThread ) == 0 ) {
throw ( new Exception ( 'Column "APP_THREAD" cannot be null.' ) );
}
//get max DEL_INDEX SELECT MAX(DEL_INDEX) AS M FROM APP_DELEGATION WHERE APP_UID="'.$Fields['APP_UID'].'"'
$c = new Criteria ();
$c->clearSelectColumns();
$c->addSelectColumn ( 'MAX(' . AppDelegationPeer::DEL_INDEX . ') ' );
$c->add ( AppDelegationPeer::APP_UID, $sAppUid );
$rs = AppDelegationPeer::doSelectRS ( $c );
$rs->next();
$row = $rs->getRow();
$delIndex = $row[0] + 1;
$this->setAppUid ( $sAppUid );
$this->setProUid ( $sProUid );
$this->setTasUid ( $sTasUid );
$this->setDelIndex ( $delIndex );
$this->setDelPrevious ( $sPrevious == -1 ? 0 : $sPrevious );
$this->setUsrUid ( $sUsrUid );
$this->setDelType ( 'NORMAL' );
$this->setDelPriority ( ($iPriority != '' ? $iPriority : '3') );
$this->setDelThread ( $sAppThread );
$this->setDelThreadStatus ( 'OPEN' );
$this->setDelDelegateDate ( 'now' );
//The function return an array now. By JHL
$delTaskDueDate=$this->calculateDueDate();
$this->setDelTaskDueDate ( $delTaskDueDate['DUE_DATE'] ); // Due date formatted
$this->setDelData ( '' ); //$delTaskDueDate['DUE_DATE_LOG'] ); // Log of actions made by Calendar Engine
// this condition assures that an internal delegation like a subprocess dont have an initial date setted
if ( $delIndex == 1 && !$isSubprocess ) //the first delegation, init date this should be now for draft applications, in other cases, should be null.
$this->setDelInitDate ('now' );
if ($this->validate() ) {
try {
$res = $this->save();
}
catch ( PropelException $e ) {
throw ( $e );
}
}
else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = '';
$validationFailuresArray = $this->getValidationFailures();
foreach($validationFailuresArray as $objValidationFailure) {
$msg .= $objValidationFailure->getMessage() . "<br/>";
}
throw ( new Exception ( 'Failed Data validation saving APP_DELEGATION row: ' . $msg ) );
}
return $this->getDelIndex();
}
/**
* Load the Application Delegation row specified in [app_id] column value.
*
* @param string $AppUid the uid of the application
* @return array $Fields the fields
*/
function Load ( $AppUid, $sDelIndex ) {
$con = Propel::getConnection(AppDelegationPeer::DATABASE_NAME);
try {
$oAppDel = AppDelegationPeer::retrieveByPk( $AppUid, $sDelIndex );
if ( get_class ($oAppDel) == 'AppDelegation' ) {
$aFields = $oAppDel->toArray( BasePeer::TYPE_FIELDNAME);
$this->fromArray ($aFields, BasePeer::TYPE_FIELDNAME );
return $aFields;
}
else {
throw( new Exception( "The row '$AppUid, $sDelIndex' in table AppDelegation doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Update the application row
* @param array $aData
* @return variant
**/
public function update($aData)
{
$con = Propel::getConnection( AppDelegationPeer::DATABASE_NAME );
try {
$con->begin();
$oApp = AppDelegationPeer::retrieveByPK( $aData['APP_UID'], $aData['DEL_INDEX'] );
if ( get_class ($oApp) == 'AppDelegation' ) {
$oApp->fromArray( $aData, BasePeer::TYPE_FIELDNAME );
if ($oApp->validate()) {
$res = $oApp->save();
$con->commit();
return $res;
}
else {
$msg = '';
foreach($this->getValidationFailures() as $objValidationFailure)
$msg .= $objValidationFailure->getMessage() . "<br/>";
throw ( new PropelException ( 'The row cannot be created!', new PropelException ( $msg ) ) );
}
}
else {
$con->rollback();
throw(new Exception( "This AppDelegation row doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
function remove($sApplicationUID, $iDelegationIndex) {
$oConnection = Propel::getConnection(StepTriggerPeer::DATABASE_NAME);
try {
$oConnection->begin();
$oApp = AppDelegationPeer::retrieveByPK( $sApplicationUID, $iDelegationIndex );
if ( get_class ($oApp) == 'AppDelegation' ) {
$result = $oApp->delete();
}
$oConnection->commit();
return $result;
}
catch(Exception $e) {
$oConnection->rollback();
throw($e);
}
}
// TasTypeDay = 1 => working days
// TasTypeDay = 2 => calendar days
function calculateDueDate()
{
//Get Task properties
$task = TaskPeer::retrieveByPK( $this->getTasUid() );
//use the dates class to calculate dates
$dates = new dates();
$iDueDate = $dates->calculateDate( $this->getDelDelegateDate(),
$task->getTasDuration(),
$task->getTasTimeUnit(), //hours or days, ( we only accept this two types or maybe weeks
$task->getTasTypeDay(), //working or calendar days
$this->getUsrUid(),
$task->getProUid(),
$this->getTasUid() );
return $iDueDate;
}
function getDiffDate ( $date1, $date2 ) {
return ( $date1 - $date2 )/(24*60*60); //days
return ( $date1 - $date2 ) / 3600;
}
function calculateDuration() {
try {
//patch rows with initdate = null and finish_date
$c = new Criteria();
$c->clearSelectColumns();
$c->addSelectColumn(AppDelegationPeer::APP_UID );
$c->addSelectColumn(AppDelegationPeer::DEL_INDEX );
$c->addSelectColumn(AppDelegationPeer::DEL_DELEGATE_DATE);
$c->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE);
$c->add(AppDelegationPeer::DEL_INIT_DATE, NULL, Criteria::ISNULL);
$c->add(AppDelegationPeer::DEL_FINISH_DATE, NULL, Criteria::ISNOTNULL);
//$c->add(AppDelegationPeer::DEL_INDEX, 1);
$rs = AppDelegationPeer::doSelectRS($c);
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rs->next();
$row = $rs->getRow();
while (is_array($row)) {
$oAppDel = AppDelegationPeer::retrieveByPk($row['APP_UID'], $row['DEL_INDEX'] );
if ( isset ($row['DEL_FINISH_DATE']) )
$oAppDel->setDelInitDate($row['DEL_FINISH_DATE']);
else
$oAppDel->setDelInitDate($row['DEL_INIT_DATE']);
$oAppDel->save();
$rs->next();
$row = $rs->getRow();
}
//walk in all rows with DEL_STARTED = 0 or DEL_FINISHED = 0
$c = new Criteria('workflow');
$c->clearSelectColumns();
$c->addSelectColumn(AppDelegationPeer::APP_UID );
$c->addSelectColumn(AppDelegationPeer::DEL_INDEX );
$c->addSelectColumn(AppDelegationPeer::DEL_DELEGATE_DATE);
$c->addSelectColumn(AppDelegationPeer::DEL_INIT_DATE);
$c->addSelectColumn(AppDelegationPeer::DEL_TASK_DUE_DATE);
$c->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE);
$c->addSelectColumn(AppDelegationPeer::DEL_DURATION);
$c->addSelectColumn(AppDelegationPeer::DEL_QUEUE_DURATION);
$c->addSelectColumn(AppDelegationPeer::DEL_DELAY_DURATION);
$c->addSelectColumn(AppDelegationPeer::DEL_STARTED);
$c->addSelectColumn(AppDelegationPeer::DEL_FINISHED);
$c->addSelectColumn(AppDelegationPeer::DEL_DELAYED);
$c->addSelectColumn(TaskPeer::TAS_DURATION);
$c->addSelectColumn(TaskPeer::TAS_TIMEUNIT);
$c->addSelectColumn(TaskPeer::TAS_TYPE_DAY);
$c->addJoin(AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN );
//$c->add(AppDelegationPeer::DEL_INIT_DATE, NULL, Criteria::ISNULL);
//$c->add(AppDelegationPeer::APP_UID, '7694483844a37bfeb0931b1063501289');
//$c->add(AppDelegationPeer::DEL_STARTED, 0);
$cton1 = $c->getNewCriterion(AppDelegationPeer::DEL_STARTED, 0);
$cton2 = $c->getNewCriterion(AppDelegationPeer::DEL_FINISHED, 0);
$cton1->addOR($cton2);
$c->add($cton1);
$rs = AppDelegationPeer::doSelectRS($c);
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rs->next();
$row = $rs->getRow();
$i =0;
//print "<table colspacing='2' border='1'>";
//print "<tr><td>iDelegateDate </td><td>iInitDate </td><td>iDueDate </td><td>iFinishDate </td><td>isStarted </td><td>isFinished </td><td>isDelayed </td><td>queueDuration </td><td>delDuration </td><td>delayDuration</td></tr>";
$now = strtotime ( 'now' );
while ( is_array($row) ) {
$fTaskDuration = $row['TAS_DURATION'];
$iDelegateDate = strtotime ( $row['DEL_DELEGATE_DATE'] );
$iInitDate = strtotime ( $row['DEL_INIT_DATE'] );
$iDueDate = strtotime ( $row['DEL_TASK_DUE_DATE'] );
$iFinishDate = strtotime ( $row['DEL_FINISH_DATE'] );
$isStarted = intval ( $row['DEL_STARTED'] );
$isFinished = intval ( $row['DEL_FINISHED'] );
$isDelayed = intval ( $row['DEL_DELAYED'] );
$queueDuration = $this->getDiffDate ($iInitDate, $iDelegateDate);
$delDuration = 0;
$delayDuration = 0;
$overduePercentage = 0.0;
//get the object,
$oAppDel = AppDelegationPeer::retrieveByPk($row['APP_UID'], $row['DEL_INDEX'] );
//if the task is not started
if ( $isStarted == 0 ) {
if ( $row['DEL_INIT_DATE'] != NULL && $row['DEL_INIT_DATE'] != '' ) {
$oAppDel->setDelStarted(1);
$queueDuration = $this->getDiffDate ($iInitDate, $iDelegateDate );
$oAppDel->setDelQueueDuration( $queueDuration);
}
else {//the task was not started
$queueDuration = $this->getDiffDate ( $now, $iDelegateDate );
$oAppDel->setDelQueueDuration( $queueDuration);
//we are putting negative number if the task is not delayed, and positive number for the time the task is delayed
$delayDuration = $this->getDiffDate ($now, $iDueDate );
$oAppDel->setDelDelayDuration( $delayDuration);
if ( $fTaskDuration != 0) {
$overduePercentage = $delayDuration / $fTaskDuration;
$oAppDel->setAppOverduePercentage( $overduePercentage);
if ( $iDueDate < $now ) {
$oAppDel->setDelDelayed(1);
}
}
}
}
//if the task was not finished
if ( $isFinished == 0 ) {
if ( $row['DEL_FINISH_DATE'] != NULL && $row['DEL_FINISH_DATE'] != '') {
$oAppDel->setAppOverduePercentage($overduePercentage);
$oAppDel->setDelFinished(1);
$delDuration = $this->getDiffDate ($iFinishDate, $iInitDate );
$oAppDel->setDelDuration( $delDuration);
//calculate due date if correspond
if ( $iDueDate < $iFinishDate ) {
$oAppDel->setDelDelayed(1);
$delayDuration = $this->getDiffDate ($iFinishDate, $iDueDate );
}
else {
$oAppDel->setDelDelayed(0);
$delayDuration = 0;
}
}
else { //the task was not completed
if ( $row['DEL_INIT_DATE'] != NULL && $row['DEL_INIT_DATE'] != '' ) {
$delDuration = $this->getDiffDate ($now, $iInitDate );
}
else
$delDuration = $this->getDiffDate ($now, $iDelegateDate);
$oAppDel->setDelDuration( $delDuration);
//we are putting negative number if the task is not delayed, and positive number for the time the task is delayed
$delayDuration = $this->getDiffDate ($now, $iDueDate );
$oAppDel->setDelDelayDuration( $delayDuration);
if ( $fTaskDuration != 0) {
$overduePercentage = $delayDuration / $fTaskDuration;
$oAppDel->setAppOverduePercentage($overduePercentage );
if ( $iDueDate < $now ) {
$oAppDel->setDelDelayed(1);
}
}
}
}
//and finally save the record
$RES = $oAppDel->save();
//print "<tr><td>$iDelegateDate </td><td>$iInitDate </td><td>$iDueDate </td><td>$iFinishDate </td><td>$isStarted </td><td>$isFinished </td><td>$isDelayed</td><td>$queueDuration </td><td>$delDuration </td>" .
// "<td>$delayDuration</td><td>$overduePercentage</td><td>" . $row['DEL_INDEX'] . " $RES </td></tr>";
//UPDATE APP_DELEGATION SET DEL_DELAYED = 0
//where
// APP_OVERDUE_PERCENTAGE < 0
$rs->next();
$row = $rs->getRow();
}
}
catch ( Exception $oError) {
//krumo ( $oError->getMessage() );
}
}
function getLastDeleration($APP_UID){
$c = new Criteria('workflow');
$c->addSelectColumn(AppDelegationPeer::APP_UID );
$c->addSelectColumn(AppDelegationPeer::DEL_INDEX );
$c->addSelectColumn(AppDelegationPeer::DEL_DELEGATE_DATE);
$c->addSelectColumn(AppDelegationPeer::DEL_INIT_DATE);
$c->addSelectColumn(AppDelegationPeer::DEL_TASK_DUE_DATE);
$c->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE);
$c->addSelectColumn(AppDelegationPeer::DEL_DURATION);
$c->addSelectColumn(AppDelegationPeer::DEL_QUEUE_DURATION);
$c->addSelectColumn(AppDelegationPeer::DEL_DELAY_DURATION);
$c->addSelectColumn(AppDelegationPeer::DEL_STARTED);
$c->addSelectColumn(AppDelegationPeer::DEL_FINISHED);
$c->addSelectColumn(AppDelegationPeer::DEL_DELAYED);
$c->addSelectColumn(AppDelegationPeer::USR_UID);
$c->add(AppDelegationPeer::APP_UID, $APP_UID);
$c->addDescendingOrderByColumn(AppDelegationPeer::DEL_INDEX);
$rs = AppDelegationPeer::doSelectRS($c);
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rs->next();
return $rs->getRow();
}
} // AppDelegation

View File

@@ -0,0 +1,46 @@
<?php
/**
* AppDelegationPeer.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.
*
*/
// include base peer class
require_once 'classes/model/om/BaseAppDelegationPeer.php';
// include object class
include_once 'classes/model/AppDelegation.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_DELEGATION' 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 AppDelegationPeer extends BaseAppDelegationPeer {
} // AppDelegationPeer

View File

@@ -0,0 +1,574 @@
<?php
/**
* AppDocument.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.
*
*/
require_once 'classes/model/om/BaseAppDocument.php';
require_once 'classes/model/Content.php';
require_once 'classes/model/InputDocument.php';
/**
* Skeleton subclass for representing a row from the 'APP_DOCUMENT' 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 AppDocument extends BaseAppDocument {
/**
* This value goes in the content table
* @var string
*/
protected $app_doc_title = '';
/**
* This value goes in the content table
* @var string
*/
protected $app_doc_comment = '';
/**
* This value goes in the content table
* @var string
*/
protected $app_doc_filename = '';
/*
* Load the application document registry
* @param string $sAppDocUid
* @param integer $iVersion (Document version)
* @return variant
*/
public function load($sAppDocUid,$iVersion=NULL)
{
try {
if($iVersion==NULL) $iVersion=$this->getLastAppDocVersion($sAppDocUid);
$oAppDocument = AppDocumentPeer::retrieveByPK($sAppDocUid,$iVersion);
if (!is_null($oAppDocument))
{
$aFields = $oAppDocument->toArray(BasePeer::TYPE_FIELDNAME);
//optimized for speed
$aContentFields = $oAppDocument->getContentFields();
$aFields['APP_DOC_TITLE'] = $aContentFields['APP_DOC_TITLE'];
$aFields['APP_DOC_COMMENT'] = $aContentFields['APP_DOC_COMMENT'];
$aFields['APP_DOC_FILENAME'] = $aContentFields['APP_DOC_FILENAME'];
$this->fromArray($aFields, BasePeer::TYPE_FIELDNAME);
return $aFields;
}
else {
throw(new Exception('Error loading Document '.$sAppDocUid.'/'.$iVersion.'. This row doesn\'t exists!'));
}
}
catch (Exception $oError) {
throw($oError);
}
}
public function getLastIndex( $sAppUid )
{
try {
$oCriteria = new Criteria();
$oCriteria->add( AppDocumentPeer::APP_UID , $sAppUid );
//$oCriteria->addAscendingOrderByColumn ( AppDocumentPeer::APP_DOC_INDEX );
$oCriteria->addDescendingOrderByColumn( AppDocumentPeer::APP_DOC_INDEX );
$lastAppDoc = AppDocumentPeer::doSelectOne($oCriteria);
if (!is_null($lastAppDoc))
{
return $lastAppDoc->getAppDocIndex();
}
else {
return 0;
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Get last Document Version based on Doc UID
* @param s $sAppDocUid
* @return integer
**/
public function getLastDocVersion( $sDocUid ,$appUID)
{
try {
$oCriteria = new Criteria();
$oCriteria->add(AppDocumentPeer::DOC_UID, $sDocUid );
$oCriteria->add(AppDocumentPeer::APP_UID, $appUID);
$oCriteria->addDescendingOrderByColumn( AppDocumentPeer::DOC_VERSION );
$lastAppDocVersion = AppDocumentPeer::doSelectOne($oCriteria);
if (!is_null($lastAppDocVersion))
{
return $lastAppDocVersion->getDocVersion();
}
else {
return 0;
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Get last Document Version based on APPDoc UID
* @param s $sAppDocUid
* @return integer
**/
public function getLastAppDocVersion( $sAppDocUid ,$appUID=0)
{
try {
$oCriteria = new Criteria();
$oCriteria->add(AppDocumentPeer::APP_DOC_UID, $sAppDocUid );
if($appUID!=0) $oCriteria->add(AppDocumentPeer::APP_UID, $appUID);
$oCriteria->addDescendingOrderByColumn( AppDocumentPeer::DOC_VERSION );
$lastAppDocVersion = AppDocumentPeer::doSelectOne($oCriteria);
if (!is_null($lastAppDocVersion))
{
return $lastAppDocVersion->getDocVersion();
}
else {
return 0;
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Create the application document registry
* @param array $aData
* @return string
**/
public function create($aData)
{
$oConnection = Propel::getConnection(AppDocumentPeer::DATABASE_NAME);
try {
$oAppDocument = new AppDocument();
if(!isset($aData['APP_DOC_UID'])){
$sUID = G::generateUniqueID();
$docVersion = 1;
}else{
$sUID = $aData['APP_DOC_UID'];
$docVersion = $this->getLastAppDocVersion($aData['APP_DOC_UID'],$oAppDocument->getAppUid());
$oAppDocument->load($aData['APP_DOC_UID'], $docVersion);
switch( $oAppDocument->getAppDocType() ){
case "OUTPUT"://Output versioning
$o = new OutputDocument();
$oOutputDocument = $o->load($oAppDocument->getDocUid());
if( !$oOutputDocument['OUT_DOC_VERSIONING'] ){
throw(new Exception('The Output document has not versioning enabled!'));
}
break;
case "INPUT":// Input versioning
$o = new InputDocument();
$oInputDocument = $o->load($oAppDocument->getDocUid());
if( !$oInputDocument['INP_DOC_VERSIONING'] ){
throw(new Exception('This Input document does not have the versioning enabled, for this reason this operation cannot be completed'));
}
break;
default://Not a valid type
throw(new Exception('The document is not of a valid Type'));
break;
}
$docVersion++;
}
$oAppDocument->fromArray($aData, BasePeer::TYPE_FIELDNAME);
$oAppDocument->setDocVersion($docVersion);
$oAppDocument->setAppDocUid( $sUID );
$oAppDocument->setAppDocIndex($this->getLastIndex( $oAppDocument->getAppUid() )+1);
if ($oAppDocument->validate()) {
$oConnection->begin();
if (isset($aData['APP_DOC_TITLE'])) {
$oAppDocument->setAppDocTitle($aData['APP_DOC_TITLE']);
}
if (isset($aData['APP_DOC_COMMENT'])) {
$oAppDocument->setAppDocComment($aData['APP_DOC_COMMENT']);
}
if (isset($aData['APP_DOC_FILENAME'])) {
$oAppDocument->setAppDocFilename($aData['APP_DOC_FILENAME']);
}
$iResult = $oAppDocument->save();
$oConnection->commit();
$this->fromArray($oAppDocument->toArray( BasePeer::TYPE_FIELDNAME ), BasePeer::TYPE_FIELDNAME);
return $sUID;
}
else {
$sMessage = '';
$aValidationFailures = $oAppDocument->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be created!<br />'.$sMessage));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
/**
* Update the application document registry
* @param array $aData
* @return string
**/
public function update($aData)
{
$oConnection = Propel::getConnection(AppDocumentPeer::DATABASE_NAME);
try {
$oAppDocument = AppDocumentPeer::retrieveByPK($aData['APP_DOC_UID'],$aData['DOC_VERSION']);
if (!is_null($oAppDocument))
{
$oAppDocument->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($oAppDocument->validate()) {
$oConnection->begin();
if (isset($aData['APP_DOC_TITLE']))
{
$oAppDocument->setAppDocTitle($aData['APP_DOC_TITLE']);
}
if (isset($aData['APP_DOC_COMMENT']))
{
$oAppDocument->setAppDocComment($aData['APP_DOC_COMMENT']);
}
if (isset($aData['APP_DOC_FILENAME']))
{
$oAppDocument->setAppDocFilename($aData['APP_DOC_FILENAME']);
}
$iResult = $oAppDocument->save();
$oConnection->commit();
return $iResult;
}
else {
$sMessage = '';
$aValidationFailures = $oAppDocument->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be updated!<br />'.$sMessage));
}
}
else {
throw(new Exception('This row doesn\'t exists!'));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
/**
* Remove the application document registry by changing status only
* Modified by Hugo Loza hugo@colosa.com
* @param array $aData
* @return string
**/
public function remove($sAppDocUid,$iVersion=1)
{
$oConnection = Propel::getConnection(AppDocumentPeer::DATABASE_NAME);
try {
$oAppDocument = AppDocumentPeer::retrieveByPK($sAppDocUid,$iVersion);
if (!is_null($oAppDocument)){
$arrayDocumentsToDelete=array();
if($oAppDocument->getAppDocType()=="INPUT"){
$oCriteria = new Criteria('workflow');
$oCriteria->add(AppDocumentPeer::APP_DOC_UID, $sAppDocUid);
$oDataset = AppDocumentPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$arrayDocumentsToDelete[]=array('sAppDocUid'=>$aRow['APP_DOC_UID'],'iVersion'=>$aRow['DOC_VERSION']);
$oDataset->next();
}
}else{
$arrayDocumentsToDelete[]=array('sAppDocUid'=>$sAppDocUid,'iVersion'=>$iVersion);
}
foreach($arrayDocumentsToDelete as $key => $docToDelete){
$aFields = array('APP_DOC_UID' => $docToDelete['sAppDocUid'],
'DOC_VERSION' => $docToDelete['iVersion'],
'APP_DOC_STATUS' => 'DELETED');
$oAppDocument->update($aFields);
}
}
else {
throw(new Exception('This row doesn\'t exists!'));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
/**
* Get the [app_doc_title] column value.
* @return string
*/
public function getAppDocTitle()
{
if ($this->app_doc_title == '') {
try {
$this->app_doc_title = Content::load('APP_DOC_TITLE', $this->getDocVersion(), $this->getAppDocUid(), (defined('SYS_LANG') ? SYS_LANG : 'en'));
if($this->app_doc_title=="") $this->app_doc_title = Content::load('APP_DOC_TITLE', '', $this->getAppDocUid(), (defined('SYS_LANG') ? SYS_LANG : 'en')); //For backward compatibility
}
catch (Exception $oError) {
throw($oError);
}
}
return $this->app_doc_title;
}
/**
* Set the [app_doc_title] column value.
*
* @param string $sValue new value
* @return void
*/
public function setAppDocTitle($sValue)
{
if ($sValue !== null && !is_string($sValue)) {
$sValue = (string)$sValue;
}
if ($this->app_doc_title !== $sValue || $sValue === '') {
try {
$this->app_doc_title = $sValue;
$iResult = Content::addContent('APP_DOC_TITLE', $this->getDocVersion(), $this->getAppDocUid(), (defined('SYS_LANG') ? SYS_LANG : 'en'), $this->app_doc_title);
}
catch (Exception $oError) {
$this->app_doc_title = '';
throw($oError);
}
}
}
/**
* Get the [app_doc_comment] column value.
* @return string
*/
public function getAppDocComment()
{
if ($this->app_doc_comment == '') {
try {
$this->app_doc_comment = Content::load('APP_DOC_COMMENT', $this->getDocVersion(), $this->getAppDocUid(), (defined('SYS_LANG') ? SYS_LANG : 'en'));
if($this->app_doc_comment=="") $this->app_doc_comment = Content::load('APP_DOC_COMMENT', '', $this->getAppDocUid(), (defined('SYS_LANG') ? SYS_LANG : 'en')); //For backward compatibility
}
catch (Exception $oError) {
throw($oError);
}
}
return $this->app_doc_comment;
}
/**
* Set the [app_doc_comment] column value.
*
* @param string $sValue new value
* @return void
*/
public function setAppDocComment($sValue)
{
if ($sValue !== null && !is_string($sValue)) {
$sValue = (string)$sValue;
}
if ($this->app_doc_comment !== $sValue || $sValue === '') {
try {
$this->app_doc_comment = $sValue;
$iResult = Content::addContent('APP_DOC_COMMENT', $this->getDocVersion(), $this->getAppDocUid(), (defined('SYS_LANG') ? SYS_LANG : 'en'), $this->app_doc_comment);
}
catch (Exception $oError) {
$this->app_doc_comment = '';
throw($oError);
}
}
}
/**
* Get the [app_doc_filename] column value.
* @return string
*/
public function getAppDocFilename()
{
if ($this->app_doc_filename == '') {
try {
$this->app_doc_filename = Content::load('APP_DOC_FILENAME', $this->getDocVersion(), $this->getAppDocUid(), (defined('SYS_LANG') ? SYS_LANG : 'en'));
if($this->app_doc_filename=="") $this->app_doc_filename = Content::load('APP_DOC_FILENAME', '', $this->getAppDocUid(), (defined('SYS_LANG') ? SYS_LANG : 'en')); //For backward compatibility
}
catch (Exception $oError) {
throw($oError);
}
}
return $this->app_doc_filename;
}
/**
* Set the [app_doc_filename] column value.
*
* @param string $sValue new value
* @return void
*/
public function setAppDocFilename($sValue)
{
if ($sValue !== null && !is_string($sValue)) {
$sValue = (string)$sValue;
}
if ($this->app_doc_filename !== $sValue || $sValue === '') {
try {
$this->app_doc_filename = $sValue;
$iResult = Content::addContent('APP_DOC_FILENAME', $this->getDocVersion(), $this->getAppDocUid(), (defined('SYS_LANG') ? SYS_LANG : 'en'), $this->app_doc_filename);
}
catch (Exception $oError) {
$this->app_doc_filename = '';
throw($oError);
}
}
}
public function isEmptyInContent ( $content, $field, $lang ) {
if ( isset ( $content[$field][ $lang ] ) ) {
if ( trim( $content[$field][ $lang ] ) != '' )
return false;
};
return true;
}
public function updateInsertContent ( $content, $field, $value ) {
if ( isset ( $content[$field][ 'en' ] ) ) {
//update
$con = ContentPeer::retrieveByPK ( $field, $this->getDocVersion(), $this->getAppDocUid(), 'en' );
$con->setConValue ( $value );
if ($con->validate ()) {
$res = $con->save ();
}
}
else {//insert
$con = new Content ( );
$con->setConCategory ( $field );
$con->setConParent ($this->getDocVersion() );
$con->setConId ( $this->getAppDocUid() );
$con->setConLang ( 'en' );
$con->setConValue ( $value );
if ($con->validate ()) {
$res = $con->save ();
}
}
}
public function normalizeContent( $content, $field , $lang ) {
$value = '';
//if the lang row is not empty, update in 'en' row and continue
if ( !$this->isEmptyInContent ( $content, $field , $lang ) ) {
//update/insert only if this lang is != 'en', with this always we will have an en row with last value
$value = $content [ $field ][ $lang ];
if ( $lang != 'en' ) {
$this->updateInsertContent ( $content, $field , $value );
}
}
else {
//if the lang row is empty, and 'en' row is not empty return 'en' value
if ( !$this->isEmptyInContent ( $content, $field , 'en' ) ) {
$value = $content [ $field ][ 'en' ];
}
//if the lang row is empty, and 'en' row is empty get value for 'other' row and update in 'en' row and continue
if ( $this->isEmptyInContent ( $content, $field , 'en' ) ) {
if ( isset($content[$field]) && is_array ($content[$field] ) ) {
foreach ( $content [ $field ] as $lan => $val ) {
if ( trim ( $val ) != '' ) {
$value = $val;
if ( $lan != 'en' ) {
$this->updateInsertContent ( $content, $field , $value );
continue;
}
}
}
}
else {
$this->updateInsertContent ( $content, $field , '' );
}
}
}
return $value;
}
/**
* Get the [app_description] , [app_title] column values.
* @return array of string
*/
public function getContentFields()
{
if ( $this->getAppDocUid() == '' ) {
throw ( new Exception( "Error in getContentFields, the APP_DOC_UID can't be blank") );
}
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$c = new Criteria();
$c->clearSelectColumns();
$c->addSelectColumn( ContentPeer::CON_CATEGORY );
$c->addSelectColumn( ContentPeer::CON_PARENT );
$c->addSelectColumn( ContentPeer::CON_LANG );
$c->addSelectColumn( ContentPeer::CON_VALUE );
$c->add( ContentPeer::CON_ID, $this->getAppDocUid() );
$c->add( ContentPeer::CON_PARENT, $this->getDocVersion() );
$c->addAscendingOrderByColumn('CON_CATEGORY');
$c->addAscendingOrderByColumn('CON_LANG');
$rs = ContentPeer::doSelectRS( $c );
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rs->next();
$content = array();
while ($row = $rs->getRow()) {
$conCategory = $row['CON_CATEGORY'];
$conLang = $row['CON_LANG'];
if ( !isset( $content[$conCategory] ) ) $content[$conCategory] = array();
if ( !isset( $content[$conCategory][$conLang] ) ) $content[$conCategory][$conLang] = array();
$content[$conCategory][$conLang] = $row['CON_VALUE'];
$rs->next();
$row = $rs->getRow();
}
$res['APP_DOC_TITLE'] = $this->normalizeContent( $content, 'APP_DOC_TITLE', $lang );
$res['APP_DOC_COMMENT'] = $this->normalizeContent( $content, 'APP_DOC_COMMENT', $lang );
$res['APP_DOC_FILENAME'] = $this->normalizeContent( $content, 'APP_DOC_FILENAME', $lang );
return $res;
}
} // AppDocument

View File

@@ -0,0 +1,46 @@
<?php
/**
* AppDocumentPeer.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.
*
*/
// include base peer class
require_once 'classes/model/om/BaseAppDocumentPeer.php';
// include object class
include_once 'classes/model/AppDocument.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_DOCUMENT' 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 AppDocumentPeer extends BaseAppDocumentPeer {
} // AppDocumentPeer

View File

@@ -0,0 +1,307 @@
<?php
require_once 'classes/model/om/BaseAppEvent.php';
/**
* Skeleton subclass for representing a row from the 'APP_EVENT' 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 AppEvent extends BaseAppEvent {
public function load($sApplicationUID, $iDelegation) {
try {
$oAppEvent = AppEventPeer::retrieveByPK($sApplicationUID, $iDelegation);
if (!is_null($oAppEvent)) {
$aFields = $oAppEvent->toArray(BasePeer::TYPE_FIELDNAME);
$this->fromArray($aFields, BasePeer::TYPE_FIELDNAME);
return $aFields;
}
else {
throw(new Exception('This row doesn\'t exist!'));
}
}
catch (Exception $oError) {
throw($oError);
}
}
function create($aData) {
$oConnection = Propel::getConnection(AppEventPeer::DATABASE_NAME);
try {
$oAppEvent = new AppEvent();
$oAppEvent->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($oAppEvent->validate()) {
$oConnection->begin();
$iResult = $oAppEvent->save();
$oConnection->commit();
return true;
}
else {
$sMessage = '';
$aValidationFailures = $oAppEvent->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be created!<br />' . $sMessage));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
function update($aData) {
$oConnection = Propel::getConnection(AppEventPeer::DATABASE_NAME);
try {
$oAppEvent = AppEventPeer::retrieveByPK($aData['APP_UID'], $aData['DEL_INDEX']);
if (!is_null($oAppEvent)) {
$oAppEvent->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($oAppEvent->validate()) {
$oConnection->begin();
$iResult = $oAppEvent->save();
$oConnection->commit();
return $iResult;
}
else {
$sMessage = '';
$aValidationFailures = $oAppEvent->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be updated!<br />'.$sMessage));
}
}
else {
throw(new Exception('This row doesn\'t exist!'));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
function remove($sApplicationUID, $iDelegation, $sEvnUid) {
$oConnection = Propel::getConnection(AppEventPeer::DATABASE_NAME);
try {
$oAppEvent = AppEventPeer::retrieveByPK($sApplicationUID, $iDelegation, $sEvnUid);
if (!is_null($oAppEvent)) {
$oConnection->begin();
$iResult = $oAppEvent->delete();
$oConnection->commit();
return $iResult;
}
else {
throw(new Exception('This row doesn\'t exist!'));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
function getAppEventsCriteria($sProcessUid, $sStatus = '', $EVN_ACTION='') {
try {
require_once 'classes/model/Event.php';
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(AppEventPeer::APP_UID);
$oCriteria->addSelectColumn(AppEventPeer::DEL_INDEX);
$oCriteria->addSelectColumn(AppEventPeer::EVN_UID);
$oCriteria->addSelectColumn(AppEventPeer::APP_EVN_ACTION_DATE);
$oCriteria->addSelectColumn(AppEventPeer::APP_EVN_ATTEMPTS);
$oCriteria->addSelectColumn(AppEventPeer::APP_EVN_LAST_EXECUTION_DATE);
$oCriteria->addSelectColumn(AppEventPeer::APP_EVN_STATUS);
$oCriteria->addSelectColumn(EventPeer::PRO_UID);
$oCriteria->addSelectColumn(EventPeer::EVN_WHEN_OCCURS);
$oCriteria->addSelectColumn(EventPeer::EVN_ACTION);
$oCriteria->addAsColumn('EVN_DESCRIPTION', 'C1.CON_VALUE');
$oCriteria->addAsColumn('TAS_TITLE', 'C2.CON_VALUE');
$oCriteria->addAsColumn('APP_TITLE', 'C3.CON_VALUE');
$oCriteria->addAlias('C1', 'CONTENT');
$oCriteria->addAlias('C2', 'CONTENT');
$oCriteria->addAlias('C3', 'CONTENT');
$oCriteria->addJoin(AppEventPeer::EVN_UID, EventPeer::EVN_UID, Criteria::LEFT_JOIN);
$del = DBAdapter::getStringDelimiter();
$aConditions = array();
$aConditions[] = array(EventPeer::EVN_UID, 'C1.CON_ID');
$aConditions[] = array('C1.CON_CATEGORY', $del . 'EVN_DESCRIPTION' . $del);
$aConditions[] = array('C1.CON_LANG', $del . SYS_LANG . $del);
$oCriteria->addJoinMC($aConditions, Criteria::LEFT_JOIN);
$aConditions = array();
$aConditions[] = array(AppEventPeer::APP_UID, AppDelegationPeer::APP_UID);
$aConditions[] = array(AppEventPeer::DEL_INDEX, AppDelegationPeer::DEL_INDEX);
$oCriteria->addJoinMC($aConditions, Criteria::LEFT_JOIN);
$aConditions = array();
$aConditions[] = array(AppDelegationPeer::TAS_UID, 'C2.CON_ID');
$aConditions[] = array('C2.CON_CATEGORY', $del . 'TAS_TITLE' . $del);
$aConditions[] = array('C2.CON_LANG', $del . SYS_LANG . $del);
$oCriteria->addJoinMC($aConditions, Criteria::LEFT_JOIN);
$aConditions = array();
$aConditions[] = array(AppDelegationPeer::APP_UID, 'C3.CON_ID');
$aConditions[] = array('C3.CON_CATEGORY', $del . 'APP_TITLE' . $del);
$aConditions[] = array('C3.CON_LANG', $del . SYS_LANG . $del);
$oCriteria->addJoinMC($aConditions, Criteria::LEFT_JOIN);
$oCriteria->add(AppEventPeer::EVN_UID, '', Criteria::NOT_EQUAL);
$oCriteria->add(EventPeer::PRO_UID, $sProcessUid);
if($EVN_ACTION != ''){
$oCriteria->add(EventPeer::EVN_ACTION, $EVN_ACTION);
}
switch ($sStatus) {
case '':
//Nothing
break;
case 'PENDING':
$oCriteria->add(AppEventPeer::APP_EVN_STATUS, 'OPEN');
break;
case 'COMPLETED':
$oCriteria->add(AppEventPeer::APP_EVN_STATUS, 'CLOSE');
break;
}
$oCriteria->addDescendingOrderByColumn(AppEventPeer::APP_EVN_ACTION_DATE);
return $oCriteria;
}
catch (Exception $oError) {
throw($oError);
}
}
function executeEvents($sNow, $debug=false) {
require_once 'classes/model/Configuration.php';
require_once 'classes/model/Triggers.php';
G::LoadClass('case');
$debug = 1;
$oCase = new Cases();
try {
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(AppEventPeer::APP_UID);
$oCriteria->addSelectColumn(AppEventPeer::DEL_INDEX);
$oCriteria->addSelectColumn(AppEventPeer::EVN_UID);
$oCriteria->addSelectColumn(AppEventPeer::APP_EVN_ACTION_DATE);
$oCriteria->addSelectColumn(AppEventPeer::APP_EVN_ATTEMPTS);
$oCriteria->addSelectColumn(AppEventPeer::APP_EVN_LAST_EXECUTION_DATE);
$oCriteria->addSelectColumn(AppEventPeer::APP_EVN_STATUS);
$oCriteria->addSelectColumn(EventPeer::PRO_UID);
$oCriteria->addSelectColumn(EventPeer::EVN_ACTION);
$oCriteria->addSelectColumn(EventPeer::TRI_UID);
$oCriteria->addSelectColumn(EventPeer::EVN_ACTION_PARAMETERS);
$oCriteria->addSelectColumn(EventPeer::EVN_RELATED_TO);
$oCriteria->addSelectColumn(AppDelegationPeer::USR_UID);
$oCriteria->addSelectColumn(AppDelegationPeer::DEL_TASK_DUE_DATE);
$oCriteria->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE);
$oCriteria->addJoin(AppEventPeer::EVN_UID, EventPeer::EVN_UID, Criteria::JOIN);
$aConditions = array();
array_push($aConditions, Array(AppEventPeer::APP_UID, AppDelegationPeer::APP_UID));
array_push($aConditions, Array(AppEventPeer::DEL_INDEX, AppDelegationPeer::DEL_INDEX));
$oCriteria->addJoinMC($aConditions, Criteria::LEFT_JOIN);
$oCriteria->addJoin(ApplicationPeer::APP_UID, AppEventPeer::APP_UID);
$oCriteria->add(AppDelegationPeer::DEL_FINISH_DATE, null, Criteria::ISNULL); //by me
$oCriteria->add(AppEventPeer::APP_EVN_STATUS, 'OPEN');
$oCriteria->add(AppEventPeer::APP_EVN_ACTION_DATE, $sNow, Criteria::LESS_EQUAL);
$oDataset = AppEventPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$c = 0;
while ($oDataset->next()){
$c++;
$aRow = $oDataset->getRow();
$oTrigger = new Triggers();
$aFields = $oCase->loadCase($aRow['APP_UID']);
$oAppEvent = AppEventPeer::retrieveByPK($aRow['APP_UID'], $aRow['DEL_INDEX'], $aRow['EVN_UID']);
//g::pr($aRow); //die;
if($debug){
require_once 'classes/model/Application.php';
$oApp = ApplicationPeer::retrieveByPk($aRow['APP_UID']);
$oEv = EventPeer::retrieveByPk($aRow['EVN_UID']);
println("\nOK+ event \"".$oEv->getEvnDescription()."\" with ID {$aRow['EVN_UID']} was found");
println(" - PROCESS................".$aRow['PRO_UID']);
println(" - APPLICATION............".$aRow['APP_UID']." CASE #".$oApp->getAppNumber());
println(" - ACTION DATE............".$aRow['APP_EVN_ACTION_DATE']);
println(" - ATTEMPTS...............".$aRow['APP_EVN_ATTEMPTS']);
println(" - INTERVAL WITH TASKS....".$aRow['EVN_RELATED_TO']);
}
if ($aRow['TRI_UID'] == '') {
//a rare case when the tri_uid is not set.
if($debug) println(" (!) Any trigger was set................................SKIPPED and will be CLOSED");
$oAppEvent->setAppEvnStatus('CLOSE');
$oAppEvent->save();
continue;
}
$oTrigger = TriggersPeer::retrieveByPk($aRow['TRI_UID']);
if( !is_object($oTrigger) ){
//the trigger record doesn't exist..
if($debug) println(" (!) The trigger {$aRow['TRI_UID']} {$oTrigger->getTriTitle()} doesn't exist.......SKIPPED and will be CLOSED");
$oAppEvent->setAppEvnStatus('CLOSE');
$oAppEvent->save();
continue;
}
$oPMScript = new PMScript();
$oPMScript->setFields($aFields['APP_DATA']);
$oPMScript->setScript($oTrigger->getTriWebbot());
$oPMScript->execute();
$oAppEvent->setAppEvnLastExecutionDate(date('Y-m-d H:i:s'));
if( sizeof($_SESSION['TRIGGER_DEBUG']['ERRORS']) == 0 ){
if($debug) println(" - The trigger '{$oTrigger->getTriTitle()}' was executed successfully!");
//g::pr($aFields);
$aFields['APP_DATA'] = $oPMScript->aFields;
$oCase->updateCase($aRow['APP_UID'], $aFields);
$oAppEvent->setAppEvnStatus('CLOSE');
} else {
if($debug) {
println(" - The trigger {$aRow['TRI_UID']} throw some errors!");
print_r($_SESSION['TRIGGER_DEBUG']['ERRORS']);
}
if ( $oAppEvent->getAppEvnAttempts() > 0 ){
$oAppEvent->setAppEvnAttempts($oAppEvent->getAppEvnAttempts() - 1);
} else {
$oAppEvent->setAppEvnStatus('CLOSE');
}
}
$oAppEvent->save();
}
return $c;
}
catch (Exception $oError) {
die($oError->getMessage());
return $oError->getMessage();
}
}
function close($APP_UID, $DEL_INDEX){
$aRow = $this->load($APP_UID, $DEL_INDEX);
$aRow['APP_EVN_STATUS'] = 'CLOSE';
$this->update($aRow);
}
} // AppEvent

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseAppEventPeer.php';
// include object class
include_once 'classes/model/AppEvent.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_EVENT' 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 AppEventPeer extends BaseAppEventPeer {
} // AppEventPeer

View File

@@ -0,0 +1,424 @@
<?php
require_once 'classes/model/om/BaseAppFolder.php';
require_once 'classes/model/Application.php';
/**
* Skeleton subclass for representing a row from the 'APP_FOLDER' 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
*/
/**
* @author hugo loza
*
*/
class AppFolder extends BaseAppFolder {
/**
* @param string $folderName
* @param strin(32) $folderParent
* @return Ambigous <>|number
*/
function createFolder($folderName, $folderParent = "/") {
//Try to Load the folder (Foldername+FolderParent)
$oCriteria = new Criteria ( 'workflow' );
$oCriteria->add ( AppFolderPeer::FOLDER_NAME, $folderName );
$oCriteria->add ( AppFolderPeer::FOLDER_PARENT_UID, $folderParent );
$oDataset = AppFolderPeer::doSelectRS ( $oCriteria );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
if ($aRow = $oDataset->getRow ()) { //Folder exist, then return the ID
return ($aRow ['FOLDER_UID']);
} else { //Folder doesn't exist. Create and return the ID
$folderUID = G::GenerateUniqueID ();
$tr = new AppFolder ( );
$tr->setFolderUid ( $folderUID );
$tr->setFolderParentUid ( $folderParent );
$tr->setFolderName ( $folderName );
$tr->setFolderCreateDate ( 'now' );
$tr->setFolderUpdateDate ( 'now' );
if ($tr->validate ()) {
// we save it, since we get no validation errors, or do whatever else you like.
$res = $tr->save ();
return $folderUID;
} else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = '';
$validationFailuresArray = $tr->getValidationFailures ();
foreach ( $validationFailuresArray as $objValidationFailure ) {
$msg .= $objValidationFailure->getMessage () . "<br/>";
}
krumo ( $msg );
}
}
}
/**
* @param string $folderPath
* @param strin(32) $sessionID
* @return string Last Folder ID generated
*/
function createFromPath($folderPath, $sessionID = "") {
if ($sessionID == "")
$sessionID = $_SESSION ['APPLICATION'];
//Get current Application Fields
$oApplication = new Application ( );
$appFields = $oApplication->Load ( $sessionID );
$folderPathParsed = G::replaceDataField ( $folderPath, $appFields );
$folderPathParsed = G::replaceDataField ( $folderPath, unserialize ( $appFields ['APP_DATA'] ) );
$folderPathParsedArray = explode ( "/", $folderPathParsed );
$folderRoot = "/"; //Always starting from Root
foreach ( $folderPathParsedArray as $folderName ) {
if (trim ( $folderName ) != "") {
$folderRoot = $this->createFolder ( $folderName, $folderRoot );
}
}
return $folderRoot != "/" ? $folderRoot : "";
}
/**
* @param string $fileTags
* @param string(32) $sessionID Application ID
* @return string
*/
function parseTags($fileTags, $sessionID = "") {
if ($sessionID == "")
$sessionID = $_SESSION ['APPLICATION'];
//Get current Application Fields
$oApplication = new Application ( );
$appFields = $oApplication->Load ( $sessionID );
$fileTagsParsed = G::replaceDataField ( $fileTags, $appFields );
$fileTagsParsed = G::replaceDataField ( $fileTags, unserialize ( $appFields ['APP_DATA'] ) );
return $fileTagsParsed;
}
/**
* @param string(32) $folderID
* @return multitype:
*/
function getFolderList($folderID) {
$Criteria = new Criteria ( 'workflow' );
$Criteria->clearSelectColumns ()->clearOrderByColumns ();
$Criteria->addSelectColumn ( AppFolderPeer::FOLDER_UID );
$Criteria->addSelectColumn ( AppFolderPeer::FOLDER_PARENT_UID );
$Criteria->addSelectColumn ( AppFolderPeer::FOLDER_NAME );
$Criteria->addSelectColumn ( AppFolderPeer::FOLDER_CREATE_DATE );
$Criteria->addSelectColumn ( AppFolderPeer::FOLDER_UPDATE_DATE );
$Criteria->add ( appFolderPeer::FOLDER_PARENT_UID, $folderID, CRITERIA::EQUAL );
$Criteria->addAscendingOrderByColumn ( AppFolderPeer::FOLDER_NAME );
$rs = appFolderPeer::doSelectRS ( $Criteria );
$rs->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$rs->next ();
$folderResult = array ();
while ( is_array ( $row = $rs->getRow () ) ) {
$folderResult [] = $row;
$rs->next ();
}
return ($folderResult);
}
/**
* @param string(32) $folderUid
* @return array <multitype:, mixed>
*/
function load($folderUid) {
$tr = AppFolderPeer::retrieveByPK ( $folderUid );
if ((is_object ( $tr ) && get_class ( $tr ) == 'AppFolder')) {
$fields ['FOLDER_UID'] = $tr->getFolderUid ();
$fields ['FOLDER_PARENT_UID'] = $tr->getFolderParentUid ();
$fields ['FOLDER_NAME'] = $tr->getFolderName ();
$fields ['FOLDER_CREATE_DATE'] = $tr->getFolderCreateDate ();
$fields ['FOLDER_UPDATE_DATE'] = $tr->getFolderUpdateDate ();
} elseif ($folderUid == "/") {
$fields ['FOLDER_UID'] = "/";
$fields ['FOLDER_PARENT_UID'] = "";
$fields ['FOLDER_NAME'] = "/";
$fields ['FOLDER_CREATE_DATE'] = "";
$fields ['FOLDER_UPDATE_DATE'] = "";
} else {
$fields = array ();
}
return $fields;
}
function getFolderStructure($folderId) {
$folderObj = $this->load ( $folderId );
$folderArray [$folderObj ['FOLDER_UID']] = array ("NAME" => $folderObj ['FOLDER_NAME'], "PARENT" => $folderObj ['FOLDER_PARENT_UID'] );
$folderArray ['PATH_ARRAY'] [] = $folderObj ['FOLDER_NAME'];
while ( $folderObj ['FOLDER_PARENT_UID'] != "" ) {
$folderObj = $this->load ( $folderObj ['FOLDER_PARENT_UID'] );
$folderArray [$folderObj ['FOLDER_UID']] = array ("NAME" => $folderObj ['FOLDER_NAME'], "PARENT" => $folderObj ['FOLDER_PARENT_UID'] );
$folderArray ['PATH_ARRAY'] [] = $folderObj ['FOLDER_NAME'];
}
$folderArray ['PATH'] = str_replace ( "//", "/", implode ( "/", array_reverse ( $folderArray ['PATH_ARRAY'] ) ) );
return $folderArray;
}
function getFolderContent($folderID, $docIdFilter = array(), $keyword = NULL, $searchType = NULL) {
require_once ("classes/model/AppDocument.php");
require_once ("classes/model/InputDocument.php");
require_once ("classes/model/OutputDocument.php");
require_once ("classes/model/Users.php");
G::LoadClass ( 'case' );
$oCase = new Cases ( );
G::LoadClass ( 'process' );
$oProcess = new Process ( );
$oAppDocument = new AppDocument ( );
$oCriteria = new Criteria ( );
if ((is_array ( $docIdFilter )) && (count ( $docIdFilter ) > 0)) { //Search by App Doc UID no matter what Folder it is
$oCriteria->add ( AppDocumentPeer::APP_DOC_UID, $docIdFilter, CRITERIA::IN );
} elseif ($folderID != NULL) {
$oCriteria->add ( AppDocumentPeer::FOLDER_UID, $folderID );
} elseif ($searchType == "TAG") {
$oCriteria->add ( AppDocumentPeer::APP_DOC_TAGS, "%" . $keyword . "%", CRITERIA::LIKE );
}
$oCase->verifyTable ();
$oCriteria->addAscendingOrderByColumn ( AppDocumentPeer::APP_DOC_INDEX );
$rs = AppDocumentPeer::doSelectRS ( $oCriteria );
$rs->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$rs->next ();
$filesResult = array ();
while ( is_array ( $row = $rs->getRow () ) ) {
//**** start get Doc Info
$oApp = new Application ( );
if (($oApp->exists ( $row ['APP_UID'] )) || ($row ['APP_UID'] == "00000000000000000000000000000000")) {
$completeInfo = $this->getCompleteDocumentInfo ( $row ['APP_UID'], $row ['APP_DOC_UID'], $row ['DOC_VERSION'], $row ['DOC_UID'], $row ['USR_UID'] );
$oAppDocument = new AppDocument ( );
$lastVersion = $oAppDocument->getLastAppDocVersion ( $row ['APP_DOC_UID'], $row ['APP_UID'] );
if ($completeInfo ['APP_DOC_STATUS'] != "DELETED") {
if ((in_array ( $row ['APP_DOC_UID'], $completeInfo ['INPUT_DOCUMENTS'] )) || (in_array ( $row ['APP_DOC_UID'], $completeInfo ['OUTPUT_DOCUMENTS'] )) || (in_array ( $completeInfo ['USR_UID'], array ($_SESSION ['USER_LOGGED'], '-1' ) ))) {
if (count ( $docIdFilter ) > 0) {
if (in_array ( $row ['APP_DOC_UID'], $docIdFilter )) {
$filesResult [] = $completeInfo;
}
} elseif ($lastVersion == $row ['DOC_VERSION']) { //Only Last Document version
if ($searchType == "ALL") {// If search in name of docs is active then filter
if ((stripos ( $completeInfo ['APP_DOC_FILENAME'], $keyword ) !== false) || (stripos ( $completeInfo ['APP_DOC_TAGS'], $keyword ) !== false)) {
$filesResult [] = $completeInfo;
}
} else {//No search filter active
$filesResult [] = $completeInfo;
}
}
}
}
}
$rs->next ();
}
return ($filesResult);
}
function getCompleteDocumentInfo($appUid, $appDocUid, $docVersion, $docUid, $usrId) {
require_once ("classes/model/AppDocument.php");
require_once ("classes/model/InputDocument.php");
require_once ("classes/model/OutputDocument.php");
require_once ("classes/model/Users.php");
//**** start get Doc Info
$oApp = new Application ( );
$oAppDocument = new AppDocument ( );
G::LoadClass ( 'case' );
$oCase = new Cases ( );
G::LoadClass ( 'process' );
$oProcess = new Process ( );
if (($oApp->exists ( $appUid )) || ($appUid == "00000000000000000000000000000000")) {
if ($appUid == "00000000000000000000000000000000") { //External Files
$row1 = $oAppDocument->load ( $appDocUid, $docVersion );
$row2 = array ('PRO_TITLE' => G::LoadTranslation ( 'ID_NOT_PROCESS_RELATED' ) );
$row3 = array ('APP_TITLE' => G::LoadTranslation ( 'ID_NOT_PROCESS_RELATED' ) );
} else {
$row1 = $oAppDocument->load ( $appDocUid, $docVersion );
$row2 = $oCase->loadCase ( $appUid );
$row3 = $oProcess->Load ( $row2 ['PRO_UID'] );
}
$lastVersion = $oAppDocument->getLastAppDocVersion ( $appDocUid, $appUid );
switch ($row1 ['APP_DOC_TYPE']) {
case "OUTPUT" :
$oOutputDocument = new OutputDocument ( );
$row4 = $oOutputDocument->load ( $docUid );
$versioningEnabled = false; //$row4['OUT_DOC_VERSIONING']; //Only enabled for Input or Attached documents. Need to study the best way for Output docs.
switch ($row4 ['OUT_DOC_GENERATE']) {
case "PDF" :
$downloadLink = "../cases/cases_ShowOutputDocument?a=" . $appDocUid . "&v=" . $docVersion . "&ext=pdf" . "&random=" . rand ();
$downloadLink1 = "";
$downloadLabel = ".pdf";
$downloadLabel1 = "";
break;
case "DOC" :
$downloadLink = "../cases/cases_ShowOutputDocument?a=" . $appDocUid . "&v=" . $docVersion . "&ext=doc" . "&random=" . rand ();
$downloadLink1 = "";
$downloadLabel = ".doc";
$downloadLabel1 = "";
break;
case "BOTH" :
$downloadLink = "../cases/cases_ShowOutputDocument?a=" . $appDocUid . "&v=" . $docVersion . "&ext=pdf" . "&random=" . rand ();
$downloadLink1 = "../cases/cases_ShowOutputDocument?a=" . $appDocUid . "&v=" . $docVersion . "&ext=doc" . "&random=" . rand ();
$downloadLabel = ".pdf";
$downloadLabel1 = ".doc";
break;
}
break;
case "INPUT" :
$oInputDocument = new InputDocument ( );
if ($docUid != - 1) {
if ($oInputDocument->InputExists ( $docUid )) {
$row4 = $oInputDocument->load ( $docUid );
$versioningEnabled = $row4 ['INP_DOC_VERSIONING'];
} else {
$row4 = array ();
$versioningEnabled = false;
}
$downloadLink = "../cases/cases_ShowDocument?a=" . $appDocUid . "&v=" . $docVersion;
$downloadLink1 = "";
$downloadLabel = G::LoadTranslation ( 'ID_DOWNLOAD' );
$downloadLabel1 = "";
} else {
$row4 = array ();
$versioningEnabled = false;
$downloadLink = "../cases/cases_ShowDocument?a=" . $appDocUid . "&v=" . $docVersion;
$downloadLink1 = "";
$downloadLabel = G::LoadTranslation ( 'ID_DOWNLOAD' );
$downloadLabel1 = "";
}
break;
default :
$row4 = array ();
$versioningEnabled = false;
$downloadLink = "../cases/cases_ShowDocument?a=" . $appDocUid . "&v=" . $docVersion;
$downloadLink1 = "";
$downloadLabel = G::LoadTranslation ( 'ID_DOWNLOAD' );
$downloadLabel1 = "";
break;
}
$oUser = new Users ( );
if ($usrId != "-1") {
$row5 = $oUser->load ( $usrId );
} else {
$row5 ['USR_USERNAME'] = "***";
}
//Labels/Links
$row6 = array ();
$row6 ['DELETE_LABEL'] = G::LoadTranslation('ID_DELETE');
$row6 ['DOWNLOAD_LABEL'] = $downloadLabel;
$row6 ['DOWNLOAD_LINK'] = $downloadLink;
$row6 ['DOWNLOAD_LABEL1'] = $downloadLabel1;
$row6 ['DOWNLOAD_LINK1'] = $downloadLink1;
//if(($docVersion>1)&&($row1['APP_DOC_TYPE']!="OUTPUT")){
if (($docVersion > 1)) {
$row6 ['VERSIONHISTORY_LABEL'] = G::LoadTranslation ( 'ID_VERSION_HISTORY' );
}
if ($versioningEnabled) {
$row6 ['NEWVERSION_LABEL'] = G::LoadTranslation ( 'ID_NEW_VERSION' );
}
$row6 ['APP_DOC_UID_VERSION'] = $appDocUid . "_" . $docVersion;
if ($appUid == "00000000000000000000000000000000") { //External Files
$row1 ['APP_DOC_TYPE'] = G::LoadTranslation ( 'ID_EXTERNAL_FILE' );
}
//**** End get docinfo
$infoMerged = array_merge ( $row1, $row2, $row3, $row4, $row5, $row6 );
//krumo($infoMerged);
//****************************************************************************************************
$sUserUID = $_SESSION ['USER_LOGGED'];
$aObjectPermissions = array ();
if (isset ( $infoMerged ['PRO_UID'] )) {
$aObjectPermissions = $oCase->getAllObjects ( $infoMerged ['PRO_UID'], $infoMerged ['APP_UID'], '', $sUserUID );
}
if (! is_array ( $aObjectPermissions )) {
$aObjectPermissions = array ('DYNAFORMS' => array (- 1 ), 'INPUT_DOCUMENTS' => array (- 1 ), 'OUTPUT_DOCUMENTS' => array (- 1 ) );
}
if (! isset ( $aObjectPermissions ['DYNAFORMS'] )) {
$aObjectPermissions ['DYNAFORMS'] = array (- 1 );
} else {
if (! is_array ( $aObjectPermissions ['DYNAFORMS'] )) {
$aObjectPermissions ['DYNAFORMS'] = array (- 1 );
}
}
if (! isset ( $aObjectPermissions ['INPUT_DOCUMENTS'] )) {
$aObjectPermissions ['INPUT_DOCUMENTS'] = array (- 1 );
} else {
if (! is_array ( $aObjectPermissions ['INPUT_DOCUMENTS'] )) {
$aObjectPermissions ['INPUT_DOCUMENTS'] = array (- 1 );
}
}
if (! isset ( $aObjectPermissions ['OUTPUT_DOCUMENTS'] )) {
$aObjectPermissions ['OUTPUT_DOCUMENTS'] = array (- 1 );
} else {
if (! is_array ( $aObjectPermissions ['OUTPUT_DOCUMENTS'] )) {
$aObjectPermissions ['OUTPUT_DOCUMENTS'] = array (- 1 );
}
}
//****************************************************************************************************
return array_merge ( $infoMerged, $aObjectPermissions );
}
}
function getFolderChilds($folderID, $folderArray) {
$folderList = $this->getFolderList ( $folderID );
$foldersList = array ();
foreach ( $folderList as $key => $folderObj ) {
$foldersList [$folderObj ['FOLDER_UID']] = $folderObj ['FOLDER_NAME'];
$foldersList = array_merge ( $foldersList, $this->getFolderChilds ( $folderObj ['FOLDER_UID'], $folderArray ) );
}
return (array_merge ( $folderArray, $foldersList ));
}
function getFolderTags($rootFolder) {
$folderArray [$rootFolder] = $rootFolder;
$foldersToProcess = $this->getFolderChilds ( $rootFolder, $folderArray );
$tagsInfo = array ();
foreach ( $foldersToProcess as $folderkey => $foldername ) {
$filesList = $this->getFolderContent ( $folderkey );
foreach ( $filesList as $key => $fileInfo ) {
$fileTags = explode ( ",", $fileInfo ['APP_DOC_TAGS'] );
foreach ( $fileTags as $key1 => $tag ) {
if (! (isset ( $tagsInfo [$tag] )))
$tagsInfo [$tag] = 0;
$tagsInfo [$tag] ++;
}
}
}
return $tagsInfo;
}
function remove ($FolderUid, $rootfolder ) {
$oCriteria = new Criteria('workflow');
$oCriteria->add ( AppFolderPeer::FOLDER_UID, $FolderUid );
AppFolderPeer::doDelete($oCriteria);
}
} // AppFolder

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseAppFolderPeer.php';
// include object class
include_once 'classes/model/AppFolder.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_FOLDER' 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 AppFolderPeer extends BaseAppFolderPeer {
} // AppFolderPeer

View File

@@ -0,0 +1,199 @@
<?php
require_once 'classes/model/om/BaseAppHistory.php';
/**
* Skeleton subclass for representing a row from the 'APP_HISTORY' 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 AppHistory extends BaseAppHistory {
function insertHistory($aData){
$this->setAppUid($aData['APP_UID']);
$this->setDelIndex($aData['DEL_INDEX']);
$this->setProUid($aData['PRO_UID']);
$this->setTasUid($aData['TAS_UID']);
$this->setDynUid($aData['CURRENT_DYNAFORM']);
$this->setUsrUid($aData['USER_UID']);
$this->setAppStatus($aData['APP_STATUS']);
$this->setHistoryDate($aData['APP_UPDATE_DATE']);
$this->setHistoryData($aData['APP_DATA']);
if ($this->validate() ) {
$res = $this->save();
}
else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = '';
$validationFailuresArray = $this->getValidationFailures();
foreach($validationFailuresArray as $objValidationFailure) {
$msg .= $objValidationFailure->getMessage() . "<br/>";
}
krumo($msg);
//return array ( 'codError' => -100, 'rowsAffected' => 0, 'message' => $msg );
}
}
function getDynaformHistory($PRO_UID,$TAS_UID,$APP_UID,$DYN_UID=""){
G::LoadClass('case');
$oCase = new Cases();
$oCase->verifyTable();
$aObjectPermissions = $oCase->getAllObjects($PRO_UID, $APP_UID, $TAS_UID, $_SESSION['USER_LOGGED']);
if (!is_array($aObjectPermissions)) {
$aObjectPermissions = array('DYNAFORMS' => array(-1), 'INPUT_DOCUMENTS' => array(-1), 'OUTPUT_DOCUMENTS' => array(-1));
}
if (!isset($aObjectPermissions['DYNAFORMS'])) {
$aObjectPermissions['DYNAFORMS'] = array(-1);
}
else {
if (!is_array($aObjectPermissions['DYNAFORMS'])) {
$aObjectPermissions['DYNAFORMS'] = array(-1);
}
}
if (!isset($aObjectPermissions['INPUT_DOCUMENTS'])) {
$aObjectPermissions['INPUT_DOCUMENTS'] = array(-1);
}
else {
if (!is_array($aObjectPermissions['INPUT_DOCUMENTS'])) {
$aObjectPermissions['INPUT_DOCUMENTS'] = array(-1);
}
}
if (!isset($aObjectPermissions['OUTPUT_DOCUMENTS'])) {
$aObjectPermissions['OUTPUT_DOCUMENTS'] = array(-1);
}
else {
if (!is_array($aObjectPermissions['OUTPUT_DOCUMENTS'])) {
$aObjectPermissions['OUTPUT_DOCUMENTS'] = array(-1);
}
}
$c = new Criteria('workflow');
$c->addSelectColumn(AppHistoryPeer::APP_UID);
$c->addSelectColumn(AppHistoryPeer::DEL_INDEX);
$c->addSelectColumn(AppHistoryPeer::PRO_UID);
$c->addSelectColumn(AppHistoryPeer::TAS_UID);
$c->addSelectColumn(AppHistoryPeer::DYN_UID);
$c->addSelectColumn(AppHistoryPeer::USR_UID);
$c->addSelectColumn(AppHistoryPeer::APP_STATUS);
$c->addSelectColumn(AppHistoryPeer::HISTORY_DATE);
$c->addSelectColumn(AppHistoryPeer::HISTORY_DATA);
$c->addSelectColumn(UsersPeer::USR_FIRSTNAME);
$c->addSelectColumn(UsersPeer::USR_LASTNAME);
$c->addAsColumn('USR_NAME', "CONCAT(USR_LASTNAME, ' ', USR_FIRSTNAME)");
$c->addJoin(AppHistoryPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN);
//WHERE
$c->add(AppHistoryPeer::DYN_UID, $aObjectPermissions['DYNAFORMS'], Criteria::IN);
$c->add(AppHistoryPeer::PRO_UID, $PRO_UID);
$c->add(AppHistoryPeer::TAS_UID, $TAS_UID);
$c->add(AppHistoryPeer::APP_UID, $APP_UID);
if((isset($DYN_UID))&&($DYN_UID!="")){
$c->add(AppHistoryPeer::DYN_UID, $DYN_UID);
}
//ORDER BY
$c->clearOrderByColumns();
$c->addDescendingOrderByColumn(AppHistoryPeer::HISTORY_DATE);
//Execute
$oDataset = AppHistoryPeer::doSelectRS($c);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aDynHistory = array();
$aDynHistory[] = array(
'DYN_TITLE' => 'char'
);
while ($aRow = $oDataset->getRow()) {
$o = new Dynaform();
$o->setDynUid($aRow['DYN_UID']);
$aRow['DYN_TITLE'] = $o->getDynTitle();
$changedValues=unserialize($aRow['HISTORY_DATA']);
$html="<table border='0' cellpadding='0' cellspacing='0'>";
$sw_add=false;
foreach($changedValues as $key =>$value){
if(($value!=NULL)&&(!is_array($value))){
$sw_add=true;
$html.="<tr>";
$html.="<td><b>$key:</b> </td>";
$html.="<td>$value</td>";
$html.="</tr>";
}
if(is_array($value)){
$html.="<tr>";
$html.="<td><b>$key (grid):</b> </td>";
$html.="<td>";
$html.="<table>";
foreach($value as $key1 =>$value1){
$html.="<tr>";
$html.="<td><b>$key1</b></td>";
$html.="<td>";
if(is_array($value1)){
$sw_add=true;
$html.="<table>";
foreach($value1 as $key2 =>$value2){
$html.="<tr>";
$html.="<td><b>$key2</b></td>";
$html.="<td>$value2</td>";
$html.="</tr>";
}
$html.="</table>";
}
$html.="</td>";
$html.="</tr>";
}
$html.="</table>";
$html.="</td>";
$html.="</tr>";
$html.="</td>";
}
}
$html.="</table>";
$aRow['FIELDS'] = $html;
if($sw_add){
$aDynHistory[] = $aRow;
}
$oDataset->next();
}
global $_DBArray;
$_DBArray['DynaformsHistory'] = $aDynHistory;
$_SESSION['_DBArray'] = $_DBArray;
G::LoadClass('ArrayPeer');
$oCriteria = new Criteria('dbarray');
$oCriteria->setDBArrayTable('DynaformsHistory');
$oCriteria->addDescendingOrderByColumn(AppHistoryPeer::HISTORY_DATE);
return $oCriteria;
}
} // AppHistory

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseAppHistoryPeer.php';
// include object class
include_once 'classes/model/AppHistory.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_HISTORY' 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 AppHistoryPeer extends BaseAppHistoryPeer {
} // AppHistoryPeer

View File

@@ -0,0 +1,120 @@
<?php
/**
* AppMessage.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.
*
*/
require_once 'classes/model/om/BaseAppMessage.php';
/**
* Skeleton subclass for representing a row from the 'APP_MESSAGE' 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 AppMessage extends BaseAppMessage {
private $data_spool;
private $status_spool;
private $error_spool;
public function getSpoolStatus() {
return $this->status_spool;
}
public function getSpoolError() {
return $this->error_spool;
}
/**
* AppMessgae quick Save method
* @Param Array(msg_uid, app_uid, del_index, app_msg_type, app_msg_subject, app_msg_from, app_msg_to,
* app_msg_body, app_msg_cc, app_msg_bcc, app_msg_attach, app_msg_template, app_msg_status )
*
* @Author Erik Amaru Ortiz <erik@colosa.com, aortiz.erik@gmai.com>
* @Date Aug 31th, 2009
*/
public function quickSave2($data_spool) {
$this->data_spool = $data_spool;
$sUID = G::generateUniqueID();
$spool = new AppMessage();
$spool->setAppMsgUid($sUID);
$spool->setMsgUid($data_spool['msg_uid']);
$spool->setAppUid($data_spool['app_uid']);
$spool->setDelIndex($data_spool['del_index']);
$spool->setAppMsgType($data_spool['app_msg_type']);
$spool->setAppMsgSubject($data_spool['app_msg_subject']);
$spool->setAppMsgFrom($data_spool['app_msg_from']);
$spool->setAppMsgTo($data_spool['app_msg_to']);
$spool->setAppMsgBody($data_spool['app_msg_body']);
$spool->setAppMsgDate(date('Y-m-d H:i:s'));
$spool->setAppMsgCc($data_spool['app_msg_cc']);
$spool->setAppMsgBcc($data_spool['app_msg_bcc']);
$spool->setappMsgAttach($data_spool['app_msg_attach']);
$spool->setAppMsgTemplate($data_spool['app_msg_template']);
$spool->setAppMsgStatus($data_spool['app_msg_status']);
if( !$spool->validate() ) {
$this->error_spool = $spool->getValidationFailures();
$this->status_spool = 'error';
$error_msg = "AppMessage::quickSave(): Validation error: \n";
foreach($errors as $key=>$value) {
$error_msg .= $value->getMessage($key) . "\n";
}
throw new Exception($error_msg);
} else {
//echo "Saving - validation ok\n";
$this->error_spool = '';
$this->status = 'success';
$spool->save();
}
return $sUID;
}
public function quickSave($aData){
if(isset($aData['app_msg_uid'])) {
$o = EmployeePeer::retrieveByPk($aData['app_msg_uid']);
}
if (isset($o) && get_class($o) == 'AppMessage') {
$o->fromArray($aData, BasePeer::TYPE_FIELDNAME);
$o->setAppMsgDate(date('Y-m-d H:i:s'));
$o->save();
return $o->getAppMsgUid();
} else {
$this->fromArray($aData, BasePeer::TYPE_FIELDNAME);
$this->setAppMsgDate(date('Y-m-d H:i:s'));
$this->save();
return $this->getAppMsgUid();
}
}
} // AppMessage

View File

@@ -0,0 +1,46 @@
<?php
/**
* AppMessagePeer.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.
*
*/
// include base peer class
require_once 'classes/model/om/BaseAppMessagePeer.php';
// include object class
include_once 'classes/model/AppMessage.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_MESSAGE' 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 AppMessagePeer extends BaseAppMessagePeer {
} // AppMessagePeer

View File

@@ -0,0 +1,42 @@
<?php
/**
* AppOwner.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.
*
*/
require_once 'classes/model/om/BaseAppOwner.php';
/**
* Skeleton subclass for representing a row from the 'APP_OWNER' 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 AppOwner extends BaseAppOwner {
} // AppOwner

View File

@@ -0,0 +1,46 @@
<?php
/**
* AppOwnerPeer.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.
*
*/
// include base peer class
require_once 'classes/model/om/BaseAppOwnerPeer.php';
// include object class
include_once 'classes/model/AppOwner.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_OWNER' 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 AppOwnerPeer extends BaseAppOwnerPeer {
} // AppOwnerPeer

View File

@@ -0,0 +1,19 @@
<?php
require_once 'classes/model/om/BaseAppSpool.php';
/**
* Skeleton subclass for representing a row from the 'APP_SPOOL' 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 AppSpool extends BaseAppSpool {
} // AppSpool

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseAppSpoolPeer.php';
// include object class
include_once 'classes/model/AppSpool.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_SPOOL' 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 AppSpoolPeer extends BaseAppSpoolPeer {
} // AppSpoolPeer

View File

@@ -0,0 +1,121 @@
<?php
/**
* AppThread.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.
*
*/
require_once 'classes/model/om/BaseAppThread.php';
/**
* Skeleton subclass for representing a row from the 'APP_THREAD' 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 AppThread extends BaseAppThread {
function createAppThread ( $sAppUid, $iDelIndex, $iParent ) {
if (!isset($sAppUid) || strlen($sAppUid ) == 0 ) {
throw ( new Exception ( 'Column "APP_UID" cannot be null.' ) );
}
if (!isset($iDelIndex) || strlen($iDelIndex ) == 0 ) {
throw ( new Exception ( 'Column "DEL_INDEX" cannot be null.' ) );
}
if (!isset($iParent) || strlen($iDelIndex ) == 0 ) {
throw ( new Exception ( 'Column "APP_THREAD_INDEX" cannot be null.' ) );
}
$c = new Criteria ();
$c->clearSelectColumns();
$c->addSelectColumn ( 'MAX(' . AppThreadPeer::APP_THREAD_INDEX . ') ' );
$c->add ( AppThreadPeer::APP_UID, $sAppUid );
$rs = AppThreadPeer::doSelectRS ( $c );
$rs->next();
$row = $rs->getRow();
$iAppThreadIndex = $row[0] + 1;
$this->setAppUid ( $sAppUid );
$this->setAppThreadIndex ( $iAppThreadIndex );
$this->setAppThreadParent ( $iParent );
$this->setAppThreadStatus ( 'OPEN' );
$this->setDelIndex ( $iDelIndex );
if ($this->validate() ) {
try {
$res = $this->save();
}
catch ( PropelException $e ) {
throw ( $e );
}
}
else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = '';
$validationFailuresArray = $this->getValidationFailures();
foreach($validationFailuresArray as $objValidationFailure) {
$msg .= $objValidationFailure->getMessage();
}
throw ( new Exception ( 'Failed Data validation. ' . $msg ) );
}
return $iAppThreadIndex;
}
public function update($aData)
{
$con = Propel::getConnection( AppThreadPeer::DATABASE_NAME );
try {
$con->begin();
$oApp = AppThreadPeer::retrieveByPK( $aData['APP_UID'], $aData['APP_THREAD_INDEX'] );
if ( get_class ($oApp) == 'AppThread' ) {
$oApp->fromArray( $aData, BasePeer::TYPE_FIELDNAME );
if ($oApp->validate()) {
$res = $oApp->save();
$con->commit();
return $res;
}
else {
$msg = '';
foreach($this->getValidationFailures() as $objValidationFailure)
$msg .= $objValidationFailure->getMessage() . "<br/>";
throw ( new PropelException ( 'The AppThread row cannot be created!', new PropelException ( $msg ) ) );
}
}
else {
$con->rollback();
throw(new Exception( "This AppThread row doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
} // AppThread

View File

@@ -0,0 +1,46 @@
<?php
/**
* AppThreadPeer.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.
*
*/
// include base peer class
require_once 'classes/model/om/BaseAppThreadPeer.php';
// include object class
include_once 'classes/model/AppThread.php';
/**
* Skeleton subclass for performing query and update operations on the 'APP_THREAD' 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 AppThreadPeer extends BaseAppThreadPeer {
} // AppThreadPeer

View File

@@ -0,0 +1,533 @@
<?php
/**
* Application.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.
*
*/
require_once 'classes/model/om/BaseApplication.php';
require_once 'classes/model/Content.php';
/**
* Skeleton subclass for representing a row from the 'APPLICATION' 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 Application extends BaseApplication {
/**
* This value goes in the content table
* @var string
*/
protected $app_title = '';
protected $app_description = '';
//protected $app_proc_code = '';
/**
* Get the [app_title] column value.
* @return string
*/
public function getAppTitle()
{
if ( $this->getAppUid() == '' ) {
throw ( new Exception( "Error in getAppTitle, the APP_UID can't be blank") );
}
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$this->app_title = Content::load ( 'APP_TITLE', '', $this->getAppUid(), $lang );
return $this->app_title;
}
/**
* Set the [app_title] column value.
*
* @param string $v new value
* @return void
*/
public function setAppTitle($v)
{
if ( $this->getAppUid() == '' ) {
throw ( new Exception( "Error in setAppTitle, the APP_UID can't be blank") );
}
// 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->app_title !== $v || $v === '') {
$this->app_title = $v;
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$res = Content::addContent( 'APP_TITLE', '', $this->getAppUid(), $lang, $this->app_title );
}
} // set()
/**
* Get the [app_description] column value.
* @return string
*/
public function getAppDescription()
{
if ( $this->getAppUid() == '' ) {
throw ( new Exception( "Error in getAppDescription, the APP_UID can't be blank") );
}
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$this->app_description = Content::load ( 'APP_DESCRIPTION', '', $this->getAppUid(), $lang );
return $this->app_description;
}
public function isEmptyInContent ( $content, $field, $lang ) {
if ( isset ( $content[$field][ $lang ] ) ) {
if ( trim( $content[$field][ $lang ] ) != '' )
return false;
};
return true;
}
public function updateInsertContent ( $content, $field, $value ) {
if ( isset ( $content[$field][ 'en' ] ) ) {
//update
$con = ContentPeer::retrieveByPK ( $field, '', $this->getAppUid(), 'en' );
$con->setConValue ( $value );
if ($con->validate ()) {
$res = $con->save ();
}
}
else {//insert
$con = new Content ( );
$con->setConCategory ( $field );
$con->setConParent ( '' );
$con->setConId ( $this->getAppUid());
$con->setConLang ( 'en' );
$con->setConValue ( $value );
if ($con->validate ()) {
$res = $con->save ();
}
}
}
public function normalizeContent( $content, $field , $lang ) {
$value = '';
//if the lang row is not empty, update in 'en' row and continue
if ( !$this->isEmptyInContent ( $content, $field , $lang ) ) {
//update/insert only if this lang is != 'en', with this always we will have an en row with last value
$value = $content [ $field ][ $lang ];
if ( $lang != 'en' ) {
$this->updateInsertContent ( $content, $field , $value );
}
}
else {
//if the lang row is empty, and 'en' row is not empty return 'en' value
if ( !$this->isEmptyInContent ( $content, $field , 'en' ) ) {
$value = $content [ $field ][ 'en' ];
}
//if the lang row is empty, and 'en' row is empty get value for 'other' row and update in 'en' row and continue
if ( $this->isEmptyInContent ( $content, $field , 'en' ) ) {
if ( isset($content[$field]) && is_array ($content[$field] ) ) {
foreach ( $content [ $field ] as $lan => $val ) {
if ( trim ( $val ) != '' ) {
$value = $val;
if ( $lan != 'en' ) {
$this->updateInsertContent ( $content, $field , $value );
continue;
}
}
}
}
else {
$this->updateInsertContent ( $content, $field , '' );
}
}
}
return $value;
}
/**
* Get the [app_description] , [app_title] column values.
* @return array of string
*/
public function getContentFields()
{
if ( $this->getAppUid() == '' ) {
throw ( new Exception( "Error in getContentFields, the APP_UID can't be blank") );
}
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$c = new Criteria();
$c->clearSelectColumns();
$c->addSelectColumn( ContentPeer::CON_CATEGORY );
$c->addSelectColumn( ContentPeer::CON_LANG );
$c->addSelectColumn( ContentPeer::CON_VALUE );
$c->add( ContentPeer::CON_ID, $this->getAppUid() );
//$c->add( ContentPeer::CON_LANG, $lang );
$c->addAscendingOrderByColumn('CON_CATEGORY');
$c->addAscendingOrderByColumn('CON_LANG');
$rs = ContentPeer::doSelectRS( $c );
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rs->next();
$content = array();
while ($row = $rs->getRow()) {
$conCategory = $row['CON_CATEGORY'];
$conLang = $row['CON_LANG'];
if ( !isset( $content[$conCategory] ) ) $content[$conCategory] = array();
if ( !isset( $content[$conCategory][$conLang] ) ) $content[$conCategory][$conLang] = array();
$content[$conCategory][$conLang] = $row['CON_VALUE'];
$rs->next();
$row = $rs->getRow();
}
$appTitle = $this->normalizeContent( $content, 'APP_TITLE', $lang );
$appDescription = $this->normalizeContent( $content, 'APP_DESCRIPTION', $lang );
$res['APP_TITLE'] = $appTitle;
$res['APP_DESCRIPTION'] = $appDescription;
return $res;
}
/**
* Set the [app_description] column value.
*
* @param string $v new value
* @return void
*/
public function setAppDescription($v)
{
if ( $this->getAppUid() == '' ) {
throw ( new Exception( "Error in setAppTitle, the APP_UID can't be blank") );
}
// 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->app_description !== $v || $v === '') {
$this->app_description = $v;
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$res = Content::addContent( 'APP_DESCRIPTION', '', $this->getAppUid(), $lang, $this->app_description );
}
} // set()
/**
* Get the [app_proc_code] column value.
* @return string
*/
/*public function getAppProcCode ()
{
if ( $this->getAppUid() == '' ) {
throw ( new Exception( "Error in getAppProcCode, the APP_UID can't be blank") );
}
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$this->app_proc_code = Content::load ( 'APP_PROC_CODE', '', $this->getAppUid(), $lang );
return $this->app_proc_code;
}*/
/**
* Set the [app_proc_code] column value.
*
* @param string $v new value
* @return void
*/
/*public function setAppProcCode ($v)
{
if ( $this->getAppUid() == '' ) {
throw ( new Exception( "Error in setAppProcCode , the APP_UID can't be blank") );
}
// 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->app_proc_code !== $v || $v === '') {
$this->app_proc_code = $v;
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$res = Content::addContent( 'APP_PROC_CODE', '', $this->getAppUid(), $lang, $this->app_proc_code );
}
}*/ // set()
/**
* Load the Application row specified in [app_id] column value.
*
* @param string $AppUid the uid of the application
* @return array $Fields the fields
*/
function Load ( $AppUid ) {
$con = Propel::getConnection(ApplicationPeer::DATABASE_NAME);
try {
$oApplication = ApplicationPeer::retrieveByPk( $AppUid );
if ( get_class ($oApplication) == 'Application' ) {
$aFields = $oApplication->toArray(BasePeer::TYPE_FIELDNAME);
$this->fromArray ($aFields, BasePeer::TYPE_FIELDNAME );
//this is the new function to optimize content queries
$aContentFields = $oApplication->getContentFields();
$aFields['APP_TITLE'] = $aContentFields['APP_TITLE'];
$aFields['APP_DESCRIPTION'] = $aContentFields['APP_DESCRIPTION'];
$this->app_title = $aFields['APP_TITLE'];
$this->app_description = $aFields['APP_DESCRIPTION'];
//$aFields['APP_PROC_CODE'] = $oApplication->getAppProcCode();
//$this->setAppProcCode ( $oApplication->getAppProcCode() );
return $aFields;
}
else {
throw( new Exception( "The Application row '$AppUid' doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Creates the Application
*
* @param
* $sProUid the process id
* $sUsrUid the userid
* @return void
*/
function create ($sProUid, $sUsrUid ) {
$con = Propel::getConnection( 'workflow' );
try {
//fill the default values for new application row
$this->setAppUid ( G::generateUniqueID() );
$this->setAppParent ( '' );
$this->setAppStatus ( 'DRAFT' );
$this->setProUid ( $sProUid );
$this->setAppProcStatus('' );
$this->setAppProcCode ( '' );
$this->setAppParallel ( 'N' );
$this->setAppInitUser ( $sUsrUid );
$this->setAppCurUser ( $sUsrUid );
$this->setAppCreateDate( 'now' );
$this->setAppInitDate ( 'now' );
$this->setAppFinishDate( '19020101' ); //to do: what is the empty date for propel???/
$this->setAppUpdateDate( 'now' );
$pin = G::generateCode( 4, 'ALPHANUMERIC');
$this->setAppData ( serialize ( array('PIN'=>$pin) ) );
$this->setAppPin ( md5($pin) );
$c = new Criteria();
$c->clearSelectColumns();
$c->addSelectColumn( 'MAX(' . ApplicationPeer::APP_NUMBER . ')' ); //the appnumber is based in all processes active, not only in the specified process guid
$result = ApplicationPeer::doSelectRS( $c );
$result->next();
$row = $result->getRow();
$maxNumber = $row[0] + 1;
$this->setAppNumber ( $maxNumber );
if ( $this->validate() ) {
$con->begin();
$res = $this->save();
$con->commit();
//to do: ID_CASE in translation $this->setAppTitle ( G::LoadTranslation ( 'ID_CASE') . $maxNumber );
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
Content::insertContent( 'APP_TITLE', '', $this->getAppUid(), $lang, '#' . $maxNumber );
Content::insertContent( 'APP_DESCRIPTION', '', $this->getAppUid(), $lang, '' );
//Content::insertContent( 'APP_PROC_CODE', '', $this->getAppUid(), $lang, '' );
$con->commit();
return $this->getAppUid();
}
else {
$msg = '';
foreach($this->getValidationFailures() as $objValidationFailure)
$msg .= $objValidationFailure->getMessage() . "<br/>";
throw ( new PropelException ( 'The APPLICATION row cannot be created!', new PropelException ( $msg ) ) );
}
}
catch (Exception $e) {
$con->rollback();
throw ($e);
}
}
/**
* Update the application row
* @param array $aData
* @return variant
**/
public function update($aData)
{
$con = Propel::getConnection( ApplicationPeer::DATABASE_NAME );
try {
$con->begin();
$oApp = ApplicationPeer::retrieveByPK( $aData['APP_UID'] );
if ( get_class ($oApp) == 'Application' ) {
$oApp->fromArray( $aData, BasePeer::TYPE_FIELDNAME );
if ($oApp->validate()) {
if ( isset ( $aData['APP_TITLE'] ) )
$oApp->setAppTitle( $aData['APP_TITLE'] );
if ( isset ( $aData['APP_DESCRIPTION'] ) )
$oApp->setAppDescription( $aData['APP_DESCRIPTION'] );
//if ( isset ( $aData['APP_PROC_CODE'] ) )
//$oApp->setAppProcCode( $aData['APP_PROC_CODE'] );
$res = $oApp->save();
$con->commit();
return $res;
}
else {
$msg = '';
foreach($this->getValidationFailures() as $objValidationFailure)
$msg .= $objValidationFailure->getMessage() . "<br/>";
throw ( new PropelException ( 'The row cannot be updated!', new PropelException ( $msg ) ) );
}
}
else {
$con->rollback();
throw(new Exception( "The row '" . $aData['APP_UID'] . "' in table APPLICATION doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Remove the application document registry
* @param array $aData or string $appUid
* @return string
**/
public function remove($appUid)
{
if ( is_array ( $appUid ) ) {
$appUid = ( isset ( $appUid['APP_UID'] ) ? $appUid['APP_UID'] : '' );
}
try {
$oApp = ApplicationPeer::retrieveByPK( $appUid );
if (!is_null($oApp))
{
Content::removeContent('APP_TITLE', '', $oApp->getAppUid());
Content::removeContent('APP_DESCRIPTION', '', $oApp->getAppUid());
//Content::removeContent('APP_PROC_CODE', '', $oApp->getAppUid());
return $oApp->delete();
}
else {
throw(new Exception( "The row '$appUid' in table Application doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
function exists( $sAppUid )
{
$oApplicaton = ApplicationPeer::retrieveByPK( $sAppUid );
return (!is_null($oApplicaton));
}
function createApplication ($aData ) {
$c = new Criteria();
$c->clearSelectColumns();
$c->addSelectColumn( 'MAX(' . ApplicationPeer::APP_NUMBER . ')' );
$c->add( ApplicationPeer::PRO_UID, $aData['PRO_UID'] );
$result = ApplicationPeer::doSelectRS( $c );
$result->next();
$row = $result->getRow();
$maxNumber = $row[0] + 1;
$this->setAppUid ( G::generateUniqueID() );
$this->setAppNumber ( $maxNumber );
$this->setAppParent (isset($aData['APP_PARENT']) ? $aData['APP_PARENT'] : 0 );
$this->setAppStatus (isset($aData['APP_STATUS']) ? $aData['APP_STATUS'] : 'DRAFT' );
$this->setProUid ( $aData['PRO_UID'] );
$this->setAppProcStatus(isset($aData['APP_PROC_STATUS'])? $aData['APP_PROC_STATUS'] : '' );
$this->setAppProcCode (isset($aData['APP_PROC_CODE']) ? $aData['APP_PROC_CODE'] : '' );
$this->setAppParallel (isset($aData['APP_PARALLEL']) ? $aData['APP_PARALLEL'] : 'N' );
$this->setAppInitUser ( $aData['USR_UID'] );
$this->setAppCurUser ( $aData['USR_UID'] );
$this->setAppCreateDate(isset($aData['APP_CREATE_DATE'])? $aData['APP_CREATE_DATE'] : 'now' );
$this->setAppInitDate (isset($aData['APP_INIT_DATE']) ? $aData['APP_INIT_DATE'] : 'now' );
//$this->setAppFinishDate(isset($aData['APP_FINISH_DATE'])? $aData['APP_FINISH_DATE'] : '' );
$this->setAppUpdateDate(isset($aData['APP_UPDATE_DATE'])? $aData['APP_UPDATE_DATE'] : 'now' );
//$this->setAppData ( serialize ( array() ) );
/** Start Comment : Sets the $this->Fields['APP_DATA']
Merge between stored APP_DATA with new APP_DATA. **/
if (!$this->getAppData())
{
// if (!$this->is_new)
// {
// $this->load($fields['APP_UID']);
// }
}
$this->Fields['APP_DATA']=isset($this->Fields['APP_DATA'])?$this->Fields['APP_DATA']:array();
if (isset($fields['APP_DATA']) && is_array($fields['APP_DATA']))
{
foreach($fields['APP_DATA'] as $k=>$v)
{
$this->Fields['APP_DATA'][$k]=$v;
}
}
/** End Comment **/
/** Begin Comment : Replace APP_DATA in APP_TITLE (before to serialize)
$pro = new process( $this->_dbc );
$pro->load((isset($fields['PRO_UID']) ? $fields['PRO_UID'] : $this->Fields['PRO_UID']));
$fields['APP_TITLE'] = G::replaceDataField( $pro->Fields['PRO_TITLE'], $this->Fields['APP_DATA']);
/** End Comment **/
// parent::save();
// $this->Fields['APP_DATA'] = unserialize($this->Fields['APP_DATA']);
// /** Start Comment: Save in the table CONTENT */
// $this->content->saveContent('APP_TITLE',$fields);
// /** End Comment */
if ($this->validate() ) {
$res = $this->save();
$this->setAppTitle ('');
$this->setAppDescription ('');
$this->setAppProcCode ('');
}
else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = '';
$validationFailuresArray = $this->getValidationFailures();
foreach($validationFailuresArray as $objValidationFailure) {
$msg .= $objValidationFailure->getMessage() . "<br/>";
}
//return array ( 'codError' => -100, 'rowsAffected' => 0, 'message' => $msg );
}
return $this->getAppUid();
}
} // Application

View File

@@ -0,0 +1,46 @@
<?php
/**
* ApplicationPeer.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.
*
*/
// include base peer class
require_once 'classes/model/om/BaseApplicationPeer.php';
// include object class
include_once 'classes/model/Application.php';
/**
* Skeleton subclass for performing query and update operations on the 'APPLICATION' 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 ApplicationPeer extends BaseApplicationPeer {
} // ApplicationPeer

View File

@@ -0,0 +1,19 @@
<?php
require_once 'classes/model/om/BaseCalendarAssignments.php';
/**
* Skeleton subclass for representing a row from the 'CALENDAR_ASSIGNMENTS' 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 CalendarAssignments extends BaseCalendarAssignments {
} // CalendarAssignments

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseCalendarAssignmentsPeer.php';
// include object class
include_once 'classes/model/CalendarAssignments.php';
/**
* Skeleton subclass for performing query and update operations on the 'CALENDAR_ASSIGNMENTS' 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 CalendarAssignmentsPeer extends BaseCalendarAssignmentsPeer {
} // CalendarAssignmentsPeer

View File

@@ -0,0 +1,107 @@
<?php
require_once 'classes/model/om/BaseCalendarBusinessHours.php';
/**
* Skeleton subclass for representing a row from the 'CALENDAR_BUSINESS_HOURS' 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 CalendarBusinessHours extends BaseCalendarBusinessHours {
function getCalendarBusinessHours($CalendarUid){
$Criteria = new Criteria('workflow');
$Criteria->clearSelectColumns ( );
$Criteria->addSelectColumn ( CalendarBusinessHoursPeer::CALENDAR_UID );
$Criteria->addSelectColumn ( CalendarBusinessHoursPeer::CALENDAR_BUSINESS_DAY );
$Criteria->addSelectColumn ( CalendarBusinessHoursPeer::CALENDAR_BUSINESS_START );
$Criteria->addSelectColumn ( CalendarBusinessHoursPeer::CALENDAR_BUSINESS_END );
$Criteria->add ( CalendarBusinessHoursPeer::CALENDAR_UID, $CalendarUid , CRITERIA::EQUAL );
$Criteria->addDescendingOrderByColumn ( CalendarBusinessHoursPeer::CALENDAR_BUSINESS_DAY );
$Criteria->addAscendingOrderByColumn ( CalendarBusinessHoursPeer::CALENDAR_BUSINESS_START );
//$Criteria->addDescendingOrderByColumn ( CalendarBusinessHoursPeer::CALENDAR_BUSINESS_START );
$rs = CalendarBusinessHoursPeer::doSelectRS($Criteria);
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rs->next();
$row = $rs->getRow();
$fields=array();
$count=0;
while (is_array($row)) {
$count++;
$fields[$count] = $row;
$rs->next();
$row = $rs->getRow();
}
return $fields;
}
function deleteAllCalendarBusinessHours($CalendarUid){
$toDelete=$this->getCalendarBusinessHours($CalendarUid);
foreach($toDelete as $key => $businessHoursInfo){
$CalendarUid = $businessHoursInfo['CALENDAR_UID'];
$CalendarBusinessDay = $businessHoursInfo['CALENDAR_BUSINESS_DAY'];
$CalendarBusinessStart = $businessHoursInfo['CALENDAR_BUSINESS_START'];
$CalendarBusinessEnd = $businessHoursInfo['CALENDAR_BUSINESS_END'];
//if exists the row in the database propel will update it, otherwise will insert.
$tr = CalendarBusinessHoursPeer::retrieveByPK ( $CalendarUid,$CalendarBusinessDay, $CalendarBusinessStart,$CalendarBusinessEnd );
if ( ( is_object ( $tr ) && get_class ($tr) == 'CalendarBusinessHours' ) ) {
$tr->delete();
}
}
}
function saveCalendarBusinessHours($aData){
$CalendarUid = $aData['CALENDAR_UID'];
$CalendarBusinessDay = $aData['CALENDAR_BUSINESS_DAY'];
$CalendarBusinessStart = $aData['CALENDAR_BUSINESS_START'];
$CalendarBusinessEnd = $aData['CALENDAR_BUSINESS_END'];
//if exists the row in the database propel will update it, otherwise will insert.
$tr = CalendarBusinessHoursPeer::retrieveByPK ( $CalendarUid,$CalendarBusinessDay, $CalendarBusinessStart,$CalendarBusinessEnd );
if ( ! ( is_object ( $tr ) && get_class ($tr) == 'CalendarBusinessHours' ) ) {
$tr = new CalendarBusinessHours();
}
$tr->setCalendarUid( $CalendarUid );
$tr->setCalendarBusinessDay( $CalendarBusinessDay );
$tr->setCalendarBusinessStart( $CalendarBusinessStart );
$tr->setCalendarBusinessEnd( $CalendarBusinessEnd );
if ($tr->validate() ) {
// we save it, since we get no validation errors, or do whatever else you like.
$res = $tr->save();
}
else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = $CalendarBusinessDay.'<hr/>';
$validationFailuresArray = $tr->getValidationFailures();
foreach($validationFailuresArray as $objValidationFailure) {
$msg .= $objValidationFailure->getMessage() . "<br/>";
}
//return array ( 'codError' => -100, 'rowsAffected' => 0, 'message' => $msg );
G::SendTemporalMessage($msg);
}
//return array ( 'codError' => 0, 'rowsAffected' => $res, 'message' => '');
//to do: uniform coderror structures for all classes
//if ( $res['codError'] < 0 ) {
// G::SendMessageText ( $res['message'] , 'error' );
//}
}
} // CalendarBusinessHours

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseCalendarBusinessHoursPeer.php';
// include object class
include_once 'classes/model/CalendarBusinessHours.php';
/**
* Skeleton subclass for performing query and update operations on the 'CALENDAR_BUSINESS_HOURS' 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 CalendarBusinessHoursPeer extends BaseCalendarBusinessHoursPeer {
} // CalendarBusinessHoursPeer

View File

@@ -0,0 +1,328 @@
<?php
require_once 'classes/model/om/BaseCalendarDefinition.php';
require_once 'classes/model/CalendarBusinessHours.php';
require_once 'classes/model/CalendarHolidays.php';
require_once 'classes/model/CalendarAssignments.php';
/**
* Skeleton subclass for representing a row from the 'CALENDAR_DEFINITION' 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 CalendarDefinition extends BaseCalendarDefinition {
public $calendarLog = '';
function getCalendarList($onlyActive = false, $arrayMode = false) {
$Criteria = new Criteria ( 'workflow' );
$Criteria->clearSelectColumns ();
$Criteria->addSelectColumn ( CalendarDefinitionPeer::CALENDAR_UID );
$Criteria->addSelectColumn ( CalendarDefinitionPeer::CALENDAR_NAME );
$Criteria->addSelectColumn ( CalendarDefinitionPeer::CALENDAR_CREATE_DATE );
$Criteria->addSelectColumn ( CalendarDefinitionPeer::CALENDAR_UPDATE_DATE );
$Criteria->addSelectColumn ( CalendarDefinitionPeer::CALENDAR_DESCRIPTION );
$Criteria->addSelectColumn ( CalendarDefinitionPeer::CALENDAR_STATUS );
// Note: This list doesn't show deleted items (STATUS = DELETED)
if ($onlyActive) { // Show only active. Used on assignment lists
$Criteria->add ( calendarDefinitionPeer::CALENDAR_STATUS, "ACTIVE", CRITERIA::EQUAL );
} else { // Show Active and Inactive calendars. USed in main list
$Criteria->add ( calendarDefinitionPeer::CALENDAR_STATUS, array ("ACTIVE", "INACTIVE" ), CRITERIA::IN );
}
if(class_exists('pmLicenseManager')){
$pmLicenseManagerO =& pmLicenseManager::getSingleton();
$expireIn=$pmLicenseManagerO->getExpireIn();
if($expireIn>0){
$Criteria->add ( calendarDefinitionPeer::CALENDAR_UID, "xx", CRITERIA::NOT_EQUAL );
}else{
$Criteria->add ( calendarDefinitionPeer::CALENDAR_UID, "00000000000000000000000000000001", CRITERIA::EQUAL );
}
}else{
$Criteria->add ( calendarDefinitionPeer::CALENDAR_UID, "00000000000000000000000000000001", CRITERIA::EQUAL );
}
if (! $arrayMode) {
return $Criteria;
} else {
$oDataset = calendarDefinitionPeer::doSelectRS ( $Criteria );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$calendarA = array (0 => 'dummy' );
$calendarCount = 0;
while ( is_array ( $aRow = $oDataset->getRow () ) ) {
$calendarCount ++;
$calendarA [$calendarCount] = $aRow;
$oDataset->next ();
}
$return ['criteria'] = $Criteria;
$return ['array'] = $calendarA;
return $return;
}
}
function getCalendarInfo($CalendarUid) {
//if exists the row in the database propel will update it, otherwise will insert.
$tr = CalendarDefinitionPeer::retrieveByPK ( $CalendarUid );
if ((is_object ( $tr ) && get_class ( $tr ) == 'CalendarDefinition')) {
$fields ['CALENDAR_UID'] = $tr->getCalendarUid ();
$fields ['CALENDAR_NAME'] = $tr->getCalendarName ();
$fields ['CALENDAR_CREATE_DATE'] = $tr->getCalendarCreateDate ();
$fields ['CALENDAR_UPDATE_DATE'] = $tr->getCalendarUpdateDate ();
$fields ['CALENDAR_DESCRIPTION'] = $tr->getCalendarDescription ();
$fields ['CALENDAR_STATUS'] = $tr->getCalendarStatus ();
$fields ['CALENDAR_WORK_DAYS'] = $tr->getCalendarWorkDays ();
$fields ['CALENDAR_WORK_DAYS_A'] = explode ( "|", $tr->getCalendarWorkDays () );
} else {
$fields ['CALENDAR_UID'] = "00000000000000000000000000000001";
$fields ['CALENDAR_NAME'] = "Default";
$fields ['CALENDAR_CREATE_DATE'] = date ( "Y-m-d" );
$fields ['CALENDAR_UPDATE_DATE'] = date ( "Y-m-d" );
$fields ['CALENDAR_DESCRIPTION'] = "Default";
$fields ['CALENDAR_STATUS'] = "ACTIVE";
$fields ['CALENDAR_WORK_DAYS'] = "1|2|3|4|5";
$fields ['CALENDAR_WORK_DAYS'] = explode ( "|", "1|2|3|4|5" );
$fields ['BUSINESS_DAY'] [1] ['CALENDAR_BUSINESS_DAY'] = 7;
$fields ['BUSINESS_DAY'] [1] ['CALENDAR_BUSINESS_START'] = "09:00";
$fields ['BUSINESS_DAY'] [1] ['CALENDAR_BUSINESS_END'] = "17:00";
$fields ['HOLIDAY'] = array ();
$this->saveCalendarInfo ( $fields );
$fields ['CALENDAR_WORK_DAYS'] = "1|2|3|4|5";
$fields ['CALENDAR_WORK_DAYS_A'] = explode ( "|", "1|2|3|4|5" );
$tr = CalendarDefinitionPeer::retrieveByPK ( $CalendarUid );
}
$CalendarBusinessHoursObj = new CalendarBusinessHours ( );
$CalendarBusinessHours = $CalendarBusinessHoursObj->getCalendarBusinessHours ( $CalendarUid );
$fields ['BUSINESS_DAY'] = $CalendarBusinessHours;
$CalendarHolidaysObj = new CalendarHolidays ( );
$CalendarHolidays = $CalendarHolidaysObj->getCalendarHolidays ( $CalendarUid );
$fields ['HOLIDAY'] = $CalendarHolidays;
return $fields;
}
function saveCalendarInfo($aData) {
$CalendarUid = $aData ['CALENDAR_UID'];
$CalendarName = $aData ['CALENDAR_NAME'];
$CalendarDescription = $aData ['CALENDAR_DESCRIPTION'];
$CalendarStatus = isset ( $aData ['CALENDAR_STATUS'] ) ? $aData ['CALENDAR_STATUS'] : "INACTIVE";
$defaultCalendars [] = '00000000000000000000000000000001';
if (in_array ( $aData ['CALENDAR_UID'], $defaultCalendars )) {
$CalendarStatus = 'ACTIVE';
$CalendarName = 'Default';
}
$CalendarWorkDays = isset ( $aData ['CALENDAR_WORK_DAYS'] ) ? implode ( "|", $aData ['CALENDAR_WORK_DAYS'] ) : "";
//if exists the row in the database propel will update it, otherwise will insert.
$tr = CalendarDefinitionPeer::retrieveByPK ( $CalendarUid );
if (! (is_object ( $tr ) && get_class ( $tr ) == 'CalendarDefinition')) {
$tr = new CalendarDefinition ( );
$tr->setCalendarCreateDate ( 'now' );
}
$tr->setCalendarUid ( $CalendarUid );
$tr->setCalendarName ( $CalendarName );
$tr->setCalendarUpdateDate ( 'now' );
$tr->setCalendarDescription ( $CalendarDescription );
$tr->setCalendarStatus ( $CalendarStatus );
$tr->setCalendarWorkDays ( $CalendarWorkDays );
if ($tr->validate ()) {
// we save it, since we get no validation errors, or do whatever else you like.
$res = $tr->save ();
//Calendar Business Hours Save code.
//First Delete all current records
$CalendarBusinessHoursObj = new CalendarBusinessHours ( );
$CalendarBusinessHoursObj->deleteAllCalendarBusinessHours ( $CalendarUid );
//Save all the sent records
foreach ( $aData ['BUSINESS_DAY'] as $key => $objData ) {
$objData ['CALENDAR_UID'] = $CalendarUid;
$CalendarBusinessHoursObj->saveCalendarBusinessHours ( $objData );
}
//Holiday Save code.
//First Delete all current records
$CalendarHolidayObj = new CalendarHolidays ( );
$CalendarHolidayObj->deleteAllCalendarHolidays ( $CalendarUid );
//Save all the sent records
foreach ( $aData ['HOLIDAY'] as $key => $objData ) {
if (($objData ['CALENDAR_HOLIDAY_NAME'] != "") && ($objData ['CALENDAR_HOLIDAY_START'] != "") && ($objData ['CALENDAR_HOLIDAY_END'] != "")) {
$objData ['CALENDAR_UID'] = $CalendarUid;
$CalendarHolidayObj->saveCalendarHolidays ( $objData );
}
}
} else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = '';
$validationFailuresArray = $tr->getValidationFailures ();
foreach ( $validationFailuresArray as $objValidationFailure ) {
$msg .= $objValidationFailure->getMessage () . "<br/>";
}
//return array ( 'codError' => -100, 'rowsAffected' => 0, 'message' => $msg );
}
//return array ( 'codError' => 0, 'rowsAffected' => $res, 'message' => '');
//to do: uniform coderror structures for all classes
//if ( $res['codError'] < 0 ) {
// G::SendMessageText ( $res['message'] , 'error' );
//}
}
function deleteCalendar($CalendarUid) {
//if exists the row in the database propel will update it, otherwise will insert.
$tr = CalendarDefinitionPeer::retrieveByPK ( $CalendarUid );
if (! (is_object ( $tr ) && get_class ( $tr ) == 'CalendarDefinition')) {
//
return false;
}
$defaultCalendars [] = '00000000000000000000000000000001';
if (in_array ( $tr->getCalendarUid(), $defaultCalendars )) {
return false;
}
$tr->setCalendarStatus ( 'DELETED' );
$tr->setCalendarUpdateDate ( 'now' );
if ($tr->validate ()) {
// we save it, since we get no validation errors, or do whatever else you like.
$res = $tr->save ();
} else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = '';
$validationFailuresArray = $tr->getValidationFailures ();
foreach ( $validationFailuresArray as $objValidationFailure ) {
$msg .= $objValidationFailure->getMessage () . "<br/>";
}
G::SendMessage ( "ERROR", $msg );
//return array ( 'codError' => -100, 'rowsAffected' => 0, 'message' => $msg );
}
//return array ( 'codError' => 0, 'rowsAffected' => $res, 'message' => '');
//to do: uniform coderror structures for all classes
//if ( $res['codError'] < 0 ) {
// G::SendMessageText ( $res['message'] , 'error' );
//}
}
function getCalendarFor($userUid, $proUid, $tasUid) {
$Criteria = new Criteria ( 'workflow' );
//Default Calendar
$calendarUid = "00000000000000000000000000000001";
$calendarOwner = "DEFAULT";
//Try to load a User Calendar if exist
$objectID = $userUid;
$Criteria->clearSelectColumns ();
$Criteria->addSelectColumn ( CalendarAssignmentsPeer::CALENDAR_UID );
$Criteria->addSelectColumn ( CalendarAssignmentsPeer::OBJECT_UID );
$Criteria->addSelectColumn ( CalendarAssignmentsPeer::OBJECT_TYPE );
$Criteria->add ( CalendarAssignmentsPeer::OBJECT_UID, $objectID, CRITERIA::EQUAL );
if (CalendarAssignmentsPeer::doCount ( $Criteria ) > 0) {
$oDataset = CalendarAssignmentsPeer::doSelectRS ( $Criteria );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$aRow = $oDataset->getRow ();
$calendarUid = $aRow ['CALENDAR_UID'];
$calendarOwner = "USER";
}
//Try to load a Process Calendar if exist
$objectID = $proUid;
$Criteria->clearSelectColumns ();
$Criteria->addSelectColumn ( CalendarAssignmentsPeer::CALENDAR_UID );
$Criteria->addSelectColumn ( CalendarAssignmentsPeer::OBJECT_UID );
$Criteria->addSelectColumn ( CalendarAssignmentsPeer::OBJECT_TYPE );
$Criteria->add ( CalendarAssignmentsPeer::OBJECT_UID, $objectID, CRITERIA::EQUAL );
if (CalendarAssignmentsPeer::doCount ( $Criteria ) > 0) {
$oDataset = CalendarAssignmentsPeer::doSelectRS ( $Criteria );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$aRow = $oDataset->getRow ();
$calendarUid = $aRow ['CALENDAR_UID'];
$calendarOwner = "PROCESS";
}
//Try to load a Task Calendar if exist
$objectID = $tasUid;
$Criteria->addSelectColumn ( CalendarAssignmentsPeer::CALENDAR_UID );
$Criteria->addSelectColumn ( CalendarAssignmentsPeer::OBJECT_UID );
$Criteria->addSelectColumn ( CalendarAssignmentsPeer::OBJECT_TYPE );
$Criteria->add ( CalendarAssignmentsPeer::OBJECT_UID, $objectID, CRITERIA::EQUAL );
$Criteria->clearSelectColumns ();
if (CalendarAssignmentsPeer::doCount ( $Criteria ) > 0) {
$oDataset = CalendarAssignmentsPeer::doSelectRS ( $Criteria );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$aRow = $oDataset->getRow ();
$calendarUid = $aRow ['CALENDAR_UID'];
$calendarOwner = "TASK";
}
if(class_exists('pmLicenseManager')){
$pmLicenseManagerO =& pmLicenseManager::getSingleton();
$expireIn=$pmLicenseManagerO->getExpireIn();
if($expireIn>0){
$calendarUid=$calendarUid;
}else{
$calendarUid = "00000000000000000000000000000001";
}
}else{
$calendarUid = "00000000000000000000000000000001";
}
//print "<h1>$calendarUid</h1>";
$calendarDefinition = $this->getCalendarInfo ( $calendarUid );
$calendarDefinition ['CALENDAR_APPLIED'] = $calendarOwner;
$this->addCalendarLog ( "--=== Calendar Applied: " . $calendarDefinition ['CALENDAR_NAME'] . " -> $calendarOwner" );
return $calendarDefinition;
}
function assignCalendarTo($objectUid, $calendarUid, $objectType) {
//if exists the row in the database propel will update it, otherwise will insert.
$tr = CalendarAssignmentsPeer::retrieveByPK ( $objectUid );
if ($calendarUid != "") {
if (! (is_object ( $tr ) && get_class ( $tr ) == 'CalendarAssignments')) {
$tr = new CalendarAssignments ( );
}
$tr->setObjectUid ( $objectUid );
$tr->setCalendarUid ( $calendarUid );
$tr->setObjectType ( $objectType );
if ($tr->validate ()) {
// we save it, since we get no validation errors, or do whatever else you like.
$res = $tr->save ();
} else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = '';
$validationFailuresArray = $tr->getValidationFailures ();
foreach ( $validationFailuresArray as $objValidationFailure ) {
$msg .= $objValidationFailure->getMessage () . "<br/>";
}
//return array ( 'codError' => -100, 'rowsAffected' => 0, 'message' => $msg );
}
} else { //Delete record
if ((is_object ( $tr ) && get_class ( $tr ) == 'CalendarAssignments')) {
$tr->delete ();
}
}
}
} // CalendarDefinition

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseCalendarDefinitionPeer.php';
// include object class
include_once 'classes/model/CalendarDefinition.php';
/**
* Skeleton subclass for performing query and update operations on the 'CALENDAR_DEFINITION' 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 CalendarDefinitionPeer extends BaseCalendarDefinitionPeer {
} // CalendarDefinitionPeer

View File

@@ -0,0 +1,111 @@
<?php
require_once 'classes/model/om/BaseCalendarHolidays.php';
/**
* Skeleton subclass for representing a row from the 'CALENDAR_HOLIDAYS' 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 CalendarHolidays extends BaseCalendarHolidays {
function getCalendarHolidays($CalendarUid){
$Criteria = new Criteria('workflow');
$Criteria->clearSelectColumns ( );
$Criteria->addSelectColumn ( CalendarHolidaysPeer::CALENDAR_UID );
$Criteria->addSelectColumn ( CalendarHolidaysPeer::CALENDAR_HOLIDAY_NAME );
$Criteria->addSelectColumn ( CalendarHolidaysPeer::CALENDAR_HOLIDAY_START );
$Criteria->addSelectColumn ( CalendarHolidaysPeer::CALENDAR_HOLIDAY_END );
$Criteria->add ( CalendarHolidaysPeer::CALENDAR_UID, $CalendarUid , CRITERIA::EQUAL );
$rs = CalendarHolidaysPeer::doSelectRS($Criteria);
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rs->next();
$row = $rs->getRow();
$fields=array();
$count=0;
while (is_array($row)) {
$count++;
$a=explode(" ",$row['CALENDAR_HOLIDAY_START']);
$row['CALENDAR_HOLIDAY_START']=$a[0];
$a=explode(" ",$row['CALENDAR_HOLIDAY_END']);
$row['CALENDAR_HOLIDAY_END']=$a[0];
$fields[$count] = $row;
$rs->next();
$row = $rs->getRow();
}
return $fields;
}
function deleteAllCalendarHolidays($CalendarUid){
$toDelete=$this->getCalendarHolidays($CalendarUid);
foreach($toDelete as $key => $holidayInfo){
print_r($holidayInfo);
$CalendarUid = $holidayInfo['CALENDAR_UID'];
$CalendarHolidayName = $holidayInfo['CALENDAR_HOLIDAY_NAME'];
$CalendarHolidayStart = $holidayInfo['CALENDAR_HOLIDAY_START'];
$CalendarHolidayEnd = $holidayInfo['CALENDAR_HOLIDAY_END'];
//if exists the row in the database propel will update it, otherwise will insert.
$tr = CalendarHolidaysPeer::retrieveByPK ( $CalendarUid,$CalendarHolidayName );
if ( ( is_object ( $tr ) && get_class ($tr) == 'CalendarHolidays' ) ) {
$tr->delete();
}
}
}
function saveCalendarHolidays($aData){
$CalendarUid = $aData['CALENDAR_UID'];
$CalendarHolidayName = $aData['CALENDAR_HOLIDAY_NAME'];
$CalendarHolidayStart = $aData['CALENDAR_HOLIDAY_START'];
$CalendarHolidayEnd = $aData['CALENDAR_HOLIDAY_END'];
//if exists the row in the database propel will update it, otherwise will insert.
$tr = CalendarHolidaysPeer::retrieveByPK ( $CalendarUid,$CalendarHolidayName);
if ( ! ( is_object ( $tr ) && get_class ($tr) == 'CalendarHolidays' ) ) {
$tr = new CalendarHolidays();
}
$tr->setCalendarUid( $CalendarUid );
$tr->setCalendarHolidayName( $CalendarHolidayName );
$tr->setCalendarHolidayStart( $CalendarHolidayStart );
$tr->setCalendarHolidayEnd( $CalendarHolidayEnd );
if ($tr->validate() ) {
// we save it, since we get no validation errors, or do whatever else you like.
$res = $tr->save();
}
else {
// Something went wrong. We can now get the validationFailures and handle them.
$msg = '';
$validationFailuresArray = $tr->getValidationFailures();
foreach($validationFailuresArray as $objValidationFailure) {
$msg .= $objValidationFailure->getMessage() . "<br/>";
}
//return array ( 'codError' => -100, 'rowsAffected' => 0, 'message' => $msg );
}
//return array ( 'codError' => 0, 'rowsAffected' => $res, 'message' => '');
//to do: uniform coderror structures for all classes
//if ( $res['codError'] < 0 ) {
// G::SendMessageText ( $res['message'] , 'error' );
//}
}
} // CalendarHolidays

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseCalendarHolidaysPeer.php';
// include object class
include_once 'classes/model/CalendarHolidays.php';
/**
* Skeleton subclass for performing query and update operations on the 'CALENDAR_HOLIDAYS' 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 CalendarHolidaysPeer extends BaseCalendarHolidaysPeer {
} // CalendarHolidaysPeer

View File

@@ -0,0 +1,873 @@
<?php
require_once 'classes/model/om/BaseCaseScheduler.php';
require_once 'classes/model/Process.php';
require_once 'classes/model/Task.php';
/**
* Skeleton subclass for representing a row from the 'CASE_SCHEDULER' 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 CaseScheduler extends BaseCaseScheduler {
/*
private $SchTimeNextRun = null;
private $SchLastRunTime = null;
public function getSchTimeNextRun() {
if($this->SchTimeNextRun === null)
$this->SchTimeNextRun = time();
return $this->SchTimeNextRun;
}
public function setSchTimeNextRun($value) {
$this->SchTimeNextRun = $value;
}
public function getSchLastRunTime(){
if($this->SchTimeNextRun === null)
$this->SchTimeNextRun = time();
return $this->SchLastRunTime;
}
public function setSchLastRunTime($value){
$this->SchLastRunTime = $value;
}
*/
public function load($SchUid) {
try {
$oRow = CaseSchedulerPeer::retrieveByPK ( $SchUid );
if (! is_null ( $oRow )) {
$aFields = $oRow->toArray ( BasePeer::TYPE_FIELDNAME );
$this->fromArray ( $aFields, BasePeer::TYPE_FIELDNAME );
$this->setNew ( false );
return $aFields;
} else {
throw (new Exception ( "The row '" . $SchUid . "' in table CASE_SCHEDULER doesn't exist!" ));
}
} catch ( Exception $oError ) {
throw ($oError);
}
}
function create($aData) {
$con = Propel::getConnection ( CaseSchedulerPeer::DATABASE_NAME );
try {
$this->fromArray ( $aData, BasePeer::TYPE_FIELDNAME );
if ($this->validate ()) {
$result = $this->save ();
} else {
$e = new Exception ( "Failed Validation in class " . get_class ( $this ) . "." );
$e->aValidationFailures = $this->getValidationFailures ();
throw ($e);
}
$con->commit ();
return $result;
} catch ( Exception $e ) {
$con->rollback ();
throw ($e);
}
}
public function update($fields) {
$con = Propel::getConnection ( CaseSchedulerPeer::DATABASE_NAME );
try {
$con->begin ();
$this->load ( $fields ['SCH_UID'] );
$this->fromArray ( $fields, BasePeer::TYPE_FIELDNAME );
if ($this->validate ()) {
$result = $this->save ();
$con->commit ();
return $result;
} else {
$con->rollback ();
throw (new Exception ( "Failed Validation in class " . get_class ( $this ) . "." ));
}
} catch ( Exception $e ) {
$con->rollback ();
throw ($e);
}
}
function remove($SchUid) {
$con = Propel::getConnection ( CaseSchedulerPeer::DATABASE_NAME );
try {
$oCaseScheduler = CaseSchedulerPeer::retrieveByPK($SchUid);
if(!is_null($oCaseScheduler)) {
$iResult = $oCaseScheduler->delete();
$con->commit();
return $iResult;
}
else {
throw(new Exception('This row doesn\'t exist!'));
}
/*
$con->begin();
$this->setSchUid ( $SchUid );
$result = $this->delete();
$con->commit();
return $result;
*/
} catch ( Exception $e ) {
$con->rollback();
throw($e);
}
}
/*
* change Status of any Process
* @param string $sSchedulerUid
* @return boolean
*/
function changeStatus($sSchedulerUid = '') {
$Fields = $this->Load ( $sSchedulerUid );
$Fields ['SCH_LAST_STATE'] = $Fields ['SCH_STATE'];
if ($Fields ['SCH_STATE'] == 'ACTIVE') {
$Fields ['SCH_STATE'] = 'INACTIVE';
} else {
$Fields ['SCH_STATE'] = 'ACTIVE';
}
$this->Update ( $Fields );
}
// SELECT A.SCH_UID, A.SCH_NAME, A.PRO_UID, B.CON_VALUE AS PROCESS,
// A.TAS_UID, B.CON_VALUE AS TASK, A.SCH_TIME_NEXT_RUN, A.SCH_LAST_RUN_TIME, A.SCH_STATE, A.SCH_LAST_STATE,
// A.USR_UID, A.SCH_OPTION
// SCH_START_TIME, SCH_START_DATE, SCH_DAYS_PERFORM_TASK, SCH_EVERY_DAYS, SCH_WEEK_DAYS
// SCH_START_DAY, SCH_MONTHS, SCH_END_DATE, SCH_REPEAT_EVERY, SCH_REPEAT_UNTIL, SCH_REPEAT_STOP_IF_RUNNING
// FROM CASE_SCHEDULER A LEFT JOIN CONTENT B ON A.PRO_UID= B.CON_ID AND B.CON_CATEGORY='PRO_TITLE' AND B.CON_LANG='en'
// LEFT JOIN CONTENT C ON A.TAS_UID= C.CON_ID AND C.CON_CATEGORY='TAS_TITLE' AND C.CON_LANG='en'
//
function getAllCriteria() {
$c = new Criteria ( 'workflow' );
$c->clearSelectColumns ();
$c->addSelectColumn ( CaseSchedulerPeer::SCH_UID );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_NAME );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_DEL_USER_NAME );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_DEL_USER_PASS );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_DEL_USER_UID );
$c->addSelectColumn ( CaseSchedulerPeer::PRO_UID );
$c->addSelectColumn ( CaseSchedulerPeer::TAS_UID );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_TIME_NEXT_RUN );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_LAST_RUN_TIME );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_STATE );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_LAST_STATE );
$c->addSelectColumn ( CaseSchedulerPeer::USR_UID );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_OPTION );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_START_TIME );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_START_DATE );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_DAYS_PERFORM_TASK );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_EVERY_DAYS );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_WEEK_DAYS );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_START_DAY );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_MONTHS );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_END_DATE );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_REPEAT_EVERY );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_REPEAT_UNTIL );
$c->addSelectColumn ( CaseSchedulerPeer::SCH_REPEAT_STOP_IF_RUNNING );
$c->addSelectColumn ( CaseSchedulerPeer::CASE_SH_PLUGIN_UID );
return $c;
}
function getAll() {
$oCriteria = $this->getAllCriteria ();
$oDataset = CaseSchedulerPeer::doSelectRS ( $oCriteria );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$aRows = Array ();
while ( $aRow = $oDataset->getRow () ) {
$aRows [] = $aRow;
$oDataset->next ();
}
foreach ( $aRows as $k => $aRow ) {
$oProcess = new Process ();
$aProcessRow = $oProcess->load ( $aRow ['PRO_UID'] );
$oTask = new Task ();
$aTaskRow = $oTask->load ( $aRow ['TAS_UID'] );
$aRows [$k] = array_merge ( $aRow, $aProcessRow, $aTaskRow );
}
return $aRows;
}
/**
* function getAllByProcess
* @author gustavo cruz
* @desc Get All Scheduled Tasks for some process.
* @param $pro_uid process uid
* @return $aRows a result set array
*/
function getAllByProcess($pro_uid) {
$oCriteria = $this->getAllCriteria ();
$oCriteria->add ( CaseSchedulerPeer::PRO_UID, $pro_uid );
$oDataset = CaseSchedulerPeer::doSelectRS ( $oCriteria );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$aRows = Array ();
while ( $aRow = $oDataset->getRow () ) {
$aRows [] = $aRow;
$oDataset->next ();
}
foreach ( $aRows as $k => $aRow ) {
$oProcess = new Process ();
$aProcessRow = $oProcess->load ( $aRow ['PRO_UID'] );
$oTask = new Task ();
$aTaskRow = $oTask->load ( $aRow ['TAS_UID'] );
$aRows [$k] = array_merge ( $aRow, $aProcessRow, $aTaskRow );
}
return $aRows;
}
function getProcessDescription() {
$c = new Criteria ( 'workflow' );
$c->clearSelectColumns ();
$c->addSelectColumn ( ProcessPeer::PRO_UID );
$oDataset = ProcessPeer::doSelectRS ( $c );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$aRows = Array ();
while ( $aRow = $oDataset->getRow () ) {
$aRows [] = $aRow;
$oDataset->next ();
}
foreach ( $aRows as $k => $aRow ) {
$oProcess = new Process ();
$aProcessRow = $oProcess->load ( $aRow ['PRO_UID'] );
$aRows [$k] = array_merge ( $aRow, array (
'PRO_TITLE' => $aProcessRow ['PRO_TITLE']
) );
}
return $aRows;
}
function getTaskDescription() {
$c = new Criteria ( 'workflow' );
$c->clearSelectColumns ();
$c->addSelectColumn ( TaskPeer::TAS_UID );
$oDataset = TaskPeer::doSelectRS ( $c );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$aRows = Array ();
while ( $aRow = $oDataset->getRow () ) {
$aRows [] = $aRow;
$oDataset->next ();
}
foreach ( $aRows as $k => $aRow ) {
$oTask = new Task ();
$aTaskRow = $oTask->load ( $aRow ['TAS_UID'] );
$aRows [$k] = array_merge ( $aRow, array (
'TAS_TITLE' => $aTaskRow ['TAS_TITLE']
), array (
'PRO_UID' => $aTaskRow ['PRO_UID']
) );
}
// g::pr($aRows); die;
return $aRows;
}
function caseSchedulerCron($date) {
G::LoadClass ( 'dates' );
require_once ('classes/model/LogCasesScheduler.php');
$oDates = new dates ();
$nTime = strtotime ( $date );
$dCurrentDate = date ( 'Y-m-d', $nTime ) . ' 00:00:00';
$dNextDay = date ( 'Y-m-d', strtotime ( "$dCurrentDate" ) ) . ' 23:59:59';
$oCriteria = $this->getAllCriteria ();
$oCriteria->addAnd ( CaseSchedulerPeer::SCH_STATE, 'INACTIVE', Criteria::NOT_EQUAL );
$oCriteria->addAnd ( CaseSchedulerPeer::SCH_STATE, 'PROCESSED', Criteria::NOT_EQUAL );
$oCriteria->add ( CaseSchedulerPeer::SCH_TIME_NEXT_RUN, $dCurrentDate, Criteria::GREATER_EQUAL );
$oCriteria->addAnd ( CaseSchedulerPeer::SCH_TIME_NEXT_RUN, $dNextDay, Criteria::LESS_EQUAL );
$oCriteria->add ( CaseSchedulerPeer::SCH_END_DATE, null, Criteria::EQUAL );
$oCriteria->addOr ( CaseSchedulerPeer::SCH_END_DATE, $dCurrentDate, Criteria::GREATER_EQUAL );
$oDataset = CaseSchedulerPeer::doSelectRS ( $oCriteria );
$oDataset->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$oDataset->next ();
$sValue = '';
$sActualTime = '';
$sDaysPerformTask = '';
$sWeeks = '';
$sStartDay = '';
$sMonths = '';
while ( $aRow = $oDataset->getRow () ) {
$sSchedulerUid = $aRow ['SCH_UID'];
$sOption = $aRow ['SCH_OPTION'];
switch ($sOption) {
case '1' :
$sDaysPerformTask = $aRow ['SCH_DAYS_PERFORM_TASK'];
$aDaysPerformTask = explode ( '|', $sDaysPerformTask );
$sValue = $aDaysPerformTask [0];
if ($sValue != 1)
$sDaysPerformTask = $aDaysPerformTask [1];
break;
case '2' :
$sDaysPerformTask = $aRow ['SCH_EVERY_DAYS'];
$sWeeks = $aRow ['SCH_WEEK_DAYS'];
break;
case '3' :
$sStartDay = $aRow ['SCH_START_DAY'];
$sMonths = $aRow ['SCH_MONTHS'];
$aStartDay = explode ( '|', $sStartDay );
$sValue = $aStartDay [0];
break;
case '4' :
$aRow ['SCH_STATE'] = 'PROCESSED';
break;
}
$sActualTime = $aRow ['SCH_TIME_NEXT_RUN'];
$sActualDataHour = date ( 'H', strtotime ( $aRow ['SCH_TIME_NEXT_RUN'] ) );
$sActualDataMinutes = date ( 'i', strtotime ( $aRow ['SCH_TIME_NEXT_RUN'] ) );
$dActualSysHour = date ( 'H', $nTime );
$dActualSysMinutes = date ( 'i', $nTime );
$sActualDataTime = strtotime ( $aRow ['SCH_TIME_NEXT_RUN'] );
$sActualSysTime = strtotime ( $nTime );
// note added consider the posibility to encapsulate some in functionality in a class method or some funtions
if ($sActualDataHour < $dActualSysHour) {
$_PORT = (SERVER_PORT != '80') ? ':' . SERVER_PORT : '';
$defaultEndpoint = 'http://' . SERVER_NAME . $_PORT . '/sys' . SYS_SYS . '/en/green/services/wsdl2';
println(" - Connecting webservice: $defaultEndpoint");
$user = $aRow ["SCH_DEL_USER_NAME"];
$pass = $aRow ["SCH_DEL_USER_PASS"];
$processId = $aRow ["PRO_UID"];
$taskId = $aRow ["TAS_UID"];
$client = new SoapClient ( $defaultEndpoint );
$params = array (
'userid' => $user,
'password' => 'md5:' . $pass
);
$result = $client->__SoapCall ( 'login', array (
$params
) );
eprint(" - Logging as user $user.............");
if ($result->status_code == 0) {
eprintln("OK+", 'green');
$sessionId = $result->message;
$newCaseLog = new LogCasesScheduler ();
$newRouteLog = new LogCasesScheduler ();
$variables = Array ();
$params = array (
'sessionId' => $sessionId,
'processId' => $processId,
'taskId' => $taskId,
'variables' => $variables
);
$paramsLog = array (
'PRO_UID' => $processId,
'TAS_UID' => $taskId,
'SCH_UID' => $sSchedulerUid,
'USR_NAME' => $user,
'RESULT' => '',
'EXEC_DATE' => date ( 'Y-m-d' ),
'EXEC_HOUR' => date ( 'H:i:s' ),
'WS_CREATE_CASE_STATUS' => '',
'WS_ROUTE_CASE_STATUS' => ''
);
$sw_transfer_control_plugin=false;//This SW will be true only if a plugin is allowed to continue the action
//If this Job was was registered to be performed by a plugin
if((isset($aRow['CASE_SH_PLUGIN_UID']))&&($aRow['CASE_SH_PLUGIN_UID']!="")){
//Check if the plugin is active
$pluginParts=explode("--",$aRow['CASE_SH_PLUGIN_UID']);
if(count($pluginParts)==2){
//***************** 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 ) );
$oPluginRegistry =& PMPluginRegistry::getSingleton();
$activePluginsForCaseScheduler=$oPluginRegistry->getCaseSchedulerPlugins();
foreach($activePluginsForCaseScheduler as $key => $caseSchedulerPlugin){
if((isset($caseSchedulerPlugin->sNamespace))&&($caseSchedulerPlugin->sNamespace==$pluginParts[0])&&(isset($caseSchedulerPlugin->sActionId))&&($caseSchedulerPlugin->sActionId==$pluginParts[1])){
$sw_transfer_control_plugin=true;
$caseSchedulerSelected=$caseSchedulerPlugin;
}
}
}
}
//If there is a trigger that is registered to do this then transfer control
if((isset($caseSchedulerSelected))&&(is_object($caseSchedulerSelected))){
eprintln(" - Transfering control to a Plugin: ".$caseSchedulerSelected->sNamespace."/".$caseSchedulerSelected->sActionId,'green');
$oData['OBJ_SOAP'] = $client;
$oData['SCH_UID'] = $aRow['SCH_UID'];
$oData['params'] = $params;
$oData['sessionId'] = $sessionId;
$oData['userId'] = $user;
$paramsLogResultFromPlugin=$oPluginRegistry->executeMethod( $caseSchedulerSelected->sNamespace, $caseSchedulerSelected->sActionExecute, $oData );
$paramsLog['WS_CREATE_CASE_STATUS']=$paramsLogResultFromPlugin['WS_CREATE_CASE_STATUS'];
$paramsLog['WS_ROUTE_CASE_STATUS']=$paramsLogResultFromPlugin['WS_ROUTE_CASE_STATUS'];
$paramsLogResult=$paramsLogResultFromPlugin['paramsLogResult'];
$paramsRouteLogResult=$paramsLogResultFromPlugin['paramsRouteLogResult'];
}else{
eprint(" - Creating the new case.............");
$result = $client->__SoapCall ( 'NewCase', array (
$params
) );
if ($result->status_code == 0) {
eprintln("OK+ CASE #{$result->caseNumber} was created!", 'green');
$caseId = $result->caseId;
$caseNumber = $result->caseNumber;
$paramsLog ['WS_CREATE_CASE_STATUS'] = "Case " . $caseNumber . " " . strip_tags ( $result->message );
$paramsLogResult = 'SUCCESS';
$params = array (
'sessionId' => $sessionId,
'caseId' => $caseId,
'delIndex' => "1"
);
eprint(" - Routing the case #$caseNumber..............");
$result = $client->__SoapCall ( 'RouteCase', array (
$params
) );
if ($result->status_code == 0) {
$paramsLog ['WS_ROUTE_CASE_STATUS'] = strip_tags ( $result->message );
$retMsg = explode("Debug", $paramsLog ['WS_ROUTE_CASE_STATUS']);
$retMsg = $retMsg[0];
eprintln("OK+ $retMsg", 'green');
$paramsRouteLogResult = 'SUCCESS';
} else {
$paramsLog ['WS_ROUTE_CASE_STATUS'] = strip_tags ( $result->message );
eprintln("FAILED-> {$paramsLog ['WS_ROUTE_CASE_STATUS']}", 'red');
$paramsRouteLogResult = 'FAILED';
}
} else {
$paramsLog ['WS_CREATE_CASE_STATUS'] = strip_tags ( $result->message );
$paramsLogResult = 'FAILED';
}
}
} else {
eprintln($result->message, 'red');
// invalid user or bad password
}
if ($paramsLogResult == 'SUCCESS' && $paramsRouteLogResult == 'SUCCESS') {
$paramsLog ['RESULT'] = 'SUCCESS';
} else {
$paramsLog ['RESULT'] = 'FAILED';
}
$newCaseLog->saveLogParameters ( $paramsLog );
$newCaseLog->save ();
if ($sOption != '4') {
$nSchLastRunTime = $sActualTime;
$dEstimatedDate = $this->updateNextRun ( $sOption, $sValue, $sActualTime, $sDaysPerformTask, $sWeeks, $sStartDay, $sMonths );
if ($aRow ['SCH_END_DATE'] != '') {
if (date ( "Y-m-d", strtotime ( $dEstimatedDate ) ) > date ( "Y-m-d", strtotime ( $aRow ['SCH_END_DATE'] ) )) {
$Fields = $this->Load ( $sSchedulerUid );
$Fields ['SCH_LAST_STATE'] = $aRow ['SCH_STATE'];
$Fields ['SCH_STATE'] = 'PROCESSED';
$this->Update ( $Fields );
}
}
$nSchTimeNextRun = $dEstimatedDate;
$this->updateDate ( $sSchedulerUid, $nSchTimeNextRun, $nSchLastRunTime );
} else {
$Fields = $this->Load ( $sSchedulerUid );
$Fields ['SCH_LAST_STATE'] = $aRow ['SCH_STATE'];
$Fields ['SCH_LAST_RUN_TIME'] = $Fields ['SCH_TIME_NEXT_RUN'];
$Fields ['SCH_STATE'] = 'PROCESSED';
$this->Update ( $Fields );
}
} else if ($sActualDataHour == $dActualSysHour && $sActualDataMinutes <= $dActualSysMinutes) {
$_PORT = ($_SERVER ['SERVER_PORT'] != '80') ? ':' . $_SERVER ['SERVER_PORT'] : '';
//$defaultEndpoint = 'http://' . $_SERVER ['SERVER_NAME'] . ':' . $_PORT . '/sys' . SYS_SYS . '/en/green/services/wsdl2';
$defaultEndpoint = 'http://' . SERVER_NAME . $_PORT . '/sys' . SYS_SYS . '/en/green/services/wsdl2';
println(" - Connecting webservice: $defaultEndpoint");
$user = $aRow ["SCH_DEL_USER_NAME"];
$pass = $aRow ["SCH_DEL_USER_PASS"];
$processId = $aRow ["PRO_UID"];
$taskId = $aRow ["TAS_UID"];
$client = new SoapClient ( $defaultEndpoint );
$params = array (
'userid' => $user,
'password' => 'md5:' . $pass
);
$result = $client->__SoapCall ( 'login', array (
$params
) );
eprint(" - Logging as user $user.............");
if ($result->status_code == 0) {
eprintln("OK+", 'green');
$sessionId = $result->message;
$newCaseLog = new LogCasesScheduler ();
$newRouteLog = new LogCasesScheduler ();
$variables = Array ();
$params = array (
'sessionId' => $sessionId,
'processId' => $processId,
'taskId' => $taskId,
'variables' => $variables
);
$paramsLog = array (
'PRO_UID' => $processId,
'TAS_UID' => $taskId,
'SCH_UID' => $sSchedulerUid,
'USR_NAME' => $user,
'RESULT' => '',
'EXEC_DATE' => date ( 'Y-m-d' ),
'EXEC_HOUR' => date ( 'H:i:s' ),
'WS_CREATE_CASE_STATUS' => '',
'WS_ROUTE_CASE_STATUS' => ''
);
$result = $client->__SoapCall ( 'NewCase', array (
$params
) );
eprint(" - Creating the new case.............");
if ($result->status_code == 0) {
eprintln("OK+ CASE #{$result->caseNumber} was created!", 'green');
$caseId = $result->caseId;
$caseNumber = $result->caseNumber;
$paramsLog ['WS_CREATE_CASE_STATUS'] = "Case " . $caseNumber . " " . strip_tags ( $result->message );
$paramsLogResult = 'SUCCESS';
$params = array (
'sessionId' => $sessionId,
'caseId' => $caseId,
'delIndex' => "1"
);
$result = $client->__SoapCall ( 'RouteCase', array (
$params
) );
eprint(" - Routing the case #$caseNumber..............");
if ($result->status_code == 0) {
$paramsLog ['WS_ROUTE_CASE_STATUS'] = strip_tags ( $result->message );
$retMsg = explode("Debug", $paramsLog ['WS_ROUTE_CASE_STATUS']);
$retMsg = $retMsg[0];
eprintln("OK+ $retMsg", 'green');
$paramsRouteLogResult = 'SUCCESS';
} else {
eprintln("FAILED-> {$paramsLog ['WS_ROUTE_CASE_STATUS']}", 'red');
$paramsLog ['WS_ROUTE_CASE_STATUS'] = strip_tags ( $result->message );
$paramsRouteLogResult = 'FAILED';
}
} else {
$paramsLog ['WS_CREATE_CASE_STATUS'] = strip_tags ( $result->message );
eprintln("FAILED->{$paramsLog ['WS_CREATE_CASE_STATUS']}", 'red');
$paramsLogResult = 'FAILED';
}
} else {
// invalid user or bad password
eprintln($result->message, 'red');
}
if ($paramsLogResult == 'SUCCESS' && $paramsRouteLogResult == 'SUCCESS') {
$paramsLog ['RESULT'] = 'SUCCESS';
} else {
$paramsLog ['RESULT'] = 'FAILED';
}
$newCaseLog->saveLogParameters ( $paramsLog );
$newCaseLog->save ();
if ($sOption != '4') {
$nSchLastRunTime = $sActualTime;
$dEstimatedDate = $this->updateNextRun ( $sOption, $sValue, $sActualTime, $sDaysPerformTask, $sWeeks, $sStartDay, $sMonths );
if ($aRow ['SCH_END_DATE'] != '') {
if (date ( "Y-m-d", strtotime ( $dEstimatedDate ) ) > date ( "Y-m-d", strtotime ( $aRow ['SCH_END_DATE'] ) )) {
$Fields = $this->Load ( $sSchedulerUid );
$Fields ['SCH_LAST_STATE'] = $aRow ['SCH_STATE'];
$Fields ['SCH_STATE'] = 'PROCESSED';
$this->Update ( $Fields );
}
}
$nSchTimeNextRun = $dEstimatedDate;
$this->updateDate ( $sSchedulerUid, $nSchTimeNextRun, $nSchLastRunTime );
} else {
$Fields = $this->Load ( $sSchedulerUid );
$Fields ['SCH_LAST_STATE'] = $aRow ['SCH_STATE'];
$Fields ['SCH_LAST_RUN_TIME'] = $Fields ['SCH_TIME_NEXT_RUN'];
$Fields ['SCH_STATE'] = 'PROCESSED';
$this->Update ( $Fields );
}
}
$oDataset->next ();
}
}
function updateDate($sSchedulerUid = '', $sSchTimeNextRun = '', $sSchLastRunTime = '') {
$Fields = $this->Load ( $sSchedulerUid );
$Fields ['SCH_TIME_NEXT_RUN'] = strtotime ( $sSchTimeNextRun );
$Fields ['SCH_LAST_RUN_TIME'] = strtotime ( $sSchLastRunTime );
$this->Update ( $Fields );
}
function updateNextRun($sOption, $sValue = '', $sActualTime = '', $sDaysPerformTask = '', $sWeeks = '', $sStartDay = '', $sMonths = '', $currentDate = '') {
$nActualDate = $currentDate . " " . $sActualTime; // date("Y-m-d H:i:s", $sActualTime);
// date("Y-m-d H:i:s", $sActualTime);
$dEstimatedDate = '';
switch ($sOption) {
case '1' :
switch ($sValue) {
case '1' :
$dEstimatedDate = date ( 'Y-m-d H:i:s', strtotime ( "$nActualDate +1 day" ) );
break;
case '2' :
$nDayOfTheWeek = date ( 'w', strtotime ( $sActualTime ) );
$nDayOfTheWeek = ($nDayOfTheWeek == 0) ? 7 : $nDayOfTheWeek;
if ($nDayOfTheWeek >= 5)
$dEstimatedDate = date ( 'Y-m-d H:i:s', strtotime ( "$nActualDate +3 day" ) );
else
$dEstimatedDate = date ( 'Y-m-d H:i:s', strtotime ( "$nActualDate +1 day" ) );
break;
case '3' :
$dEstimatedDate = date ( 'Y-m-d H:i:s', strtotime ( "$nActualDate + " . $sDaysPerformTask . " day" ) );
break;
}
break;
case '2' :
if (strlen ( $sWeeks ) > 0) {
//die($sActualTime);
$nDayOfTheWeek = date ( 'w', strtotime ( $sActualTime ) );
// $nDayOfTheWeek = 1;
// echo "*".$nDayOfTheWeek."*";
$aWeeks = explode ( '|', $sWeeks );
$nFirstDay = $aWeeks [0];
$aDaysWeek = array (
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
);
$nFirstDay = $nFirstDay - 1;
// echo "¨¨".$nFirstDay."¨¨";
$nDayOfTheWeek = ($nDayOfTheWeek == 0) ? 7 : $nDayOfTheWeek;
// echo $nDayOfTheWeek;
$nSW = 0;
$nNextDay = 0;
foreach ( $aWeeks as $value ) {
if ($value > $nDayOfTheWeek) {
$nNextDay = $value - 1;
$nSW = 1;
break;
}
}
//die;
if ($nSW == 1) {
$dEstimatedDate = date ( 'Y-m-d', strtotime ( "$nActualDate next " . $aDaysWeek [$nNextDay] ) ) . ' ' . date ( 'H:i:s', strtotime ( $sActualTime ) );
//print_r($dEstimatedDate);
// die("03");
} else {
$nEveryDays = $sDaysPerformTask;
// $nEveryDays = '1';
if ($nFirstDay >= $nDayOfTheWeek || $nEveryDays == 1)
$sTypeOperation = "next";
else
$sTypeOperation = "last";
if ($nEveryDays == 1) {
// echo "**** $nActualDate *" . $sTypeOperation . "* *" . $aDaysWeek[$nFirstDay] . '*****' . date('H:i:s', strtotime($sActualTime)). "**";
$dEstimatedDate = date ( 'Y-m-d', strtotime ( "$nActualDate " . $sTypeOperation . " " . $aDaysWeek [$nFirstDay] ) ) . ' ' . date ( 'H:i:s', strtotime ( $sActualTime ) );
// echo "(date)*".$dEstimatedDate."*";
// die("01");
} else {
$nEveryDays = 1;
// $nActualDate = date('Y-m-d').' '.$sActualTime;
$nDataTmp = date ( 'Y-m-d', strtotime ( "$nActualDate + " . $nEveryDays . " Week" ) );
// echo "$nActualDate + " . $nEveryDays . " Week ";
// echo "++";
// echo strtotime( "+".$nEveryDays . " week"), "\n";
// echo strtotime("$nActualDate +" . $nEveryDays . " Week ");
// echo "++";
// echo $nDataTmp;
// echo "--";
// echo $sTypeOperation;
// echo $nFirstDay;
// print_r ($aDaysWeek);
// $sTypeOperation = "next";
$dEstimatedDate = date ( 'Y-m-d', strtotime ( "$nDataTmp " . $sTypeOperation . " " . $aDaysWeek [$nFirstDay] ) ) . ' ' . date ( 'H:i:s', strtotime ( $sActualTime ) );
// echo (strtotime ("$nDataTmp " . $sTypeOperation . " " . $aDaysWeek[$nFirstDay]));
// echo "$nDataTmp " . $sTypeOperation . " " . $aDaysWeek[$nFirstDay];
// echo $dEstimatedDate;
// echo "--";
// echo date('Y-m-d', strtotime ("$nDataTmp " . $sTypeOperation . " " . $aDaysWeek[$nFirstDay])) . ' ' . date('H:i:s', strtotime($sActualTime));
// die("02");
}
// die("03");
}
}
break;
case '3' :
if (strlen ( $sMonths ) > 0) { // Must have at least one selected month
// Calculamos para la siguiente ejecucion, acorde a lo seleccionado
$aStartDay = explode ( '|', $sStartDay );
$nYear = date ( "Y", strtotime ( $sActualTime ) );
$nCurrentMonth = date ( "m", strtotime ( $sActualTime ) );
$nCurrentDay = date ( "d", strtotime ( $sActualTime ) );
$aMonths = explode ( '|', $sMonths );
$nSW = 0;
$nNextMonth = 0;
foreach ( $aMonths as $value ) {
if ($value > $nCurrentMonth) {
$nNextMonth = $value - 1;
$nSW = 1;
break;
}
}
if ($nSW == 1) { // Mes encontrado
$nExecNextMonth = $nNextMonth;
} else {
$nExecNextMonth = $aMonths [0] - 1;
$nYear ++;
}
switch ($sValue) {
case '1' :
$nExecNextMonth ++;
$nCurrentDay = $aStartDay [1];
$dEstimatedDate = date ( 'Y-m-d', strtotime ( "$nYear-$nExecNextMonth-$nCurrentDay" ) ) . ' ' . date ( 'H:i:s', strtotime ( $sActualTime ) );
break;
case '2' :
$aMontsShort = array (
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
);
$aWeeksShort = array (
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
);
$sNumDayWeek = $aStartDay [1];
$sDayWeek = ($aStartDay [2] == 7 ? 0 : $aStartDay [2]);
switch ($sNumDayWeek) {
case '1' :
$sDaysWeekOpt = "+0";
break;
case '2' :
$sDaysWeekOpt = "+1";
break;
case '3' :
$sDaysWeekOpt = "+2";
break;
case '4' :
$sDaysWeekOpt = "+3";
break;
case '5' :
$sDaysWeekOpt = "-1";
$nExecNextMonth ++;
if ($nExecNextMonth >= 12) {
$nExecNextMonth = 0;
$nYear ++;
}
break;
}
$dEstimatedDate = date ( 'Y-m-d', strtotime ( $sDaysWeekOpt . ' week ' . $aWeeksShort [$sDayWeek - 1] . ' ' . $aMontsShort [$nExecNextMonth] . ' ' . $nYear ) ) . ' ' . date ( 'H:i:s', strtotime ( $sActualTime ) );
// krumo($nExecNextMonth, $sDayWeek);
// krumo($sDaysWeekOpt . ' week ' . $aWeeksShort[$sDayWeek-1] . ' ' . $aMontsShort[$nExecNextMonth] . ' ' . $nYear);
break;
}
}
break;
}
return $dEstimatedDate;
}
function Exists( $sUid ) {
try {
$oObj = CaseSchedulerPeer::retrieveByPk( $sUid );
return (get_class($oObj) == 'CaseScheduler');
}
catch (Exception $oError) {
throw($oError);
}
}
} // CaseScheduler

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseCaseSchedulerPeer.php';
// include object class
include_once 'classes/model/CaseScheduler.php';
/**
* Skeleton subclass for performing query and update operations on the 'CASE_SCHEDULER' 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 CaseSchedulerPeer extends BaseCaseSchedulerPeer {
} // CaseSchedulerPeer

View File

@@ -0,0 +1,121 @@
<?php
require_once 'classes/model/om/BaseCaseTracker.php';
/**
* Skeleton subclass for representing a row from the 'CASE_TRACKER' 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 CaseTracker extends BaseCaseTracker {
public function load($sProcessUID) {
try {
$oRow = CaseTrackerPeer::retrieveByPK($sProcessUID);
if (!is_null($oRow)) {
$aFields = $oRow->toArray(BasePeer::TYPE_FIELDNAME);
$this->fromArray($aFields, BasePeer::TYPE_FIELDNAME);
$this->setNew(false);
return $aFields;
}
else {
throw(new Exception("The row '$sProcessUID' in table CASE_TRACKER doesn't exist!"));
}
}
catch (Exception $oError) {
throw($oError);
}
}
public function create($aData) {
$oConnection = Propel::getConnection(CaseTrackerPeer::DATABASE_NAME);
try {
if (!isset($aData['CT_MAP_TYPE'])) {
$aData['CT_MAP_TYPE'] = 'PROCESSMAP';
}
$oCaseTracker = new CaseTracker();
$oCaseTracker->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($oCaseTracker->validate()) {
$oConnection->begin();
$iResult = $oCaseTracker->save();
$oConnection->commit();
return true;
}
else {
$sMessage = '';
$aValidationFailures = $oCaseTracker->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be created!<br />'.$sMessage));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
public function update($aData) {
$oConnection = Propel::getConnection(CaseTrackerPeer::DATABASE_NAME);
try {
$oCaseTracker = CaseTrackerPeer::retrieveByPK($aData['PRO_UID']);
if (!is_null($oCaseTracker))
{
$oCaseTracker->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($oCaseTracker->validate()) {
$oConnection->begin();
$iResult = $oCaseTracker->save();
$oConnection->commit();
return $iResult;
}
else {
$sMessage = '';
$aValidationFailures = $oCaseTracker->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be updated!<br />'.$sMessage));
}
}
else {
throw(new Exception('This row doesn\'t exist!'));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
public function remove($sProcessUID) {
$oConnection = Propel::getConnection(CaseTrackerPeer::DATABASE_NAME);
try {
$oConnection->begin();
$this->setProUid($sProcessUID);
$iResult = $this->delete();
$oConnection->commit();
return $iResult;
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
function caseTrackerExists ( $sUid ) {
try {
$oObj = CaseTrackerPeer::retrieveByPk($sUid);
return (get_class($oObj) == 'CaseTracker');
}
catch (Exception $oError) {
throw($oError);
}
}
} // CaseTracker

View File

@@ -0,0 +1,169 @@
<?php
require_once 'classes/model/om/BaseCaseTrackerObject.php';
/**
* Skeleton subclass for representing a row from the 'CASE_TRACKER_OBJECT' 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 CaseTrackerObject extends BaseCaseTrackerObject {
public function load($Uid) {
try {
$oRow = CaseTrackerObjectPeer::retrieveByPK( $Uid );
if (!is_null($oRow))
{
$aFields = $oRow->toArray(BasePeer::TYPE_FIELDNAME);
$this->fromArray($aFields,BasePeer::TYPE_FIELDNAME);
$this->setNew(false);
return $aFields;
}
else {
throw( new Exception( "The row '$Uid' in table CaseTrackerObject doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
public function create($aData) {
$oConnection = Propel::getConnection(CaseTrackerObjectPeer::DATABASE_NAME);
try {
if (!isset($aData['CTO_UID'])) {
$aData['CTO_UID'] = G::generateUniqueID();
}
$oCaseTrackerObject = new CaseTrackerObject();
$oCaseTrackerObject->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($oCaseTrackerObject->validate()) {
$oConnection->begin();
$iResult = $oCaseTrackerObject->save();
$oConnection->commit();
return true;
}
else {
$sMessage = '';
$aValidationFailures = $oCaseTrackerObject->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be created!<br />'.$sMessage));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
public function update($aData)
{
$oConnection = Propel::getConnection(CaseTrackerObjectPeer::DATABASE_NAME);
try {
$oCaseTrackerObject = CaseTrackerObjectPeer::retrieveByPK($aData['CTO_UID']);
if (!is_null($oCaseTrackerObject))
{
$oCaseTrackerObject->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($oCaseTrackerObject->validate()) {
$oConnection->begin();
$iResult = $oCaseTrackerObject->save();
$oConnection->commit();
return $iResult;
}
else {
$sMessage = '';
$aValidationFailures = $oCaseTrackerObject->getValidationFailures();
foreach($aValidationFailures as $oValidationFailure) {
$sMessage .= $oValidationFailure->getMessage() . '<br />';
}
throw(new Exception('The registry cannot be updated!<br />'.$sMessage));
}
}
else {
throw(new Exception('This row doesn\'t exist!'));
}
}
catch (Exception $oError) {
$oConnection->rollback();
throw($oError);
}
}
public function remove($sCTOUID) {
$oConnection = Propel::getConnection(CaseTrackerObjectPeer::DATABASE_NAME);
try {
$oCaseTobj = CaseTrackerObjectPeer::retrieveByPK($sCTOUID);
if (get_class($oCaseTobj) == 'CaseTrackerObject')
{
$oConnection->begin();
$iResult = $oCaseTobj->delete();
$oConnection->commit();
return $iResult;
}
else {
throw( new Exception( "The row '" . $sCTOUID . "' in table CaseTrackerObject doesn't exist!" ));
}
}
catch (Exception $oError) {var_dump($oError);die;
$oConnection->rollback();
throw($oError);
}
}
function reorderPositions($sProcessUID, $iPosition) {
try {
$oCriteria = new Criteria('workflow');
$oCriteria->add(CaseTrackerObjectPeer::PRO_UID, $sProcessUID);
$oCriteria->add(CaseTrackerObjectPeer::CTO_POSITION, $iPosition, '>');
$oDataset = CaseTrackerObjectPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$this->update(array('CTO_UID' => $aRow['CTO_UID'],
'PRO_UID' => $aRow['PRO_UID'],
'CTO_TYPE_OBJ' => $aRow['CTO_TYPE_OBJ'],
'CTO_UID_OBJ' => $aRow['CTO_UID_OBJ'],
'CTO_CONDITION' => $aRow['CTO_CONDITION'],
'CTO_POSITION' => $aRow['CTO_POSITION'] - 1));
$oDataset->next();
}
}
catch (Exception $oException) {
throw $Exception;
}
}
function caseTrackerObjectExists ( $Uid ) {
try {
$oObj = CaseTrackerObjectPeer::retrieveByPk( $Uid );
if ( get_class ($oObj) == 'CaseTrackerObject' ) {
return true;
}
else {
return false;
}
}
catch (Exception $oError) {
throw($oError);
}
}
function removeByObject($sType, $sObjUid) {
try {
$oCriteria = new Criteria('workflow');
$oCriteria->add(CaseTrackerObjectPeer::CTO_TYPE_OBJ, $sType);
$oCriteria->add(CaseTrackerObjectPeer::CTO_UID_OBJ, $sObjUid);
CaseTrackerObjectPeer::doDelete($oCriteria);
}
catch(Exception $e) {
throw($e);
}
}
} // CaseTrackerObject

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseCaseTrackerObjectPeer.php';
// include object class
include_once 'classes/model/CaseTrackerObject.php';
/**
* Skeleton subclass for performing query and update operations on the 'CASE_TRACKER_OBJECT' 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 CaseTrackerObjectPeer extends BaseCaseTrackerObjectPeer {
} // CaseTrackerObjectPeer

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseCaseTrackerPeer.php';
// include object class
include_once 'classes/model/CaseTracker.php';
/**
* Skeleton subclass for performing query and update operations on the 'CASE_TRACKER' 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 CaseTrackerPeer extends BaseCaseTrackerPeer {
} // CaseTrackerPeer

View File

@@ -0,0 +1,145 @@
<?php
/**
* Configuration.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.
*
*/
require_once 'classes/model/om/BaseConfiguration.php';
require_once 'classes/model/Content.php';
/**
* Skeleton subclass for representing a row from the 'CONFIGURATION' 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 Configuration extends BaseConfiguration {
public function create($aData)
{
$con = Propel::getConnection(ConfigurationPeer::DATABASE_NAME);
try
{
$con->begin();
$this->setCfgUid($aData['CFG_UID']);
$this->setObjUid($aData['OBJ_UID']);
$this->setCfgValue(isset($aData['CFG_VALUE'])?$aData['CFG_VALUE']:'');
$this->setProUid($aData['PRO_UID']);
$this->setUsrUid($aData['USR_UID']);
$this->setAppUid($aData['APP_UID']);
if($this->validate())
{
$result=$this->save();
$con->commit();
return $result;
}
else
{
$con->rollback();
throw(new Exception("Failed Validation in class ".get_class($this)."."));
}
}
catch(Exception $e)
{
$con->rollback();
throw($e);
}
}
public function load($CfgUid, $ObjUid='', $ProUid='', $UsrUid='', $AppUid='')
{
try {
$oRow = ConfigurationPeer::retrieveByPK( $CfgUid, $ObjUid, $ProUid, $UsrUid, $AppUid );
if (!is_null($oRow))
{
$aFields = $oRow->toArray(BasePeer::TYPE_FIELDNAME);
$this->fromArray($aFields,BasePeer::TYPE_FIELDNAME);
$this->setNew(false);
return $aFields;
}
else {
throw(new Exception( "The row '$CfgUid, $ObjUid, $ProUid, $UsrUid, $AppUid' in table Configuration doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
public function update($fields)
{
$con = Propel::getConnection(ConfigurationPeer::DATABASE_NAME);
try
{
$con->begin();
$this->load($fields['CFG_UID'], $fields['OBJ_UID'], $fields['PRO_UID'], $fields['USR_UID'], $fields['APP_UID']);
$this->fromArray($fields,BasePeer::TYPE_FIELDNAME);
if($this->validate())
{
$contentResult=0;
$result=$this->save();
$result=($result==0)?($contentResult>0?1:0):$result;
$con->commit();
return $result;
}
else
{
$con->rollback();
throw(new Exception("Failed Validation in class ".get_class($this)."."));
}
}
catch(Exception $e)
{
$con->rollback();
throw($e);
}
}
public function remove($CfgUid, $ObjUid, $ProUid, $UsrUid, $AppUid)
{
$con = Propel::getConnection(ConfigurationPeer::DATABASE_NAME);
try
{
$con->begin();
$this->setCfgUid($CfgUid);
$this->setObjUid($ObjUid);
$this->setProUid($ProUid);
$this->setUsrUid($UsrUid);
$this->setAppUid($AppUid);
$result=$this->delete();
$con->commit();
return $result;
}
catch(Exception $e)
{
$con->rollback();
throw($e);
}
}
public function exists($CfgUid, $ObjUid, $ProUid, $UsrUid, $AppUid)
{
$oRow = ConfigurationPeer::retrieveByPK( $CfgUid, $ObjUid, $ProUid, $UsrUid, $AppUid );
return ( get_class ($oRow) == 'Configuration' );
}
} // Configuration

View File

@@ -0,0 +1,46 @@
<?php
/**
* ConfigurationPeer.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.
*
*/
// include base peer class
require_once 'classes/model/om/BaseConfigurationPeer.php';
// include object class
include_once 'classes/model/Configuration.php';
/**
* Skeleton subclass for performing query and update operations on the 'CONFIGURATION' 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 ConfigurationPeer extends BaseConfigurationPeer {
} // ConfigurationPeer

View File

@@ -0,0 +1,299 @@
<?php
/**
* Content.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.
*
*/
require_once 'classes/model/om/BaseContent.php';
/**
* Skeleton subclass for representing a row from the 'CONTENT' 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 Content extends BaseContent {
/*
* Load the content row specified by the parameters:
* @param string $sUID
* @return variant
*/
function load($ConCategory, $ConParent, $ConId, $ConLang) {
$content = ContentPeer::retrieveByPK ( $ConCategory, $ConParent, $ConId, $ConLang );
if (is_null ( $content )) {
//we dont find any value for this field and language in CONTENT table
$ConValue = Content::autoLoadSave ( $ConCategory, $ConParent, $ConId, $ConLang );
} else {
//krumo($content);
$ConValue = $content->getConValue ();
if ($ConValue == "") { //try to find a valid translation
$ConValue = Content::autoLoadSave ( $ConCategory, $ConParent, $ConId, $ConLang );
}
}
return $ConValue;
}
/*
* Find a valid Lang for current Content. The most recent
* @param string $ConCategory
* @param string $ConParent
* @param string $ConId
* @return string
*
*/
function getDefaultContentLang($ConCategory, $ConParent, $ConId, $destConLang) {
$Criteria = new Criteria ( 'workflow' );
$Criteria->clearSelectColumns ()->clearOrderByColumns ();
$Criteria->addSelectColumn ( ContentPeer::CON_CATEGORY );
$Criteria->addSelectColumn ( ContentPeer::CON_PARENT );
$Criteria->addSelectColumn ( ContentPeer::CON_ID );
$Criteria->addSelectColumn ( ContentPeer::CON_LANG );
$Criteria->addSelectColumn ( ContentPeer::CON_VALUE );
$Criteria->add ( ContentPeer::CON_CATEGORY, $ConCategory, CRITERIA::EQUAL );
$Criteria->add ( ContentPeer::CON_PARENT, $ConParent, CRITERIA::EQUAL );
$Criteria->add ( ContentPeer::CON_ID, $ConId, CRITERIA::EQUAL );
$Criteria->add ( ContentPeer::CON_LANG, $destConLang, CRITERIA::NOT_EQUAL );
$rs = ContentPeer::doSelectRS ( $Criteria );
$rs->setFetchmode ( ResultSet::FETCHMODE_ASSOC );
$rs->next ();
if (is_array ( $row = $rs->getRow () )) {
$defaultLang = $row ['CON_LANG'];
} else {
$defaultLang = "";
}
return ($defaultLang);
}
/*
* Load the content row and the Save automatically the row for the destination language
* @param string $ConCategory
* @param string $ConParent
* @param string $ConId
* @param string $destConLang
* @return string
* if the row doesn't exists, it will be created automatically, even the default 'en' language
*/
function autoLoadSave($ConCategory, $ConParent, $ConId, $destConLang) {
//search in 'en' language, the default language
$content = ContentPeer::retrieveByPK ( $ConCategory, $ConParent, $ConId, 'en' );
if ((is_null ( $content )) || ($content->getConValue () == "")) {
$differentLang = Content::getDefaultContentLang ( $ConCategory, $ConParent, $ConId, $destConLang );
$content = ContentPeer::retrieveByPK ( $ConCategory, $ConParent, $ConId, $differentLang );
}
//to do: review if the $destConLang is a valid language/
if (is_null ( $content ))
$ConValue = ''; //we dont find any value for this field and language in CONTENT table
else
$ConValue = $content->getConValue ();
try {
$con = ContentPeer::retrieveByPK ( $ConCategory, $ConParent, $ConId, $destConLang );
if (is_null ( $con )) {
$con = new Content ( );
}
$con->setConCategory ( $ConCategory );
$con->setConParent ( $ConParent );
$con->setConId ( $ConId );
$con->setConLang ( $destConLang );
$con->setConValue ( $ConValue );
if ($con->validate ()) {
$res = $con->save ();
}
} catch ( Exception $e ) {
throw ($e);
}
return $ConValue;
}
/*
* Insert a content row
* @param string $ConCategory
* @param string $ConParent
* @param string $ConId
* @param string $ConLang
* @param string $ConValue
* @return variant
*/
function addContent($ConCategory, $ConParent, $ConId, $ConLang, $ConValue) {
try {
$con = ContentPeer::retrieveByPK ( $ConCategory, $ConParent, $ConId, $ConLang );
if (is_null ( $con )) {
$con = new Content ( );
} else {
if ($con->getConParent () == $ConParent && $con->getConCategory () == $ConCategory && $con->getConValue () == $ConValue && $con->getConLang () == $ConLang && $con->getConId () == $ConId)
return true;
}
$con->setConCategory ( $ConCategory );
if ($con->getConParent () != $ConParent)
$con->setConParent ( $ConParent );
$con->setConId ( $ConId );
$con->setConLang ( $ConLang );
$con->setConValue ( $ConValue );
if ($con->validate ()) {
$res = $con->save ();
return $res;
} else {
$e = new Exception ( "Error in addcontent, the row $ConCategory, $ConParent, $ConId, $ConLang is not Valid" );
throw ($e);
}
} catch ( Exception $e ) {
throw ($e);
}
}
/*
* Insert a content row
* @param string $ConCategory
* @param string $ConParent
* @param string $ConId
* @param string $ConLang
* @param string $ConValue
* @return variant
*/
function insertContent($ConCategory, $ConParent, $ConId, $ConLang, $ConValue) {
try {
$con = new Content ( );
$con->setConCategory ( $ConCategory );
$con->setConParent ( $ConParent );
$con->setConId ( $ConId );
$con->setConLang ( $ConLang );
$con->setConValue ( $ConValue );
if ($con->validate ()) {
$res = $con->save ();
return $res;
} else {
$e = new Exception ( "Error in addcontent, the row $ConCategory, $ConParent, $ConId, $ConLang is not Valid" );
throw ($e);
}
} catch ( Exception $e ) {
throw ($e);
}
}
/*
* remove a content row
* @param string $ConCategory
* @param string $ConParent
* @param string $ConId
* @param string $ConLang
* @param string $ConValue
* @return variant
*/
function removeContent($ConCategory, $ConParent, $ConId) {
try {
$c = new Criteria ( );
$c->add ( ContentPeer::CON_CATEGORY, $ConCategory );
$c->add ( ContentPeer::CON_PARENT, $ConParent );
$c->add ( ContentPeer::CON_ID, $ConId );
$result = ContentPeer::doSelectRS ( $c );
$result->next ();
$row = $result->getRow ();
while ( is_array ( $row ) ) {
ContentPeer::doDelete ( array ($ConCategory, $ConParent, $ConId, $row [3] ) );
$result->next ();
$row = $result->getRow ();
}
} catch ( Exception $e ) {
throw ($e);
}
}
/*
* Reasons if the record already exists
*
* @param string $ConCategory
* @param string $ConParent
* @param string $ConId
* @param string $ConLang
* @param string $ConValue
* @return boolean true or false
*/
function Exists ($ConCategory, $ConParent, $ConId, $ConLang)
{
try {
$oPro = ContentPeer::retrieveByPk($ConCategory, $ConParent, $ConId, $ConLang);
if ( get_class ($oPro) == 'Content' ) {
return true;
} else {
return false;
}
}
catch (Exception $oError) {
throw($oError);
}
}
function regenerateContent($langId)
{
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(ContentPeer::CON_CATEGORY);
$oCriteria->addSelectColumn(ContentPeer::CON_ID);
$oCriteria->addSelectColumn(ContentPeer::CON_VALUE);
$oCriteria->add(ContentPeer::CON_LANG, 'en');
$oCriteria->add(ContentPeer::CON_VALUE, '', Criteria::NOT_EQUAL );
$oDataset = ContentPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$oContent = new Content();
while ($aRow = $oDataset->getRow()) {
$oContent->load($aRow['CON_CATEGORY'], '', $aRow['CON_ID'], $langId);
$oDataset->next();
}
}
function removeLanguageContent($lanId) {
try {
$c = new Criteria ( );
$c->addSelectColumn(ContentPeer::CON_CATEGORY);
$c->addSelectColumn(ContentPeer::CON_PARENT);
$c->addSelectColumn(ContentPeer::CON_ID);
$c->addSelectColumn(ContentPeer::CON_LANG);
$c->add ( ContentPeer::CON_LANG, $lanId );
$result = ContentPeer::doSelectRS ( $c );
$result->next ();
$row = $result->getRow ();
while ( is_array ( $row ) ) {
ContentPeer::doDelete ( array ($row['CON_CATEGORY'], $row['CON_PARENT'], $row['CON_ID'], $lanId ) );
$result->next ();
$row = $result->getRow ();
}
} catch ( Exception $e ) {
throw ($e);
}
}
} // Content

View File

@@ -0,0 +1,46 @@
<?php
/**
* ContentPeer.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.
*
*/
// include base peer class
require_once 'classes/model/om/BaseContentPeer.php';
// include object class
include_once 'classes/model/Content.php';
/**
* Skeleton subclass for performing query and update operations on the 'CONTENT' 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 ContentPeer extends BaseContentPeer {
} // ContentPeer

View File

@@ -0,0 +1,195 @@
<?php
/**
* DbSource.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.
*
*/
require_once 'classes/model/Content.php';
require_once 'classes/model/om/BaseDbSource.php';
/**
* Skeleton subclass for representing a row from the 'DB_SOURCE' 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 DbSource extends BaseDbSource
{
/**
* This value goes in the content table
* @var string
*/
protected $db_source_description = '';
/**
* Get the rep_tab_title column value.
* @return string
*/
public function getDBSourceDescription() {
if ( $this->getDbsUid() == "" ) {
throw ( new Exception( "Error in getDBSourceDescription, the getDbsUid() can't be blank") );
}
$lang = defined ( 'SYS_LANG' ) ? SYS_LANG : 'en';
$this->db_source_description = Content::load ( 'DBS_DESCRIPTION', '', $this->getDbsUid(), $lang );
return $this->db_source_description;
}
function getCriteriaDBSList($sProcessUID)
{
$sDelimiter = DBAdapter::getStringDelimiter();
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(DbSourcePeer::DBS_UID);
$oCriteria->addSelectColumn(DbSourcePeer::PRO_UID);
$oCriteria->addSelectColumn(DbSourcePeer::DBS_TYPE);
$oCriteria->addSelectColumn(DbSourcePeer::DBS_SERVER);
$oCriteria->addSelectColumn(DbSourcePeer::DBS_DATABASE_NAME);
$oCriteria->addSelectColumn(DbSourcePeer::DBS_USERNAME);
$oCriteria->addSelectColumn(DbSourcePeer::DBS_PASSWORD);
$oCriteria->addSelectColumn(DbSourcePeer::DBS_PORT);
$oCriteria->addAsColumn('DBS_DESCRIPTION', 'C.CON_VALUE');
$oCriteria->addAlias('C', 'CONTENT');
$aConditions = array();
$aConditions[] = array(DbSourcePeer::DBS_UID, 'C.CON_ID');
$aConditions[] = array('C.CON_CATEGORY', $sDelimiter . 'DBS_DESCRIPTION' . $sDelimiter);
$aConditions[] = array('C.CON_LANG', $sDelimiter . SYS_LANG . $sDelimiter);
$oCriteria->addJoinMC($aConditions, Criteria::LEFT_JOIN);
$oCriteria->add(DbSourcePeer::PRO_UID, $sProcessUID);
return $oCriteria;
}
public function load($Uid)
{
try {
$oRow = DbSourcePeer::retrieveByPK($Uid);
if (!is_null($oRow)) {
$aFields = $oRow->toArray(BasePeer::TYPE_FIELDNAME);
$this->fromArray($aFields, BasePeer::TYPE_FIELDNAME);
$aFields['DBS_DESCRIPTION'] = $this->getDBSourceDescription();
$this->setNew(false);
return $aFields;
} else {
throw(new Exception( "The row '$Uid' in table DbSource doesn't exist!" ));
}
}
catch (exception $oError) {
throw ($oError);
}
}
function Exists ( $Uid ) {
try {
$oPro = DbSourcePeer::retrieveByPk( $Uid );
if ( get_class ($oPro) == 'DbSource' ) {
return true;
}
else {
return false;
}
}
catch (Exception $oError) {
throw($oError);
}
}
public function update($fields)
{
if( $fields['DBS_ENCODE'] == '0'){
unset($fields['DBS_ENCODE']);
}
$con = Propel::getConnection(DbSourcePeer::DATABASE_NAME);
try {
$con->begin();
$this->load($fields['DBS_UID']);
$this->fromArray($fields, BasePeer::TYPE_FIELDNAME);
if ($this->validate()) {
$result = $this->save();
$con->commit();
return $result;
} else {
$con->rollback();
throw (new Exception("Failed Validation in class " . get_class($this) . "."));
}
}
catch (exception $e) {
$con->rollback();
throw ($e);
}
}
function remove($DbsUid)
{
$con = Propel::getConnection(DbSourcePeer::DATABASE_NAME);
try {
$con->begin();
$this->setDbsUid($DbsUid);
// note added by gustavo cruz gustavo-at-colosa-dot-com
// we assure that the _delete attribute must be set to false
// if a record exists in the database with that uid.
if ($this->Exists($DbsUid)){
$this->setDeleted(false);
}
$result = $this->delete();
$con->commit();
return $result;
}
catch (exception $e) {
$con->rollback();
throw ($e);
}
}
function create($aData)
{
if( $aData['DBS_ENCODE'] == '0'){
unset($aData['DBS_ENCODE']);
}
$con = Propel::getConnection(DbSourcePeer::DATABASE_NAME);
try {
if ( isset ( $aData['DBS_UID'] ) && $aData['DBS_UID']== '' )
unset ( $aData['DBS_UID'] );
if ( !isset ( $aData['DBS_UID'] ) )
$aData['DBS_UID'] = G::generateUniqueID();
$this->fromArray($aData, BasePeer::TYPE_FIELDNAME);
if ($this->validate()) {
$result = $this->save();
} else {
$e = new Exception("Failed Validation in class " . get_class($this) . ".");
$e->aValidationFailures = $this->getValidationFailures();
throw ($e);
}
$con->commit();
return $this->getDbsUid();
}
catch (exception $e) {
$con->rollback();
throw ($e);
}
}
} // DbSource

View File

@@ -0,0 +1,23 @@
<?php
// include base peer class
require_once 'classes/model/om/BaseDbSourcePeer.php';
// include object class
include_once 'classes/model/DbSource.php';
/**
* Skeleton subclass for performing query and update operations on the 'DB_SOURCE' 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 DbSourcePeer extends BaseDbSourcePeer {
} // DbSourcePeer

View File

@@ -0,0 +1,558 @@
<?php
/**
* Department.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.
*
*/
require_once 'classes/model/om/BaseDepartment.php';
require_once 'classes/model/Users.php';
/**
* Skeleton subclass for representing a row from the 'DEPARTMENT' 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 Department extends BaseDepartment {
protected $depo_title = '';
/**
* Create the Department
*
* @param array $aData
* @return void
*/
function create ($aData ) {
$con = Propel::getConnection( DepartmentPeer::DATABASE_NAME );
try {
if ( isset ( $aData['DEP_UID'] ) )
$this->setDepUid ( $aData['DEP_UID'] );
else
$this->setDepUid ( G::generateUniqueID() );
if ( isset ( $aData['DEP_PARENT'] ) )
$this->setDepParent ( $aData['DEP_PARENT'] );
else
$this->setDepParent ( '' );
if ( isset ( $aData['DEP_MANAGER'] ) )
$this->setDepManager ( $aData['DEP_MANAGER'] );
else
$this->setDepManager ( '' );
if ( isset ( $aData['DEP_LOCATION'] ) )
$this->setDepLocation ( $aData['DEP_LOCATION'] );
else
$this->setDepLocation ( '' );
if ( isset ( $aData['DEP_STATUS'] ) )
$this->setDepStatus ( $aData['DEP_STATUS'] );
else
$this->setDepStatus ( 'ACTIVE' );
if ( isset ( $aData['DEP_REF_CODE'] ) )
$this->setDepRefCode ( $aData['DEP_REF_CODE'] );
else
$this->setDepRefCode ( '' );
if ( isset ( $aData['DEP_LDAP_DN'] ) )
$this->setDepLdapDn ( $aData['DEP_LDAP_DN'] );
else
$this->setDepLdapDn ( '' );
if ( isset ( $aData['DEP_TITLE'] ) )
$this->setDepTitle ( $aData['DEP_TITLE'] );
else
$this->setDepTitle ( '' );
if ( $this->validate() ) {
$con->begin();
$res = $this->save();
$con->commit();
return $this->getDepUid();
}
else {
$msg = '';
foreach($this->getValidationFailures() as $objValidationFailure)
$msg .= $objValidationFailure->getMessage() . "<br/>";
throw ( new Exception ( " The Department row cannot be created $msg " ) );
}
}
catch (Exception $e) {
$con->rollback();
throw ($e);
}
}
/**
* Get the [depo_title] column value.
* @return string
*/
public function getDepTitle()
{
if ( $this->getDepUid() == '' ) {
throw ( new Exception( "Error in getDepTitle, the DEP_UID can't be blank") );
}
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$this->depo_title = Content::load ( 'DEPO_TITLE', '', $this->getDepUid(), $lang );
return $this->depo_title;
}
/**
* Set the [depo_title] column value.
*
* @param string $v new value
* @return void
*/
public function setDepTitle($v)
{
if ( $this->getDepUid() == '' ) {
throw ( new Exception( "Error in setGrpTitle, the GRP_UID can't be blank") );
}
// 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->depo_title !== $v || $v === '') {
$this->depo_title = $v;
$lang = defined ( 'SYS_LANG') ? SYS_LANG : 'en';
$res = Content::addContent( 'DEPO_TITLE', '', $this->getDepUid(), $lang, $this->depo_title );
}
} // set()
/**
* Load the Process row specified in [depo_id] column value.
*
* @param string $ProUid the uid of the Prolication
* @return array $Fields the fields
*/
function Load ( $DepUid ) {
$con = Propel::getConnection(DepartmentPeer::DATABASE_NAME);
try {
$oDept = DepartmentPeer::retrieveByPk( $DepUid );
if ( get_class ($oDept) == 'Department' ) {
$aFields = $oDept->toArray(BasePeer::TYPE_FIELDNAME);
$this->fromArray ($aFields, BasePeer::TYPE_FIELDNAME );
$aFields['DEPO_TITLE'] = $oDept->getDepTitle();
return $aFields;
}
else {
throw(new Exception( "The row '$DepUid' in table Department doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Update the Dep row
* @param array $aData
* @return variant
**/
public function update($aData)
{
$con = Propel::getConnection( DepartmentPeer::DATABASE_NAME );
try {
$con->begin();
$oPro = DepartmentPeer::retrieveByPK( $aData['DEP_UID'] );
if ( get_class ($oPro) == 'Department' ) {
$oPro->fromArray( $aData, BasePeer::TYPE_FIELDNAME );
if ($oPro->validate()) {
if ( isset ( $aData['DEPO_TITLE'] ) )
$oPro->setDepTitle( $aData['DEPO_TITLE'] );
if ( isset ( $aData['DEP_STATUS'] ) )
$oPro->setDepStatus( $aData['DEP_STATUS'] );
if ( isset ( $aData['DEP_PARENT'] ) )
$oPro->setDepParent( $aData['DEP_PARENT'] );
if ( isset ( $aData['DEP_MANAGER'] ) )
$oPro->setDepManager( $aData['DEP_MANAGER'] );
$res = $oPro->save();
$con->commit();
return $res;
}
else {
$msg = '';
foreach($this->getValidationFailures() as $objValidationFailure)
$msg .= $objValidationFailure->getMessage() . "<br/>";
throw ( new PropelException ( 'The Department row cannot be created!', new PropelException ( $msg ) ) );
}
}
else {
$con->rollback();
throw(new Exception( "The row '" . $aData['DEP_UID'] . "' in table Department doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Remove the row
* @param array $aData or string $ProUid
* @return string
**/
public function remove($ProUid)
{
if ( is_array ( $ProUid ) ) {
$ProUid = ( isset ( $ProUid['DEP_UID'] ) ? $ProUid['DEP_UID'] : '' );
}
try {
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(UsersPeer::USR_UID);
$oCriteria->add(UsersPeer::DEP_UID, $ProUid, Criteria::EQUAL);
$oDataset = UsersPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
$aFields = array();
while ($aRow = $oDataset->getRow()) {
$aFields['USR_UID'] = $aRow['USR_UID'];
$aFields['DEP_UID'] = '';
$oDepto = UsersPeer::retrieveByPk($aFields['USR_UID']);
if (get_class($oDepto) == 'UsersPeer') {
return true;
} else {
$oDepto = new Users();
$oDepto->update($aFields);
}
$oDataset->next();
}
$oPro = DepartmentPeer::retrieveByPK( $ProUid );
if (!is_null($oPro))
{
Content::removeContent('DEPO_TITLE', '', $oPro->getDepUid());
Content::removeContent('DEPO_DESCRIPTION', '', $oPro->getDepUid());
return $oPro->delete();
}
else {
throw(new Exception( "The row '$ProUid' in table Group doesn't exist!" ));
}
}
catch (Exception $oError) {
throw($oError);
}
}
/**
* Load the Department row specified in [depo_id] column value.
*
* @param string $ProUid the uid of the Prolication
* @return array $Fields the fields
*/
function existsDepartment( $DepUid ) {
$con = Propel::getConnection(DepartmentPeer::DATABASE_NAME);
$oPro = DepartmentPeer::retrieveByPk( $DepUid );
if ( get_class ($oPro) == 'Department' ) {
return true;
}
else {
return false;
}
}
function existsUserInDepartment( $depId, $userId ) {
$con = Propel::getConnection(DepartmentPeer::DATABASE_NAME);
$oUser = UsersPeer::retrieveByPk( $userId );
if ( get_class ($oUser) == 'Users' ) {
if ( $oUser->getDepUid() == $depId )
return true;
}
return false;
}
function updateDepartmentManager ($depId) {
$managerId = '';
$depParent = '';
$oDept = DepartmentPeer::retrieveByPk( $depId );
if ( get_class ($oDept) == 'Department' ) {
$managerId = $oDept->getDepManager( );
$depParent = $oDept->getDepParent( );
}
// update the reportsTo field to all users in that department
$conn = Propel::getConnection(UsersPeer::DATABASE_NAME);
$selectCriteria = new Criteria('workflow');
$selectCriteria->add(UsersPeer::DEP_UID, $depId );
$selectCriteria->add(UsersPeer::USR_UID, $managerId , Criteria::NOT_EQUAL);
// Create a Criteria object includes the value you want to set
$updateCriteria = new Criteria('workflow');
$updateCriteria->add(UsersPeer::USR_REPORTS_TO, $managerId );
BasePeer::doUpdate($selectCriteria, $updateCriteria, $conn);
// update manager's manager, getting the manager of PARENT DEPARTMENT in order to enable scalating
$oUser = UsersPeer::retrieveByPk( $managerId );
if ( get_class ($oUser) == 'Users' ) {
$oDept = DepartmentPeer::retrieveByPk( $depParent );
$oUser->setUsrReportsTo( '' ); //by default no manager
if ( get_class ($oDept) == 'Department' ) {
$managerParentId = $oDept->getDepManager( );
if ( trim($managerParentId) != '' ) {
$oUser->setUsrReportsTo( $managerParentId );
}
}
$oUser->save();
}
// get children departments to update the reportsTo of these children
$childrenCriteria = new Criteria('workflow');
$childrenCriteria->add(DepartmentPeer::DEP_PARENT, $depId );
$oDataset = DepartmentPeer::doSelectRS($childrenCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ( $aRow = $oDataset->getRow() ) {
$oUser = UsersPeer::retrieveByPk($aRow['DEP_MANAGER']);
if (get_class($oUser) == 'Users') {
$oUser->setUsrReportsTo ( $managerId );
$oUser->save();
}
$oDataset->next();
}
}
//add an user to a department and sync all about manager info
function addUserToDepartment( $depId, $userId, $manager, $updateManager = false ) {
try {
//update the field in user table
$oUser = UsersPeer::retrieveByPk( $userId );
if ( get_class ($oUser) == 'Users' ) {
$oUser->setDepUid( $depId );
$oUser->save();
}
//if the user is a manager update Department Table
if ( $manager ) {
$oDept = DepartmentPeer::retrieveByPk( $depId );
if ( get_class ($oDept) == 'Department' ) {
$oDept->setDepManager( $userId );
$oDept->save();
}
}
//now update the reportsto to all
if ( $updateManager ) {
$this->updateDepartmentManager ($depId);
}
return true;
}
catch ( Exception $oError) {
throw($oError);
}
}
// select departments
// this function is used to draw the hierachy tree view
function getDepartments( $DepParent ) {
try {
$result = array();
$criteria = new Criteria('workflow');
$criteria->add(DepartmentPeer::DEP_PARENT, $DepParent, Criteria::EQUAL);
$con = Propel::getConnection(DepartmentPeer::DATABASE_NAME);
$objects = DepartmentPeer::doSelect($criteria, $con);
foreach( $objects as $oDepartment ) {
$node = array();
$node['DEP_UID'] = $oDepartment->getDepUid();
$node['DEP_PARENT'] = $oDepartment->getDepParent();
$node['DEP_TITLE'] = $oDepartment->getDepTitle();
$node['DEP_LAST'] = 0;
$criteriaCount = new Criteria('workflow');
$criteriaCount->clearSelectColumns();
$criteriaCount->addSelectColumn( 'COUNT(*)' );
$criteriaCount->add(DepartmentPeer::DEP_PARENT, $oDepartment->getDepUid(), Criteria::EQUAL);
$rs = DepartmentPeer::doSelectRS($criteriaCount);
$rs->next();
$row = $rs->getRow();
$node['HAS_CHILDREN'] = $row[0];
$result[] = $node;
}
if ( count($result) >= 1 )
$result[ count($result) -1 ]['DEP_LAST'] = 1;
return $result;
}
catch (exception $e) {
throw $e;
}
}
function getUsersFromDepartment( $sDepUid, $sManagerUid ) {
try {
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(UsersPeer::USR_UID);
$oCriteria->addSelectColumn(UsersPeer::USR_REPORTS_TO);
$oCriteria->add(UsersPeer::USR_STATUS, 'CLOSED', Criteria::NOT_EQUAL);
$oCriteria->add(UsersPeer::DEP_UID, $sDepUid);
$rs = UsersPeer::doSelectRS($oCriteria);
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oUser = new Users();
$aUsers[] = array('USR_UID' =>'char', 'USR_USERNAME' =>'char','USR_FULLNAME' =>'char', 'USR_REPORTS_TO'=>'char','USR_MANAGER' =>'char');
$rs->next();
$row = $rs->getRow();
while( is_array($row) ) {
$usrFields = $oUser->LoadDetails( $row['USR_UID'] );
$row['USR_USERNAME'] = $usrFields['USR_USERNAME'];
$row['USR_FULLNAME'] = $usrFields['USR_FULLNAME'];
$row['USR_MANAGER'] = $row['USR_UID'] == $sManagerUid ? G::loadTranslation("ID_YES") : G::loadTranslation("ID_NO");
$row['DEP_UID'] = $sDepUid;
if ( $row['USR_REPORTS_TO'] != '' ) {
try {
$managerFields = $oUser->LoadDetails( $row['USR_REPORTS_TO'] );
$row['USR_REPORTS_NAME'] = $managerFields['USR_FULLNAME'];
}
catch (exception $e) {
$row['USR_REPORTS_NAME'] = '.';
}
}
else
$row['USR_REPORTS_NAME'] = '.';
$aUsers[] = $row;
$rs->next();
$row = $rs->getRow();
}
G::LoadClass('ArrayPeer');
global $_DBArray;
$_DBArray['DepartmentUserList'] = $aUsers ;
$_SESSION['_DBArray'] = $_DBArray;
$oCriteriaT = new Criteria('dbarray');
$oCriteriaT->setDBArrayTable('DepartmentUserList');
return $oCriteriaT;
}
catch (exception $e) {
throw $e;
}
}
/*
* Remove a user from Departments
* @param string $DepUid, $UsrUid
* @return array
*/
function removeUserFromDepartment($DepUid, $UsrUid) {
$aFields = array ('USR_UID'=> $UsrUid,'DEP_UID'=> '', 'USR_REPORTS_TO' => '');
try {
$oUser = UsersPeer::retrieveByPk( $UsrUid );
if ( get_class($oUser) == 'Users' ) {
//$oDepto = new Users();
$oUser->setDepUid ( '');
$oUser->setUsrReportsTo ( '');
$oUser->save();
}
}
catch (exception $oError) {
throw ($oError);
}
}
/*
* Return the available users list criteria object
* @param string $sGroupUID
* @return object
*/
function getAvailableUsersCriteria($sGroupUID = '')
{
try {
$oCriteria = new Criteria('workflow');
$oCriteria->addSelectColumn(UsersPeer::USR_UID);
$oCriteria->addSelectColumn(UsersPeer::USR_FIRSTNAME);
$oCriteria->addSelectColumn(UsersPeer::USR_LASTNAME);
$oCriteria->add(UsersPeer::DEP_UID, "", Criteria::EQUAL);
$oCriteria->add(UsersPeer::USR_STATUS, 'ACTIVE');
return $oCriteria;
}
catch (exception $oError) {
throw ($oError);
}
}
/*
* Return the cant Users In Department
* @param string $sDepUID
* @return object
*/
function cantUsersInDepartment ( $sDepUID ) {
try {
$c = new Criteria('workflow');
$c->addSelectColumn('COUNT(*)');
$c->add(UsersPeer::USR_STATUS, 'CLOSED', Criteria::NOT_EQUAL);
$c->add(UsersPeer::DEP_UID, $sDepUID);
$rs = UsersPeer::doSelectRS($c);
$rs->next();
$row = $rs->getRow();
$count = $row[0];
return $count;
}
catch (exception $oError) {
throw ($oError);
}
}
function loadByGroupname ( $Groupname ) {
$c = new Criteria('workflow');
$del = DBAdapter::getStringDelimiter();
$c->clearSelectColumns();
$c->addSelectColumn( ContentPeer::CON_CATEGORY );
$c->addSelectColumn( ContentPeer::CON_VALUE );
$c->add(ContentPeer::CON_CATEGORY, 'DEPO_TITLE');
$c->add(ContentPeer::CON_VALUE, $Groupname);
$c->add(ContentPeer::CON_LANG, SYS_LANG );
return $c;
}
} // Department

Some files were not shown because too many files have changed in this diff Show More