From 3a3c09dabdb5846a08f5dd335cadd6be82d8eee1 Mon Sep 17 00:00:00 2001 From: Hector Cortez Date: Thu, 14 Mar 2013 15:50:49 -0400 Subject: [PATCH] BUG 0000 Adjustment for the standardization of code. CODE_STYLE --- .../engine/classes/class.javaBridgePM.php | 32 +- workflow/engine/classes/class.wsTools.php | 772 +++++++++--------- .../classes/triggers/api/class.zimbraApi.php | 482 +++++------ .../classes/triggers/class.pmTrSharepoint.php | 255 +++--- .../engine/methods/processes/clases_Test.php | 200 +++-- .../methods/tools/methodsPermissions.php | 6 +- .../templates/tools/methodsPermissions.php | 234 +++--- 7 files changed, 960 insertions(+), 1021 deletions(-) diff --git a/workflow/engine/classes/class.javaBridgePM.php b/workflow/engine/classes/class.javaBridgePM.php index 3840809e3..11c6f95b7 100755 --- a/workflow/engine/classes/class.javaBridgePM.php +++ b/workflow/engine/classes/class.javaBridgePM.php @@ -24,12 +24,15 @@ * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ -if (! defined( 'JAVA_BRIDGE_PATH' )) +if (! defined( 'JAVA_BRIDGE_PATH' )) { define( 'JAVA_BRIDGE_PATH', 'JavaBridgePM' ); -if (! defined( 'JAVA_BRIDGE_PORT' )) +} +if (! defined( 'JAVA_BRIDGE_PORT' )) { define( 'JAVA_BRIDGE_PORT', '8080' ); -if (! defined( 'JAVA_BRIDGE_HOST' )) +} +if (! defined( 'JAVA_BRIDGE_HOST' )) { define( 'JAVA_BRIDGE_HOST', '127.0.0.1' ); +} /** * @@ -37,9 +40,9 @@ if (! defined( 'JAVA_BRIDGE_HOST' )) */ class JavaBridgePM { - var $JavaBridgeDir = JAVA_BRIDGE_PATH; - var $JavaBridgePort = JAVA_BRIDGE_PORT; - var $JavaBridgeHost = JAVA_BRIDGE_HOST; + public $JavaBridgeDir = JAVA_BRIDGE_PATH; + public $JavaBridgePort = JAVA_BRIDGE_PORT; + public $JavaBridgeHost = JAVA_BRIDGE_HOST; /** * checkJavaExtension @@ -48,7 +51,7 @@ class JavaBridgePM * * @return true or false */ - function checkJavaExtension () + public function checkJavaExtension () { try { if (! extension_loaded( 'java' )) { @@ -58,8 +61,9 @@ class JavaBridgePM $includedFiles = get_included_files(); $found = false; foreach ($includedFiles as $filename) { - if ($urlJavaInc == $filename) + if ($urlJavaInc == $filename) { $found = true; + } } if (! $found) { throw new Exception( 'The PHP/Java Bridge is not defined' ); @@ -86,7 +90,7 @@ class JavaBridgePM * @param string $className * @return s boolean success */ - function convertValue ($value, $className) + public function convertValue ($value, $className) { // if we are a string, just use the normal conversion // methods from the java extension... @@ -94,10 +98,10 @@ class JavaBridgePM 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') { + } elseif ($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') { + } elseif ($className == 'java.sql.Timestamp' || $className == 'java.sql.Time') { $temp = new Java( $className ); $javaObject = $temp->valueOf( $value ); return $javaObject; @@ -119,7 +123,7 @@ class JavaBridgePM * @param object $template * @return void */ - function generateJrxmlFromDynaform ($outDocUid, $dynaformUid, $template) + public function generateJrxmlFromDynaform ($outDocUid, $dynaformUid, $template) { require_once 'classes/model/Dynaform.php'; $dyn = new Dynaform(); @@ -129,8 +133,9 @@ class JavaBridgePM $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') + if ($val->type == 'submit' || $val->type == 'button' || $val->type == 'title' || $val->type == 'subtitle') { unset( $xmlFields[$key] ); + } } //$sqlSentence = 'SELECT * from ' . $tableName; @@ -168,6 +173,5 @@ class JavaBridgePM $iSize = file_put_contents( $reportFilename, $content ); printf( "saved %s bytes in file %s \n", $iSize, $reportFilename ); } - } diff --git a/workflow/engine/classes/class.wsTools.php b/workflow/engine/classes/class.wsTools.php index 3822f6f37..71bfd8e22 100755 --- a/workflow/engine/classes/class.wsTools.php +++ b/workflow/engine/classes/class.wsTools.php @@ -1,30 +1,29 @@ .*?)' *, *\n* *')(?P.*?)(' *\) *;.*)/"; - var $initPropel = false; - var $initPropelRoot = false; + public $name = null; + public $path = null; + public $db = null; + public $dbPath = null; + public $dbInfo = null; + public $dbInfoRegExp = "/( *define *\( *'(?P.*?)' *, *\n* *')(?P.*?)(' *\) *;.*)/"; + public $initPropel = false; + public $initPropelRoot = false; /** * Create a workspace tools object. @@ -36,7 +35,7 @@ class workspaceTools * @access public * @param string $workspaceName name of the workspace */ - function __construct ($workspaceName) + public function __construct($workspaceName) { $this->name = $workspaceName; $this->path = PATH_DB . $this->name; @@ -51,9 +50,9 @@ class workspaceTools * * @return bool */ - public function workspaceExists () + public function workspaceExists() { - return (file_exists( $this->path ) && file_exists( $this->dbPath )); + return (file_exists($this->path) && file_exists($this->dbPath)); } /** @@ -61,35 +60,35 @@ class workspaceTools * * @param bool $first true if this is the first workspace to be upgrade */ - public function upgrade ($first = false, $buildCacheView = false, $workSpace = SYS_SYS) + public function upgrade($first = false, $buildCacheView = false, $workSpace = SYS_SYS) { - $start = microtime( true ); - CLI::logging( "> Updating database...\n" ); + $start = microtime(true); + CLI::logging("> Updating database...\n"); $this->upgradeDatabase(); - $stop = microtime( true ); + $stop = microtime(true); $final = $stop - $start; - CLI::logging( "<*> Process Updating database carried out in $final seconds.\n" ); + CLI::logging("<*> Process Updating database carried out in $final seconds.\n"); - $start = microtime( true ); - CLI::logging( "> Updating translations...\n" ); - $this->upgradeTranslation( $first ); - $stop = microtime( true ); + $start = microtime(true); + CLI::logging("> Updating translations...\n"); + $this->upgradeTranslation($first); + $stop = microtime(true); $final = $stop - $start; - CLI::logging( "<*> Process Updating translations carried out in $final seconds.\n" ); + CLI::logging("<*> Process Updating translations carried out in $final seconds.\n"); - $start = microtime( true ); - CLI::logging( "> Updating Content...\n" ); - $this->upgradeContent( $workSpace ); - $stop = microtime( true ); + $start = microtime(true); + CLI::logging("> Updating Content...\n"); + $this->upgradeContent($workSpace); + $stop = microtime(true); $final = $stop - $start; - CLI::logging( "<*> Process Updating Content carried out in $final seconds.\n" ); + CLI::logging("<*> Process Updating Content carried out in $final seconds.\n"); - $start = microtime( true ); - CLI::logging( "> Updating cache view...\n" ); - $this->upgradeCacheView( $buildCacheView, true); - $stop = microtime( true ); + $start = microtime(true); + CLI::logging("> Updating cache view...\n"); + $this->upgradeCacheView($buildCacheView, true); + $stop = microtime(true); $final = $stop - $start; - CLI::logging( "<*> Process Updating cache view carried out in $final seconds.\n" ); + CLI::logging("<*> Process Updating cache view carried out in $final seconds.\n"); } /** @@ -97,22 +96,22 @@ class workspaceTools * * @return array with database information */ - public function getDBInfo () + public function getDBInfo() { - if (! $this->workspaceExists()) { - throw new Exception( "Could not get db.php in workspace " . $this->name ); + if (!$this->workspaceExists()) { + throw new Exception("Could not get db.php in workspace " . $this->name); } - if (isset( $this->dbInfo )) { + if (isset($this->dbInfo)) { return $this->dbInfo; } - $sDbFile = file_get_contents( $this->dbPath ); + $sDbFile = file_get_contents($this->dbPath); /* This regular expression will match any "define ('', '');" * with any combination of whitespace between words. * Each match will have these groups: * ((define('()2', ')1 ()3 (');)4 )0 */ - preg_match_all( $this->dbInfoRegExp, $sDbFile, $matches, PREG_SET_ORDER ); - $values = array (); + preg_match_all($this->dbInfoRegExp, $sDbFile, $matches, PREG_SET_ORDER); + $values = array(); foreach ($matches as $match) { $values[$match['key']] = $match['value']; } @@ -124,22 +123,20 @@ class workspaceTools return $this->dbInfo = $values; } - private function resetDBInfoCallback ($matches) + private function resetDBInfoCallback($matches) { /* This function changes the values of defines while keeping their formatting * intact. * $matches will contain several groups: * ((define('()2', ')1 ()3 (');)4 )0 */ - $dbPrefix = array ('DB_NAME' => 'wf_','DB_USER' => 'wf_','DB_RBAC_NAME' => 'rb_','DB_RBAC_USER' => 'rb_','DB_REPORT_NAME' => 'rp_','DB_REPORT_USER' => 'rp_' - ); + $dbPrefix = array('DB_NAME' => 'wf_', 'DB_USER' => 'wf_', 'DB_RBAC_NAME' => 'rb_', 'DB_RBAC_USER' => 'rb_', 'DB_REPORT_NAME' => 'rp_', 'DB_REPORT_USER' => 'rp_'); $key = $matches['key']; $value = $matches['value']; - if (array_search( $key, array ('DB_HOST','DB_RBAC_HOST','DB_REPORT_HOST' - ) ) !== false) { + if (array_search($key, array('DB_HOST', 'DB_RBAC_HOST', 'DB_REPORT_HOST')) !== false) { /* Change the database hostname for these keys */ $value = $this->newHost; - } elseif (array_key_exists( $key, $dbPrefix )) { + } elseif (array_key_exists($key, $dbPrefix)) { if ($this->resetDBNames) { /* Change the database name to the new workspace, following the standard * of prefix (either wf_, rp_, rb_) and the workspace name. @@ -167,37 +164,36 @@ class workspaceTools * @param bool $resetDBNames if true, also reset all database names * @return array contains the new database names as values */ - public function resetDBInfo ($newHost, $resetDBNames = true) + public function resetDBInfo($newHost, $resetDBNames = true) { - if (count( explode( ":", $newHost ) ) < 2) { + if (count(explode(":", $newHost)) < 2) { $newHost .= ':3306'; } $this->newHost = $newHost; $this->resetDBNames = $resetDBNames; - $this->resetDBDiff = array (); + $this->resetDBDiff = array(); - if (! $this->workspaceExists()) { - throw new Exception( "Could not find db.php in the workspace" ); + if (!$this->workspaceExists()) { + throw new Exception("Could not find db.php in the workspace"); } - $sDbFile = file_get_contents( $this->dbPath ); + $sDbFile = file_get_contents($this->dbPath); if ($sDbFile === false) { - throw new Exception( "Could not read database information from db.php" ); + throw new Exception("Could not read database information from db.php"); } - /* Match all defines in the config file. Check updateDBCallback to know what - * keys are changed and what groups are matched. - * This regular expression will match any "define ('', '');" - * with any combination of whitespace between words. - */ - $sNewDbFile = preg_replace_callback( "/( *define *\( *'(?P.*?)' *, *\n* *')(?P.*?)(' *\) *;.*)/", array (&$this,'resetDBInfoCallback' - ), $sDbFile ); - if (file_put_contents( $this->dbPath, $sNewDbFile ) === false) { - throw new Exception( "Could not write database information to db.php" ); + /* Match all defines in the config file. Check updateDBCallback to know what + * keys are changed and what groups are matched. + * This regular expression will match any "define ('', '');" + * with any combination of whitespace between words. + */ + $sNewDbFile = preg_replace_callback("/( *define *\( *'(?P.*?)' *, *\n* *')(?P.*?)(' *\) *;.*)/", array(&$this, 'resetDBInfoCallback'), $sDbFile); + if (file_put_contents($this->dbPath, $sNewDbFile) === false) { + throw new Exception("Could not write database information to db.php"); } $newDBNames = $this->resetDBDiff; - unset( $this->resetDBDiff ); - unset( $this->resetDBNames ); + unset($this->resetDBDiff); + unset($this->resetDBNames); //Clear the cached information about db.php - unset( $this->dbInfo ); + unset($this->dbInfo); return $newDBNames; } @@ -207,14 +203,12 @@ class workspaceTools * @param string $dbName a db name, such as wf, rp and rb * @return array with all the database information. */ - public function getDBCredentials ($dbName) + public function getDBCredentials($dbName) { - $prefixes = array ("wf" => "","rp" => "REPORT_","rb" => "RBAC_" - ); + $prefixes = array("wf" => "", "rp" => "REPORT_", "rb" => "RBAC_"); $prefix = $prefixes[$dbName]; $dbInfo = $this->getDBInfo(); - return array ('adapter' => $dbInfo["DB_ADAPTER"],'name' => $dbInfo["DB_" . $prefix . "NAME"],'host' => $dbInfo["DB_" . $prefix . "HOST"],'user' => $dbInfo["DB_" . $prefix . "USER"],'pass' => $dbInfo["DB_" . $prefix . "PASS"],'dsn' => sprintf( "%s://%s:%s@%s/%s?encoding=utf8", $dbInfo['DB_ADAPTER'], $dbInfo["DB_" . $prefix . "USER"], $dbInfo["DB_" . $prefix . "PASS"], $dbInfo["DB_" . $prefix . "HOST"], $dbInfo["DB_" . $prefix . "NAME"] ) - ); + return array('adapter' => $dbInfo["DB_ADAPTER"], 'name' => $dbInfo["DB_" . $prefix . "NAME"], 'host' => $dbInfo["DB_" . $prefix . "HOST"], 'user' => $dbInfo["DB_" . $prefix . "USER"], 'pass' => $dbInfo["DB_" . $prefix . "PASS"], 'dsn' => sprintf("%s://%s:%s@%s/%s?encoding=utf8", $dbInfo['DB_ADAPTER'], $dbInfo["DB_" . $prefix . "USER"], $dbInfo["DB_" . $prefix . "PASS"], $dbInfo["DB_" . $prefix . "HOST"], $dbInfo["DB_" . $prefix . "NAME"])); } /** @@ -223,24 +217,24 @@ class workspaceTools * @param bool $root wheter to also initialize a root connection * @return the Propel connection */ - public function initPropel ($root = false) + public function initPropel($root = false) { - if (($this->initPropel && ! $root) || ($this->initPropelRoot && $root)) { + if (($this->initPropel && !$root) || ($this->initPropelRoot && $root)) { return; } - $wfDetails = $this->getDBCredentials( "wf" ); - $rbDetails = $this->getDBCredentials( "rb" ); - $rpDetails = $this->getDBCredentials( "rp" ); + $wfDetails = $this->getDBCredentials("wf"); + $rbDetails = $this->getDBCredentials("rb"); + $rpDetails = $this->getDBCredentials("rp"); - $config = array ('datasources' => array ('workflow' => array ('connection' => $wfDetails["dsn"],'adapter' => $wfDetails["adapter"] - ),'rbac' => array ('connection' => $rbDetails["dsn"],'adapter' => $rbDetails["adapter"] - ),'rp' => array ('connection' => $rpDetails["dsn"],'adapter' => $rpDetails["adapter"] - ) - ) + $config = array('datasources' => array('workflow' => array('connection' => $wfDetails["dsn"], 'adapter' => $wfDetails["adapter"] + ), 'rbac' => array('connection' => $rbDetails["dsn"], 'adapter' => $rbDetails["adapter"] + ), 'rp' => array('connection' => $rpDetails["dsn"], 'adapter' => $rpDetails["adapter"] + ) + ) ); if ($root) { - $dbHash = @explode( SYSTEM_HASH, G::decrypt( HASH_INSTALLATION, SYSTEM_HASH ) ); + $dbHash = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); $dbInfo = $this->getDBInfo(); $host = $dbHash[0]; @@ -248,12 +242,11 @@ class workspaceTools $pass = $dbHash[2]; $dbName = $dbInfo["DB_NAME"]; - $rootConfig = array ('datasources' => array ('root' => array ('connection' => "mysql://$user:$pass@$host/$dbName?encoding=utf8",'adapter' => "mysql" - ) - ) + $rootConfig = array( + 'datasources' => array('root' => array('connection' => "mysql://$user:$pass@$host/$dbName?encoding=utf8", 'adapter' => "mysql")) ); - $config["datasources"] = array_merge( $config["datasources"], $rootConfig["datasources"] ); + $config["datasources"] = array_merge($config["datasources"], $rootConfig["datasources"]); $this->initPropelRoot = true; } @@ -263,13 +256,13 @@ class workspaceTools require_once ("propel/Propel.php"); require_once ("creole/Creole.php"); - Propel::initConfiguration( $config ); + Propel::initConfiguration($config); } /** * Close the propel connection from initPropel */ - private function closePropel () + private function closePropel() { Propel::close(); $this->initPropel = false; @@ -279,19 +272,19 @@ class workspaceTools /** * Upgrade this workspace Content. */ - public function upgradeContent ($workSpace = SYS_SYS) + public function upgradeContent($workSpace = SYS_SYS) { - $this->initPropel( true ); + $this->initPropel(true); //require_once 'classes/model/Translation.php'; $translation = new Translation(); $information = $translation->getTranslationEnvironments(); - $arrayLang = array (); + $arrayLang = array(); foreach ($information as $key => $value) { - $arrayLang[] = trim( $value['LOCALE'] ); + $arrayLang[] = trim($value['LOCALE']); } //require_once ('classes/model/Content.php'); $regenerateContent = new Content(); - $regenerateContent->regenerateContent( $arrayLang, $workSpace ); + $regenerateContent->regenerateContent($arrayLang, $workSpace); } /** @@ -299,24 +292,24 @@ class workspaceTools * * @param bool $first if updating a series of workspace, true if the first */ - public function upgradeTranslation ($first = true) + public function upgradeTranslation($first = true) { - $this->initPropel( true ); + $this->initPropel(true); //require_once ('classes/model/Language.php'); - G::LoadThirdParty( 'pear/json', 'class.json' ); + G::LoadThirdParty('pear/json', 'class.json'); foreach (System::listPoFiles() as $poFile) { - $poName = basename( $poFile ); - $names = explode( ".", basename( $poFile ) ); - $extension = array_pop( $names ); - $langid = array_pop( $names ); - if (strcasecmp( $langid, "en" ) == 0) { - CLI::logging( "Updating database translations with $poName\n" ); - Language::import( $poFile, false, true ); + $poName = basename($poFile); + $names = explode(".", basename($poFile)); + $extension = array_pop($names); + $langid = array_pop($names); + if (strcasecmp($langid, "en") == 0) { + CLI::logging("Updating database translations with $poName\n"); + Language::import($poFile, false, true); } elseif ($first) { - CLI::logging( "Updating XML form translations with $poName\n" ); - Language::import( $poFile, true, false ); - CLI::logging( "Updating database translations with $poName\n" ); - Language::import( $poFile, false, true ); + CLI::logging("Updating XML form translations with $poName\n"); + Language::import($poFile, true, false); + CLI::logging("Updating database translations with $poName\n"); + Language::import($poFile, false, true); } } } @@ -326,16 +319,16 @@ class workspaceTools * * @return database connection */ - private function getDatabase () + private function getDatabase() { - if (isset( $this->db ) && $this->db->isConnected()) { + if (isset($this->db) && $this->db->isConnected()) { return $this->db; } - G::LoadSystem( 'database_' . strtolower( $this->dbAdapter ) ); - $this->db = new database( $this->dbAdapter, $this->dbHost, $this->dbUser, $this->dbPass, $this->dbName ); - if (! $this->db->isConnected()) { - $this->db->logQuery( 'No available connection to database!' ); - throw new Exception( "Could not connect to database" ); + G::LoadSystem('database_' . strtolower($this->dbAdapter)); + $this->db = new database($this->dbAdapter, $this->dbHost, $this->dbUser, $this->dbPass, $this->dbName); + if (!$this->db->isConnected()) { + $this->db->logQuery('No available connection to database!'); + throw new Exception("Could not connect to database"); } return $this->db; } @@ -343,9 +336,9 @@ class workspaceTools /** * Close any database opened with getDatabase */ - private function closeDatabase () + private function closeDatabase() { - if (! isset( $this->db )) { + if (!isset($this->db)) { return; } $this->db->close(); @@ -355,7 +348,7 @@ class workspaceTools /** * Close all currently opened databases */ - public function close () + public function close() { $this->closePropel(); $this->closeDatabase(); @@ -366,31 +359,31 @@ class workspaceTools * * @return array with the database schema */ - public function getSchema () + public function getSchema() { $oDataBase = $this->getDatabase(); - $aOldSchema = array (); + $aOldSchema = array(); try { $oDataBase->iFetchType = MYSQL_NUM; - $oDataset1 = $oDataBase->executeQuery( $oDataBase->generateShowTablesSQL() ); + $oDataset1 = $oDataBase->executeQuery($oDataBase->generateShowTablesSQL()); } catch (Exception $e) { - $oDataBase->logQuery( $e->getmessage() ); + $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] ); + 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 (); + $oDataset2 = $oDataBase->executeQuery($oDataBase->generateDescTableSQL($sTable)); + $aOldSchema[$sTable] = array(); $oDataBase->iFetchType = MYSQL_ASSOC; - while ($aRow2 = $oDataBase->getRegistry( $oDataset2 )) { + 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']; @@ -398,14 +391,14 @@ class workspaceTools } //get indexes of each table SHOW INDEX FROM `ADDITIONAL_TABLES`; -- WHERE Key_name <> 'PRIMARY' - $oDataset2 = $oDataBase->executeQuery( $oDataBase->generateTableIndexSQL( $aRow1[0] ) ); + $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 (); + 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 (); + if (!isset($aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']])) { + $aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']] = array(); } $aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']][] = $aRow2['Column_name']; } @@ -413,7 +406,7 @@ class workspaceTools $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) { + if (count($aOldSchema) == 0) { $aOldSchema = null; } return $aOldSchema; @@ -427,38 +420,37 @@ class workspaceTools * @param bool $checkOnly only check if the upgrade is needed if true * @param string $lang not currently used */ - public function upgradeCacheView ($fill = true, $checkOnly = false) + public function upgradeCacheView($fill = true, $checkOnly = false) { - $this->initPropel( true ); + $this->initPropel(true); $lang = "en"; //require_once ('classes/model/AppCacheView.php'); - //check the language, if no info in config about language, the default is 'en' G::LoadClass("configuration"); $oConf = new Configurations(); - $oConf->loadConfig( $x, 'APP_CACHE_VIEW_ENGINE', '', '', '', '' ); + $oConf->loadConfig($x, 'APP_CACHE_VIEW_ENGINE', '', '', '', ''); $appCacheViewEngine = $oConf->aConfig; //setup the appcacheview object, and the path for the sql files $appCache = new AppCacheView(); - $appCache->setPathToAppCacheFiles( PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP ); + $appCache->setPathToAppCacheFiles(PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP); - $userGrants = $appCache->checkGrantsForUser( false ); + $userGrants = $appCache->checkGrantsForUser(false); $currentUser = $userGrants['user']; $currentUserIsSuper = $userGrants['super']; //if user does not have the SUPER privilege we need to use the root user and grant the SUPER priv. to normal user. - if (! $currentUserIsSuper) { - $appCache->checkGrantsForUser( true ); - $appCache->setSuperForUser( $currentUser ); + if (!$currentUserIsSuper) { + $appCache->checkGrantsForUser(true); + $appCache->setSuperForUser($currentUser); $currentUserIsSuper = true; } - CLI::logging( "-> Creating table\n" ); + CLI::logging("-> Creating table\n"); //now check if table APPCACHEVIEW exists, and it have correct number of fields, etc. $res = $appCache->checkAppCacheView(); @@ -466,45 +458,43 @@ class workspaceTools //Update APP_DELEGATION.DEL_LAST_INDEX data $res = $appCache->updateAppDelegationDelLastIndex($lang, $checkOnly); - CLI::logging( "-> Creating triggers\n" ); + CLI::logging("-> Creating triggers\n"); //now check if we have the triggers installed - $triggers = array (); - $triggers[] = $appCache->triggerAppDelegationInsert( $lang, $checkOnly ); - $triggers[] = $appCache->triggerAppDelegationUpdate( $lang, $checkOnly ); - $triggers[] = $appCache->triggerApplicationUpdate( $lang, $checkOnly ); - $triggers[] = $appCache->triggerApplicationDelete( $lang, $checkOnly ); - $triggers[] = $appCache->triggerContentUpdate( $lang, $checkOnly ); + $triggers = array(); + $triggers[] = $appCache->triggerAppDelegationInsert($lang, $checkOnly); + $triggers[] = $appCache->triggerAppDelegationUpdate($lang, $checkOnly); + $triggers[] = $appCache->triggerApplicationUpdate($lang, $checkOnly); + $triggers[] = $appCache->triggerApplicationDelete($lang, $checkOnly); + $triggers[] = $appCache->triggerContentUpdate($lang, $checkOnly); if ($fill) { - CLI::logging( "-> Rebuild Cache View\n" ); + CLI::logging("-> Rebuild Cache View\n"); //build using the method in AppCacheView Class - $res = $appCache->fillAppCacheView( $lang ); + $res = $appCache->fillAppCacheView($lang); //set status in config table - $confParams = Array ('LANG' => $lang,'STATUS' => 'active' - ); + $confParams = Array('LANG' => $lang, 'STATUS' => 'active'); } $oConf->aConfig = $confParams; - $oConf->saveConfig( 'APP_CACHE_VIEW_ENGINE', '', '', '' ); + $oConf->saveConfig('APP_CACHE_VIEW_ENGINE', '', '', ''); // removing casesList configuration records. TODO: removing these lines that resets all the configurations records $oCriteria = new Criteria(); - $oCriteria->add( ConfigurationPeer::CFG_UID, "casesList" ); - $oCriteria->add( ConfigurationPeer::OBJ_UID, array ("todo","draft","sent","unassigned","paused","cancelled" - ), Criteria::NOT_IN ); - ConfigurationPeer::doDelete( $oCriteria ); + $oCriteria->add(ConfigurationPeer::CFG_UID, "casesList"); + $oCriteria->add(ConfigurationPeer::OBJ_UID, array("todo", "draft", "sent", "unassigned", "paused", "cancelled"), Criteria::NOT_IN); + ConfigurationPeer::doDelete($oCriteria); // end of reset } /** * Upgrade this workspace database to the latest plugins schema */ - public function upgradePluginsDatabase () + public function upgradePluginsDatabase() { foreach (System::getPlugins() as $pluginName) { - $pluginSchema = System::getPluginSchema( $pluginName ); + $pluginSchema = System::getPluginSchema($pluginName); if ($pluginSchema !== false) { - CLI::logging( "Updating plugin " . CLI::info( $pluginName ) . "\n" ); - $this->upgradeSchema( $pluginSchema ); + CLI::logging("Updating plugin " . CLI::info($pluginName) . "\n"); + $this->upgradeSchema($pluginSchema); } } } @@ -515,10 +505,10 @@ class workspaceTools * @param bool $checkOnly only check if the upgrade is needed if true * @return array bool upgradeSchema for more information */ - public function upgradeDatabase ($checkOnly = false) + public function upgradeDatabase($checkOnly = false) { $systemSchema = System::getSystemSchema(); - $this->upgradeSchema( $systemSchema ); + $this->upgradeSchema($systemSchema); $this->upgradeData(); return true; } @@ -531,22 +521,22 @@ class workspaceTools * @return array bool the changes if checkOnly is true, else return * true on success */ - public function upgradeSchema ($schema, $checkOnly = false) + public function upgradeSchema($schema, $checkOnly = false) { $dbInfo = $this->getDBInfo(); - if (strcmp( $dbInfo["DB_ADAPTER"], "mysql" ) != 0) { - throw new Exception( "Only MySQL is supported" ); + if (strcmp($dbInfo["DB_ADAPTER"], "mysql") != 0) { + throw new Exception("Only MySQL is supported"); } $workspaceSchema = $this->getSchema(); - $changes = System::compareSchema( $workspaceSchema, $schema ); - $changed = (count( $changes['tablesToAdd'] ) > 0 || count( $changes['tablesToAlter'] ) > 0 || count( $changes['tablesWithNewIndex'] ) > 0 || count( $changes['tablesToAlterIndex'] ) > 0); - if ($checkOnly || (! $changed)) { + $changes = System::compareSchema($workspaceSchema, $schema); + $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 { - CLI::logging( "-> Nothing to change in the data base structure\n" ); + CLI::logging("-> Nothing to change in the data base structure\n"); return $changed; } } @@ -554,106 +544,106 @@ class workspaceTools $oDataBase = $this->getDatabase(); $oDataBase->iFetchType = MYSQL_NUM; - $oDataBase->logQuery( count( $changes ) ); + $oDataBase->logQuery(count($changes)); - if (! empty( $changes['tablesToAdd'] )) { - CLI::logging( "-> " . count( $changes['tablesToAdd'] ) . " tables to add\n" ); + if (!empty($changes['tablesToAdd'])) { + CLI::logging("-> " . count($changes['tablesToAdd']) . " tables to add\n"); } foreach ($changes['tablesToAdd'] as $sTable => $aColumns) { - $oDataBase->executeQuery( $oDataBase->generateCreateTableSQL( $sTable, $aColumns ) ); - if (isset( $changes['tablesToAdd'][$sTable]['INDEXES'] )) { + $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 ) ); + $oDataBase->executeQuery($oDataBase->generateAddKeysSQL($sTable, $indexName, $aIndex)); } } } - if (! empty( $changes['tablesToAlter'] )) { - CLI::logging( "-> " . count( $changes['tablesToAlter'] ) . " tables to alter\n" ); + if (!empty($changes['tablesToAlter'])) { + CLI::logging("-> " . count($changes['tablesToAlter']) . " tables to alter\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 ) ); + $oDataBase->executeQuery($oDataBase->generateDropColumnSQL($sTable, $vData)); break; case 'ADD': - $oDataBase->executeQuery( $oDataBase->generateAddColumnSQL( $sTable, $sColumn, $vData ) ); + $oDataBase->executeQuery($oDataBase->generateAddColumnSQL($sTable, $sColumn, $vData)); break; case 'CHANGE': - $oDataBase->executeQuery( $oDataBase->generateChangeColumnSQL( $sTable, $sColumn, $vData ) ); + $oDataBase->executeQuery($oDataBase->generateChangeColumnSQL($sTable, $sColumn, $vData)); break; } } } } - if (! empty( $changes['tablesWithNewIndex'] )) { - CLI::logging( "-> " . count( $changes['tablesWithNewIndex'] ) . " indexes to add\n" ); + if (!empty($changes['tablesWithNewIndex'])) { + CLI::logging("-> " . count($changes['tablesWithNewIndex']) . " indexes to add\n"); } foreach ($changes['tablesWithNewIndex'] as $sTable => $aIndexes) { foreach ($aIndexes as $sIndexName => $aIndexFields) { - $oDataBase->executeQuery( $oDataBase->generateAddKeysSQL( $sTable, $sIndexName, $aIndexFields ) ); + $oDataBase->executeQuery($oDataBase->generateAddKeysSQL($sTable, $sIndexName, $aIndexFields)); } } - if (! empty( $changes['tablesToAlterIndex'] )) { - CLI::logging( "-> " . count( $changes['tablesToAlterIndex'] ) . " indexes to alter\n" ); + if (!empty($changes['tablesToAlterIndex'])) { + CLI::logging("-> " . count($changes['tablesToAlterIndex']) . " indexes to alter\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->executeQuery($oDataBase->generateDropKeySQL($sTable, $sIndexName)); + $oDataBase->executeQuery($oDataBase->generateAddKeysSQL($sTable, $sIndexName, $aIndexFields)); } } $this->closeDatabase(); return true; } - public function upgradeData () + public function upgradeData() { - if (file_exists( PATH_CORE . 'data' . PATH_SEP . 'check.data' )) { - $checkData = unserialize( file_get_contents( PATH_CORE . 'data' . PATH_SEP . 'check.data' ) ); - if (is_array( $checkData )) { + if (file_exists(PATH_CORE . 'data' . PATH_SEP . 'check.data')) { + $checkData = unserialize(file_get_contents(PATH_CORE . 'data' . PATH_SEP . 'check.data')); + if (is_array($checkData)) { foreach ($checkData as $checkThis) { - $this->updateThisRegistry( $checkThis ); + $this->updateThisRegistry($checkThis); } } } } - public function updateThisRegistry ($data) + public function updateThisRegistry($data) { $dataBase = $this->getDatabase(); $sql = ''; switch ($data['action']) { case 1: - $sql = $dataBase->generateInsertSQL( $data['table'], $data['data'] ); + $sql = $dataBase->generateInsertSQL($data['table'], $data['data']); $message = "-> Row added in {$data['table']}\n"; break; case 2: - $sql = $dataBase->generateUpdateSQL( $data['table'], $data['keys'], $data['data'] ); + $sql = $dataBase->generateUpdateSQL($data['table'], $data['keys'], $data['data']); $message = "-> Row updated in {$data['table']}\n"; break; case 3: - $sql = $dataBase->generateDeleteSQL( $data['table'], $data['keys'], $data['data'] ); + $sql = $dataBase->generateDeleteSQL($data['table'], $data['keys'], $data['data']); $message = "-> Row deleted in {$data['table']}\n"; break; case 4: - $sql = $dataBase->generateSelectSQL( $data['table'], $data['keys'], $data['data'] ); - $dataset = $dataBase->executeQuery( $sql ); - if ($dataBase->getRegistry( $dataset )) { - $sql = $dataBase->generateDeleteSQL( $data['table'], $data['keys'], $data['data'] ); - $dataBase->executeQuery( $sql ); + $sql = $dataBase->generateSelectSQL($data['table'], $data['keys'], $data['data']); + $dataset = $dataBase->executeQuery($sql); + if ($dataBase->getRegistry($dataset)) { + $sql = $dataBase->generateDeleteSQL($data['table'], $data['keys'], $data['data']); + $dataBase->executeQuery($sql); } - $sql = $dataBase->generateInsertSQL( $data['table'], $data['data'] ); + $sql = $dataBase->generateInsertSQL($data['table'], $data['data']); $message = "-> Row updated in {$data['table']}\n"; break; } if ($sql != '') { - $dataBase->executeQuery( $sql ); - CLI::logging( $message ); + $dataBase->executeQuery($sql); + CLI::logging($message); } } @@ -663,12 +653,12 @@ class workspaceTools * @param string $path the directory where to create the sql files * @return array information about this workspace */ - public function getMetadata () + public function getMetadata() { - $Fields = array_merge( System::getSysInfo(), $this->getDBInfo() ); + $Fields = array_merge(System::getSysInfo(), $this->getDBInfo()); $Fields['WORKSPACE_NAME'] = $this->name; - if (isset( $this->dbHost )) { + if (isset($this->dbHost)) { //TODO: This code stopped working with the refactoring //require_once ("propel/Propel.php"); @@ -682,16 +672,16 @@ class workspaceTools //} - G::LoadClass( 'net' ); - $dbNetView = new NET( $this->dbHost ); - $dbNetView->loginDbServer( $this->dbUser, $this->dbPass ); + G::LoadClass('net'); + $dbNetView = new NET($this->dbHost); + $dbNetView->loginDbServer($this->dbUser, $this->dbPass); try { - $sMySQLVersion = $dbNetView->getDbServerVersion( 'mysql' ); + $sMySQLVersion = $dbNetView->getDbServerVersion('mysql'); } catch (Exception $oException) { $sMySQLVersion = 'Unknown'; } - $Fields['DATABASE'] = $dbNetView->dbName( $this->dbAdapter ) . ' (Version ' . $sMySQLVersion . ')'; + $Fields['DATABASE'] = $dbNetView->dbName($this->dbAdapter) . ' (Version ' . $sMySQLVersion . ')'; $Fields['DATABASE_SERVER'] = $this->dbHost; $Fields['DATABASE_NAME'] = $this->dbName; $Fields['AVAILABLE_DB'] = "Not defined"; @@ -709,11 +699,17 @@ class workspaceTools /** * Print the system information gathered from getSysInfo */ - public static function printSysInfo () + public static function printSysInfo() { $fields = System::getSysInfo(); - $info = array ('ProcessMaker Version' => $fields['PM_VERSION'],'System' => $fields['SYSTEM'],'PHP Version' => $fields['PHP'],'Server Address' => $fields['SERVER_ADDR'],'Client IP Address' => $fields['IP'],'Plugins' => (count( $fields['PLUGINS_LIST'] ) > 0) ? $fields['PLUGINS_LIST'][0] : 'None' + $info = array( + 'ProcessMaker Version' => $fields['PM_VERSION'], + 'System' => $fields['SYSTEM'], + 'PHP Version' => $fields['PHP'], + 'Server Address' => $fields['SERVER_ADDR'], + 'Client IP Address' => $fields['IP'], + 'Plugins' => (count($fields['PLUGINS_LIST']) > 0) ? $fields['PLUGINS_LIST'][0] : 'None' ); foreach ($fields['PLUGINS_LIST'] as $k => $v) { @@ -724,16 +720,16 @@ class workspaceTools } foreach ($info as $k => $v) { - if (is_numeric( $k )) { + if (is_numeric($k)) { $k = ""; } - CLI::logging( sprintf( "%20s %s\n", $k, pakeColor::colorize( $v, 'INFO' ) ) ); + CLI::logging(sprintf("%20s %s\n", $k, pakeColor::colorize($v, 'INFO'))); } } - public function printInfo ($fields = null) + public function printInfo($fields = null) { - if (! $fields) { + if (!$fields) { $fields = $this->getMetadata(); } @@ -741,16 +737,16 @@ class workspaceTools $rbDsn = $fields['DB_ADAPTER'] . '://' . $fields['DB_RBAC_USER'] . ':' . $fields['DB_RBAC_PASS'] . '@' . $fields['DB_RBAC_HOST'] . '/' . $fields['DB_RBAC_NAME']; $rpDsn = $fields['DB_ADAPTER'] . '://' . $fields['DB_REPORT_USER'] . ':' . $fields['DB_REPORT_PASS'] . '@' . $fields['DB_REPORT_HOST'] . '/' . $fields['DB_REPORT_NAME']; - $info = array ('Workspace Name' => $fields['WORKSPACE_NAME'], - //'Available Databases' => $fields['AVAILABLE_DB'], - 'Workflow Database' => sprintf( "%s://%s:%s@%s/%s", $fields['DB_ADAPTER'], $fields['DB_USER'], $fields['DB_PASS'], $fields['DB_HOST'], $fields['DB_NAME'] ),'RBAC Database' => sprintf( "%s://%s:%s@%s/%s", $fields['DB_ADAPTER'], $fields['DB_RBAC_USER'], $fields['DB_RBAC_PASS'], $fields['DB_RBAC_HOST'], $fields['DB_RBAC_NAME'] ),'Report Database' => sprintf( "%s://%s:%s@%s/%s", $fields['DB_ADAPTER'], $fields['DB_REPORT_USER'], $fields['DB_REPORT_PASS'], $fields['DB_REPORT_HOST'], $fields['DB_REPORT_NAME'] ),'MySql Version' => $fields['DATABASE'] + $info = array('Workspace Name' => $fields['WORKSPACE_NAME'], + //'Available Databases' => $fields['AVAILABLE_DB'], + 'Workflow Database' => sprintf("%s://%s:%s@%s/%s", $fields['DB_ADAPTER'], $fields['DB_USER'], $fields['DB_PASS'], $fields['DB_HOST'], $fields['DB_NAME']), 'RBAC Database' => sprintf("%s://%s:%s@%s/%s", $fields['DB_ADAPTER'], $fields['DB_RBAC_USER'], $fields['DB_RBAC_PASS'], $fields['DB_RBAC_HOST'], $fields['DB_RBAC_NAME']), 'Report Database' => sprintf("%s://%s:%s@%s/%s", $fields['DB_ADAPTER'], $fields['DB_REPORT_USER'], $fields['DB_REPORT_PASS'], $fields['DB_REPORT_HOST'], $fields['DB_REPORT_NAME']), 'MySql Version' => $fields['DATABASE'] ); foreach ($info as $k => $v) { - if (is_numeric( $k )) { + if (is_numeric($k)) { $k = ""; } - CLI::logging( sprintf( "%20s %s\n", $k, pakeColor::colorize( $v, 'INFO' ) ) ); + CLI::logging(sprintf("%20s %s\n", $k, pakeColor::colorize($v, 'INFO'))); } } @@ -759,14 +755,14 @@ class workspaceTools * * @param bool $printSysInfo include sys info as well or not */ - public function printMetadata ($printSysInfo = true) + public function printMetadata($printSysInfo = true) { if ($printSysInfo) { workspaceTools::printSysInfo(); - CLI::logging( "\n" ); + CLI::logging("\n"); } - workspaceTools::printInfo( $this->getMetadata() ); + workspaceTools::printInfo($this->getMetadata()); } /** @@ -776,20 +772,19 @@ class workspaceTools * * @param string $path the directory where to create the sql files */ - public function exportDatabase ($path) + public function exportDatabase($path) { $dbInfo = $this->getDBInfo(); - $databases = array ("wf","rp","rb" - ); - $dbNames = array (); + $databases = array("wf", "rp", "rb"); + $dbNames = array(); foreach ($databases as $db) { - $dbInfo = $this->getDBCredentials( $db ); - $oDbMaintainer = new DataBaseMaintenance( $dbInfo["host"], $dbInfo["user"], $dbInfo["pass"] ); - CLI::logging( "Saving database {$dbInfo["name"]}\n" ); - $oDbMaintainer->connect( $dbInfo["name"] ); + $dbInfo = $this->getDBCredentials($db); + $oDbMaintainer = new DataBaseMaintenance($dbInfo["host"], $dbInfo["user"], $dbInfo["pass"]); + CLI::logging("Saving database {$dbInfo["name"]}\n"); + $oDbMaintainer->connect($dbInfo["name"]); $oDbMaintainer->lockTables(); - $oDbMaintainer->setTempDir( $path . "/" ); - $oDbMaintainer->backupDataBase( $oDbMaintainer->getTempDir() . $dbInfo["name"] . ".sql" ); + $oDbMaintainer->setTempDir($path . "/"); + $oDbMaintainer->backupDataBase($oDbMaintainer->getTempDir() . $dbInfo["name"] . ".sql"); $oDbMaintainer->unlockTables(); $dbNames[] = $dbInfo; } @@ -799,19 +794,17 @@ class workspaceTools /** * adds files to the backup archive */ - private function addToBackup ($backup, $filename, $pathRoot, $archiveRoot = "") + private function addToBackup($backup, $filename, $pathRoot, $archiveRoot = "") { - if (is_file( $filename )) { - CLI::logging( "-> $filename\n" ); - $backup->addModify( $filename, $archiveRoot, $pathRoot ); + if (is_file($filename)) { + CLI::logging("-> $filename\n"); + $backup->addModify($filename, $archiveRoot, $pathRoot); } else { - CLI::logging( " + $filename\n" ); - $backup->addModify( $filename, $archiveRoot, $pathRoot ); + CLI::logging(" + $filename\n"); + $backup->addModify($filename, $archiveRoot, $pathRoot); //foreach (glob($filename . "/*") as $item) { // $this->addToBackup($backup, $item, $pathRoot, $archiveRoot); //} - - } } @@ -821,16 +814,16 @@ class workspaceTools * @param string $filename the backup filename * @param bool $compress wheter to compress or not */ - static public function createBackup ($filename, $compress = true) + static public function createBackup($filename, $compress = true) { - G::LoadThirdParty( 'pear/Archive', 'Tar' ); - if (! file_exists( dirname( $filename ) )) { - mkdir( dirname( $filename ) ); + G::LoadThirdParty('pear/Archive', 'Tar'); + if (!file_exists(dirname($filename))) { + mkdir(dirname($filename)); } - if (file_exists( $filename )) { - unlink( $filename ); + if (file_exists($filename)) { + unlink($filename); } - $backup = new Archive_Tar( $filename ); + $backup = new Archive_Tar($filename); return $backup; } @@ -844,49 +837,48 @@ class workspaceTools * archive object created by createBackup * @param bool $compress specifies wheter the backup is compressed or not */ - public function backup ($backupFile, $compress = true) + public function backup($backupFile, $compress = true) { /* $filename can be a string, in which case it's used as the filename of * the backup, or it can be a previously created tar, which allows for * multiple workspaces in one backup. */ - if (! $this->workspaceExists()) { - throw new Exception( "Workspace '{$this->name}' not found" ); + if (!$this->workspaceExists()) { + throw new Exception("Workspace '{$this->name}' not found"); } - if (is_string( $backupFile )) { - $backup = $this->createBackup( $backupFile ); + if (is_string($backupFile)) { + $backup = $this->createBackup($backupFile); $filename = $backupFile; } else { $backup = $backupFile; $filename = $backup->_tarname; } - if (! file_exists( PATH_DATA . "upgrade/" )) { - mkdir( PATH_DATA . "upgrade/" ); + if (!file_exists(PATH_DATA . "upgrade/")) { + mkdir(PATH_DATA . "upgrade/"); } - $tempDirectory = PATH_DATA . "upgrade/" . basename( tempnam( __FILE__, '' ) ); - mkdir( $tempDirectory ); + $tempDirectory = PATH_DATA . "upgrade/" . basename(tempnam(__FILE__, '')); + mkdir($tempDirectory); $metadata = $this->getMetadata(); - CLI::logging( "Backing up database...\n" ); - $metadata["databases"] = $this->exportDatabase( $tempDirectory ); - $metadata["directories"] = array ("{$this->name}.files" - ); + CLI::logging("Backing up database...\n"); + $metadata["databases"] = $this->exportDatabase($tempDirectory); + $metadata["directories"] = array("{$this->name}.files"); $metadata["version"] = 1; $metaFilename = "$tempDirectory/{$this->name}.meta"; /* Write metadata to file, but make it prettier before. The metadata is just * a JSON codified array. */ - if (! file_put_contents( $metaFilename, str_replace( array (",","{","}" - ), array (",\n ","{\n ","\n}\n" - ), G::json_encode( $metadata ) ) )) { - throw new Exception( "Could not create backup metadata" ); + if (!file_put_contents($metaFilename, str_replace(array(",", "{", "}" + ), array(",\n ", "{\n ", "\n}\n" + ), G::json_encode($metadata)))) { + throw new Exception("Could not create backup metadata"); } - CLI::logging( "Copying database to backup...\n" ); - $this->addToBackup( $backup, $tempDirectory, $tempDirectory ); - CLI::logging( "Copying files to backup...\n" ); + CLI::logging("Copying database to backup...\n"); + $this->addToBackup($backup, $tempDirectory, $tempDirectory); + CLI::logging("Copying files to backup...\n"); - $this->addToBackup( $backup, $this->path, $this->path, "{$this->name}.files" ); + $this->addToBackup($backup, $this->path, $this->path, "{$this->name}.files"); //Remove leftovers. - G::rm_dir( $tempDirectory ); + G::rm_dir($tempDirectory); } //TODO: Move to class.dbMaintenance.php @@ -903,30 +895,30 @@ class workspaceTools * @param string $hostname the hostname the user will be connecting from * @param string $database the database to grant permissions */ - private function createDBUser ($username, $password, $hostname, $database) + private function createDBUser($username, $password, $hostname, $database) { - mysql_select_db( "mysql" ); - $hostname = array_shift( explode( ":", $hostname ) ); + mysql_select_db("mysql"); + $hostname = array_shift(explode(":", $hostname)); $sqlstmt = "SELECT * FROM user WHERE user = '$username' AND host = '$hostname'"; - $result = mysql_query( $sqlstmt ); + $result = mysql_query($sqlstmt); if ($result === false) { - throw new Exception( "Unable to retrieve users: " . mysql_error() ); + throw new Exception("Unable to retrieve users: " . mysql_error()); } - $users = mysql_num_rows( $result ); + $users = mysql_num_rows($result); if ($users != 0) { - $result = mysql_query( "DROP USER '$username'@'$hostname'" ); + $result = mysql_query("DROP USER '$username'@'$hostname'"); if ($result === false) { - throw new Exception( "Unable to drop user: " . mysql_error() ); + throw new Exception("Unable to drop user: " . mysql_error()); } } - CLI::logging( "Creating user $username for $hostname\n" ); - $result = mysql_query( "CREATE USER '$username'@'$hostname' IDENTIFIED BY '$password'" ); + CLI::logging("Creating user $username for $hostname\n"); + $result = mysql_query("CREATE USER '$username'@'$hostname' IDENTIFIED BY '$password'"); if ($result === false) { - throw new Exception( "Unable to create user $username: " . mysql_error() ); + throw new Exception("Unable to create user $username: " . mysql_error()); } - $result = mysql_query( "GRANT ALL ON $database.* TO '$username'@'$hostname'" ); + $result = mysql_query("GRANT ALL ON $database.* TO '$username'@'$hostname'"); if ($result === false) { - throw new Exception( "Unable to grant priviledges to user $username: " . mysql_error() ); + throw new Exception("Unable to grant priviledges to user $username: " . mysql_error()); } } @@ -941,92 +933,90 @@ class workspaceTools * @param string $filename the script filename * @param string $database the database to execute this script into */ - private function executeSQLScript ($database, $filename) + private function executeSQLScript($database, $filename) { - mysql_query( "CREATE DATABASE IF NOT EXISTS " . mysql_real_escape_string( $database ) ); - mysql_select_db( $database ); - $script = file_get_contents( $filename ); - $lines = explode( "\n", $script ); + mysql_query("CREATE DATABASE IF NOT EXISTS " . mysql_real_escape_string($database)); + mysql_select_db($database); + $script = file_get_contents($filename); + $lines = explode("\n", $script); $previous = null; foreach ($lines as $j => $line) { // Remove comments from the script - $line = trim( $line ); - if (strpos( $line, "--" ) === 0) { - $line = substr( $line, 0, strpos( $line, "--" ) ); + $line = trim($line); + if (strpos($line, "--") === 0) { + $line = substr($line, 0, strpos($line, "--")); } - if (empty( $line )) { + if (empty($line)) { continue; } - // Concatenate the previous line, if any, with the current + // Concatenate the previous line, if any, with the current if ($previous) { $line = $previous . " " . $line; } $previous = null; // If the current line doesnt end with ; then put this line together // with the next one, thus supporting multi-line statements. - if (strrpos( $line, ";" ) != strlen( $line ) - 1) { + if (strrpos($line, ";") != strlen($line) - 1) { $previous = $line; continue; } - $line = substr( $line, 0, strrpos( $line, ";" ) ); - $result = mysql_query( $line ); + $line = substr($line, 0, strrpos($line, ";")); + $result = mysql_query($line); if ($result === false) { - throw new Exception( "Error when running script '$filename', line $j, query '$line': " . mysql_error() ); + throw new Exception("Error when running script '$filename', line $j, query '$line': " . mysql_error()); } } } - static public function restoreLegacy ($directory) + static public function restoreLegacy($directory) { - throw new Exception( "Use gulliver to restore backups from old versions" ); + throw new Exception("Use gulliver to restore backups from old versions"); } - static public function getBackupInfo ($filename) + static public function getBackupInfo($filename) { - G::LoadThirdParty( 'pear/Archive', 'Tar' ); - $backup = new Archive_Tar( $filename ); + G::LoadThirdParty('pear/Archive', 'Tar'); + $backup = new Archive_Tar($filename); //Get a temporary directory in the upgrade directory - $tempDirectory = PATH_DATA . "upgrade/" . basename( tempnam( __FILE__, '' ) ); - mkdir( $tempDirectory ); - $metafiles = array (); + $tempDirectory = PATH_DATA . "upgrade/" . basename(tempnam(__FILE__, '')); + mkdir($tempDirectory); + $metafiles = array(); foreach ($backup->listContent() as $backupFile) { $filename = $backupFile["filename"]; - if (strpos( $filename, "/" ) === false && substr_compare( $filename, ".meta", - 5, 5, true ) === 0) { - if (! $backup->extractList( array ($filename - ), $tempDirectory )) { - throw new Exception( "Could not extract backup" ); + if (strpos($filename, "/") === false && substr_compare($filename, ".meta", - 5, 5, true) === 0) { + if (!$backup->extractList(array($filename), $tempDirectory)) { + throw new Exception("Could not extract backup"); } $metafiles[] = "$tempDirectory/$filename"; } } - CLI::logging( "Found " . count( $metafiles ) . " workspace(s) in backup\n" ); + CLI::logging("Found " . count($metafiles) . " workspace(s) in backup\n"); foreach ($metafiles as $metafile) { - $data = file_get_contents( $metafile ); - $workspaceData = G::json_decode( $data ); - CLI::logging( "\n" ); - workspaceTools::printInfo( (array) $workspaceData ); - + $data = file_get_contents($metafile); + $workspaceData = G::json_decode($data); + CLI::logging("\n"); + workspaceTools::printInfo((array) $workspaceData); } - G::rm_dir( $tempDirectory ); + G::rm_dir($tempDirectory); } - static public function dirPerms ($filename, $owner, $group, $perms) + static public function dirPerms($filename, $owner, $group, $perms) { - $chown = @chown( $filename, $owner ); - $chgrp = @chgrp( $filename, $group ); - $chmod = @chmod( $filename, $perms ); + $chown = @chown($filename, $owner); + $chgrp = @chgrp($filename, $group); + $chmod = @chmod($filename, $perms); if ($chgrp === false || $chmod === false || $chown === false) { - CLI::logging( CLI::error( "Failed to set permissions for $filename" ) . "\n" ); + CLI::logging(CLI::error("Failed to set permissions for $filename") . "\n"); } - if (is_dir( $filename )) { - foreach (array_merge( glob( $filename . "/*" ), glob( $filename . "/.*" ) ) as $item) { - if (basename( $item ) == "." || basename( $item ) == "..") { + if (is_dir($filename)) { + foreach (array_merge(glob($filename . "/*"), glob($filename . "/.*")) as $item) { + if (basename($item) == "." || basename($item) == "..") { continue; } - workspaceTools::dirPerms( $item, $owner, $group, $perms ); + workspaceTools::dirPerms($item, $owner, $group, $perms); } } } @@ -1041,121 +1031,119 @@ class workspaceTools * @param string $newWorkspaceName if defined, supplies the name for the * workspace to restore to */ - static public function restore ($filename, $srcWorkspace, $dstWorkspace = null, $overwrite = true) + static public function restore($filename, $srcWorkspace, $dstWorkspace = null, $overwrite = true) { - G::LoadThirdParty( 'pear/Archive', 'Tar' ); - $backup = new Archive_Tar( $filename ); + G::LoadThirdParty('pear/Archive', 'Tar'); + $backup = new Archive_Tar($filename); //Get a temporary directory in the upgrade directory - $tempDirectory = PATH_DATA . "upgrade/" . basename( tempnam( __FILE__, '' ) ); + $tempDirectory = PATH_DATA . "upgrade/" . basename(tempnam(__FILE__, '')); $parentDirectory = PATH_DATA . "upgrade"; - if (is_writable( $parentDirectory )) { - mkdir( $tempDirectory ); + if (is_writable($parentDirectory)) { + mkdir($tempDirectory); } else { - throw new Exception( "Could not create directory:" . $parentDirectory ); + throw new Exception("Could not create directory:" . $parentDirectory); } //Extract all backup files, including database scripts and workspace files - if (! $backup->extract( $tempDirectory )) { - throw new Exception( "Could not extract backup" ); + if (!$backup->extract($tempDirectory)) { + throw new Exception("Could not extract backup"); } //Search for metafiles in the new standard (the old standard would contain //txt files). - $metaFiles = glob( $tempDirectory . "/*.meta" ); - if (empty( $metaFiles )) { - $metaFiles = glob( $tempDirectory . "/*.txt" ); - if (! empty( $metaFiles )) { - return workspaceTools::restoreLegacy( $tempDirectory ); + $metaFiles = glob($tempDirectory . "/*.meta"); + if (empty($metaFiles)) { + $metaFiles = glob($tempDirectory . "/*.txt"); + if (!empty($metaFiles)) { + return workspaceTools::restoreLegacy($tempDirectory); } else { - throw new Exception( "No metadata found in backup" ); + throw new Exception("No metadata found in backup"); } } else { - CLI::logging( "Found " . count( $metaFiles ) . " workspaces in backup:\n" ); + CLI::logging("Found " . count($metaFiles) . " workspaces in backup:\n"); foreach ($metaFiles as $metafile) { - CLI::logging( "-> " . basename( $metafile ) . "\n" ); + CLI::logging("-> " . basename($metafile) . "\n"); } } - if (count( $metaFiles ) > 1 && (! isset( $srcWorkspace ))) { - throw new Exception( "Multiple workspaces in backup but no workspace specified to restore" ); + if (count($metaFiles) > 1 && (!isset($srcWorkspace))) { + throw new Exception("Multiple workspaces in backup but no workspace specified to restore"); } - if (isset( $srcWorkspace ) && ! in_array( "$srcWorkspace.meta", array_map( BASENAME, $metaFiles ) )) { - throw new Exception( "Workspace $srcWorkspace not found in backup" ); + if (isset($srcWorkspace) && !in_array("$srcWorkspace.meta", array_map(BASENAME, $metaFiles))) { + throw new Exception("Workspace $srcWorkspace not found in backup"); } foreach ($metaFiles as $metaFile) { - $metadata = G::json_decode( file_get_contents( $metaFile ) ); + $metadata = G::json_decode(file_get_contents($metaFile)); if ($metadata->version != 1) { - throw new Exception( "Backup version {$metadata->version} not supported" ); + throw new Exception("Backup version {$metadata->version} not supported"); } $backupWorkspace = $metadata->WORKSPACE_NAME; - if (isset( $dstWorkspace )) { + if (isset($dstWorkspace)) { $workspaceName = $dstWorkspace; $createWorkspace = true; } else { $workspaceName = $metadata->WORKSPACE_NAME; $createWorkspace = false; } - if (isset( $srcWorkspace ) && strcmp( $metadata->WORKSPACE_NAME, $srcWorkspace ) != 0) { - CLI::logging( CLI::warning( "> Workspace $backupWorkspace found, but not restoring." ) . "\n" ); + if (isset($srcWorkspace) && strcmp($metadata->WORKSPACE_NAME, $srcWorkspace) != 0) { + CLI::logging(CLI::warning("> Workspace $backupWorkspace found, but not restoring.") . "\n"); continue; } else { - CLI::logging( "> Restoring " . CLI::info( $backupWorkspace ) . " to " . CLI::info( $workspaceName ) . "\n" ); + CLI::logging("> Restoring " . CLI::info($backupWorkspace) . " to " . CLI::info($workspaceName) . "\n"); } - $workspace = new workspaceTools( $workspaceName ); + $workspace = new workspaceTools($workspaceName); if ($workspace->workspaceExists()) { if ($overwrite) { - CLI::logging( CLI::warning( "> Workspace $workspaceName already exist, overwriting!" ) . "\n" ); + CLI::logging(CLI::warning("> Workspace $workspaceName already exist, overwriting!") . "\n"); } else { - throw new Exception( "Destination workspace already exist (use -o to overwrite)" ); + throw new Exception("Destination workspace already exist (use -o to overwrite)"); } } - if (file_exists( $workspace->path )) { - G::rm_dir( $workspace->path ); + if (file_exists($workspace->path)) { + G::rm_dir($workspace->path); } foreach ($metadata->directories as $dir) { - CLI::logging( "+> Restoring directory '$dir'\n" ); + CLI::logging("+> Restoring directory '$dir'\n"); - if (! rename( "$tempDirectory/$dir", $workspace->path )) { - throw new Exception( "There was an error copying the backup files ($tempDirectory/$dir) to the workspace directory {$workspace->path}." ); + if (!rename("$tempDirectory/$dir", $workspace->path)) { + throw new Exception("There was an error copying the backup files ($tempDirectory/$dir) to the workspace directory {$workspace->path}."); } - } - CLI::logging( "> Changing file permissions\n" ); - $shared_stat = stat( PATH_DATA ); + CLI::logging("> Changing file permissions\n"); + $shared_stat = stat(PATH_DATA); if ($shared_stat !== false) { - workspaceTools::dirPerms( $workspace->path, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode'] ); + workspaceTools::dirPerms($workspace->path, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); } else { - CLI::logging( CLI::error( "Could not get the shared folder permissions, not changing workspace permissions" ) . "\n" ); + CLI::logging(CLI::error("Could not get the shared folder permissions, not changing workspace permissions") . "\n"); } - list ($dbHost, $dbUser, $dbPass) = @explode( SYSTEM_HASH, G::decrypt( HASH_INSTALLATION, SYSTEM_HASH ) ); + list ($dbHost, $dbUser, $dbPass) = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); - CLI::logging( "> Connecting to system database in '$dbHost'\n" ); - $link = mysql_connect( $dbHost, $dbUser, $dbPass ); - @mysql_query( "SET NAMES 'utf8';" ); - @mysql_query( "SET FOREIGN_KEY_CHECKS=0;" ); - if (! $link) { - throw new Exception( 'Could not connect to system database: ' . mysql_error() ); + CLI::logging("> Connecting to system database in '$dbHost'\n"); + $link = mysql_connect($dbHost, $dbUser, $dbPass); + @mysql_query("SET NAMES 'utf8';"); + @mysql_query("SET FOREIGN_KEY_CHECKS=0;"); + if (!$link) { + throw new Exception('Could not connect to system database: ' . mysql_error()); } - $newDBNames = $workspace->resetDBInfo( $dbHost, $createWorkspace ); + $newDBNames = $workspace->resetDBInfo($dbHost, $createWorkspace); foreach ($metadata->databases as $db) { $dbName = $newDBNames[$db->name]; - CLI::logging( "+> Restoring database {$db->name} to $dbName\n" ); - $workspace->executeSQLScript( $dbName, "$tempDirectory/{$db->name}.sql" ); - $workspace->createDBUser( $dbName, $db->pass, "localhost", $dbName ); - $workspace->createDBUser( $dbName, $db->pass, "%", $dbName ); + CLI::logging("+> Restoring database {$db->name} to $dbName\n"); + $workspace->executeSQLScript($dbName, "$tempDirectory/{$db->name}.sql"); + $workspace->createDBUser($dbName, $db->pass, "localhost", $dbName); + $workspace->createDBUser($dbName, $db->pass, "%", $dbName); } - $workspace->upgradeCacheView( false ); - - mysql_close( $link ); + $workspace->upgradeCacheView(false); + mysql_close($link); } - CLI::logging( "Removing temporary files\n" ); + CLI::logging("Removing temporary files\n"); - G::rm_dir( $tempDirectory ); + G::rm_dir($tempDirectory); - CLI::logging( CLI::info( "Done restoring" ) . "\n" ); + CLI::logging(CLI::info("Done restoring") . "\n"); } } diff --git a/workflow/engine/classes/triggers/api/class.zimbraApi.php b/workflow/engine/classes/triggers/api/class.zimbraApi.php index 255b596c1..b8fbccb6e 100644 --- a/workflow/engine/classes/triggers/api/class.zimbraApi.php +++ b/workflow/engine/classes/triggers/api/class.zimbraApi.php @@ -18,7 +18,7 @@ class Zimbra protected $_connected = false; // boolean to determine if the connect function has been called protected static $_num_soap_calls = 0; // the number of times a SOAP call has been made protected $_preAuthKey; // key for doing pre-authentication - protected $_lcached_assets = array (); // an array to hold assets that have been cached + protected $_lcached_assets = array(); // an array to hold assets that have been cached protected $_preauth_expiration = 0; // 0 indicates using the default preauth expiration as defined on the server protected $_dev; // boolean indicating whether this is development or not protected $_protocol; // which protocol to use when building the URL @@ -34,7 +34,6 @@ class Zimbra protected $_idm; // IDMObject protected $_username; // the user we are operating as - /** * __construct * @@ -46,7 +45,7 @@ class Zimbra * @param string $which defaults to prod */ - public function __construct ($username, $serverUrl, $preAuthKey, $which = 'prod', $protocol = 'http') + public function __construct($username, $serverUrl, $preAuthKey, $which = 'prod', $protocol = 'http') { if ($which == 'dev') { $which = 'zimbra_dev'; @@ -56,7 +55,7 @@ class Zimbra } $this->_preAuthKey = $preAuthKey; - $this->_protocol = $protocol."://"; // could also be http:// + $this->_protocol = $protocol . "://"; // could also be http:// $this->_server = $serverUrl; //'zimbra.hostname.edu'; $this->_server1 = $serverUrl; //'zimbra.hostname.edu'; $this->_username = $username; @@ -65,7 +64,6 @@ class Zimbra // end __construct - /** * sso * @@ -76,14 +74,14 @@ class Zimbra * @param string $options options for sso * @return boolean */ - public function sso ($options = '') + public function sso($options = '') { if ($this->_username) { - setcookie( 'ZM_SKIN', 'plymouth', time() + 60 * 60 * 24 * 30, '/', '.plymouth.edu' ); + setcookie('ZM_SKIN', 'plymouth', time() + 60 * 60 * 24 * 30, '/', '.plymouth.edu'); - $pre_auth = $this->getPreAuth( $this->_username ); + $pre_auth = $this->getPreAuth($this->_username); $url = $this->_protocol . '/service/preauth?account=' . $this->_username . '@' . $this->_server . '&expires=' . $this->_preauth_expiration . '×tamp=' . $this->_timestamp . '&preauth=' . $pre_auth; //.'&'.$options; - header( "Location: $url" ); + header("Location: $url"); exit(); } else { return false; @@ -92,7 +90,6 @@ class Zimbra // end sso - /** * createAccount * @@ -100,7 +97,7 @@ class Zimbra * @param string $password password * @return string account id */ - function createAccount ($name, $password) + public function createAccount($name, $password) { $option_string = ''; @@ -112,9 +109,9 @@ class Zimbra '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); } catch (SoapFault $exception) { - print_exception( $exception ); + print_exception($exception); } return $result['SOAP:ENVELOPE']['SOAP:BODY']['CREATEACCOUNTRESPONSE']['ACCOUNT']['ID']; @@ -130,7 +127,7 @@ class Zimbra * @param string $username username * @return string preauthentication key in hmacsha1 format */ - private function getPreAuth ($username) + private function getPreAuth($username) { $account_identifier = $username . '@' . $this->_server1; $by_value = 'name'; @@ -139,12 +136,11 @@ class Zimbra $string = $account_identifier . '|' . $by_value . '|' . $expires . '|' . $timestamp; - return $this->hmacsha1( $this->_preAuthKey, $string ); + return $this->hmacsha1($this->_preAuthKey, $string); } // end getPreAuth - /** * hmacsha1 * @@ -156,23 +152,22 @@ class Zimbra * @param string $data data to encrypt * @return string converted to hmac sha1 format */ - private function hmacsha1 ($key, $data) + private function hmacsha1($key, $data) { $blocksize = 64; $hashfunc = 'sha1'; - if (strlen( $key ) > $blocksize) { - $key = pack( 'H*', $hashfunc( $key ) ); + if (strlen($key) > $blocksize) { + $key = pack('H*', $hashfunc($key)); } - $key = str_pad( $key, $blocksize, chr( 0x00 ) ); - $ipad = str_repeat( chr( 0x36 ), $blocksize ); - $opad = str_repeat( chr( 0x5c ), $blocksize ); - $hmac = pack( 'H*', $hashfunc( ($key ^ $opad) . pack( 'H*', $hashfunc( ($key ^ $ipad) . $data ) ) ) ); - return bin2hex( $hmac ); + $key = str_pad($key, $blocksize, chr(0x00)); + $ipad = str_repeat(chr(0x36), $blocksize); + $opad = str_repeat(chr(0x5c), $blocksize); + $hmac = pack('H*', $hashfunc(($key ^ $opad) . pack('H*', $hashfunc(($key ^ $ipad) . $data)))); + return bin2hex($hmac); } // end hmacsha1 - /** * connect * @@ -182,34 +177,33 @@ class Zimbra * @access public * @return array associative array of account information */ - public function connect () + public function connect() { if ($this->_connected) { return $this->_account_info; } $completeurl = $this->_protocol . $this->_server . $this->_path; $this->_curl = curl_init(); - curl_setopt( $this->_curl, CURLOPT_URL, $this->_protocol . $this->_server . $this->_path ); - curl_setopt( $this->_curl, CURLOPT_POST, true ); - curl_setopt( $this->_curl, CURLOPT_RETURNTRANSFER, true ); - curl_setopt( $this->_curl, CURLOPT_SSL_VERIFYPEER, false ); - curl_setopt( $this->_curl, CURLOPT_SSL_VERIFYHOST, false ); + curl_setopt($this->_curl, CURLOPT_URL, $this->_protocol . $this->_server . $this->_path); + curl_setopt($this->_curl, CURLOPT_POST, true); + curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($this->_curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($this->_curl, CURLOPT_SSL_VERIFYHOST, false); //Apply proxy settings $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { - curl_setopt( $this->_curl, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); + curl_setopt($this->_curl, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); if ($sysConf['proxy_port'] != '') { - curl_setopt( $this->_curl, CURLOPT_PROXYPORT, $sysConf['proxy_port'] ); + curl_setopt($this->_curl, CURLOPT_PROXYPORT, $sysConf['proxy_port']); } if ($sysConf['proxy_user'] != '') { - curl_setopt( $this->_curl, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '') ); + curl_setopt($this->_curl, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); } - curl_setopt( $this->_curl, CURLOPT_HTTPHEADER, array ('Expect:' - ) ); + curl_setopt($this->_curl, CURLOPT_HTTPHEADER, array('Expect:')); } - $preauth = $this->getPreAuth( $this->_username ); + $preauth = $this->getPreAuth($this->_username); $header = ''; if ($this->_admin) { @@ -224,13 +218,13 @@ class Zimbra '; } - $response = $this->soapRequest( $body, $header, true ); + $response = $this->soapRequest($body, $header, true); if ($response) { - $tmp = $this->makeXMLTree( $response ); + $tmp = $this->makeXMLTree($response); $this->_account_info = $tmp['soap:Envelope'][0]['soap:Header'][0]['context'][0]['refresh'][0]['folder'][0]; - $this->session_id = $this->extractSessionID( $response ); - $this->auth_token = $this->extractAuthToken( $response ); + $this->session_id = $this->extractSessionID($response); + $this->auth_token = $this->extractAuthToken($response); $this->_connected = true; @@ -244,7 +238,6 @@ class Zimbra // end connect - /** * administerUser * @@ -255,9 +248,9 @@ class Zimbra * @param string $username username to administer * @return boolean */ - public function administerUser ($username) + public function administerUser($username) { - if (! $this->_admin) { + if (!$this->_admin) { return false; } @@ -266,13 +259,13 @@ class Zimbra $body = ' ' . $this->_username . '@' . $this->_server . ' '; - $response = $this->soapRequest( $body, $header ); + $response = $this->soapRequest($body, $header); if ($response) { - $tmp = $this->makeXMLTree( $response ); + $tmp = $this->makeXMLTree($response); $this->_account_info = $tmp['soap:Envelope'][0]['soap:Header'][0]['context'][0]['refresh'][0]['folder'][0]; - $this->session_id = $this->extractSessionID( $response ); - $this->auth_token = $this->extractAuthToken( $response ); + $this->session_id = $this->extractSessionID($response); + $this->auth_token = $this->extractAuthToken($response); return true; } else { @@ -282,7 +275,6 @@ class Zimbra // end administerUser - /** * getInfo * @@ -293,15 +285,15 @@ class Zimbra * @param string $options options for info retrieval, defaults to null * @return array information */ - public function getInfo ($options = '') + public function getInfo($options = '') { // valid sections: mbox,prefs,attrs,zimlets,props,idents,sigs,dsrcs,children - $option_string = $this->buildOptionString( $options ); + $option_string = $this->buildOptionString($options); $soap = ''; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['GetInfoResponse'][0]; } else { return false; @@ -310,7 +302,6 @@ class Zimbra // end getInfo - /** * getMessages * @@ -322,16 +313,16 @@ class Zimbra * @param array $options options to apply to retrieval * @return array array of messages */ - public function getMessages ($search = 'in:inbox', $options = array('limit' => 5, 'fetch' => 'none')) + public function getMessages($search = 'in:inbox', $options = array('limit' => 5, 'fetch' => 'none')) { - $option_string = $this->buildOptionString( $options ); + $option_string = $this->buildOptionString($options); $soap = ' ' . $search . ' '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['SearchResponse'][0]; } else { return false; @@ -340,7 +331,6 @@ class Zimbra // end getMessages - /** * getContacts * @@ -352,16 +342,16 @@ class Zimbra * @param array $options options to apply to retrieval * @return array array of messages */ - public function getContacts ($search = 'in:contacts', $options = array('limit' => 5, 'fetch' => 'none')) + public function getContacts($search = 'in:contacts', $options = array('limit' => 5, 'fetch' => 'none')) { - $option_string = $this->buildOptionString( $options ); + $option_string = $this->buildOptionString($options); $soap = ' ' . $search . ' '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['SearchResponse'][0]; } else { return false; @@ -373,25 +363,25 @@ class Zimbra /* getAppointments * - * get the Appointments in folder - * - * @since version 1.0 - * @access public - * @param string $search folder to retrieve from - * @param array $options options to apply to retrieval - * @return array array of messages - */ + * get the Appointments in folder + * + * @since version 1.0 + * @access public + * @param string $search folder to retrieve from + * @param array $options options to apply to retrieval + * @return array array of messages + */ - public function getAppointments ($search = 'in:calendar', $options = array('limit' => 50, 'fetch' => 'none')) + public function getAppointments($search = 'in:calendar', $options = array('limit' => 50, 'fetch' => 'none')) { - $option_string = $this->buildOptionString( $options ); + $option_string = $this->buildOptionString($options); $soap = ' ' . $search . ' '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['SearchResponse'][0]; } else { return false; @@ -403,25 +393,25 @@ class Zimbra /* getTasks * - * get the Tasks in folder - * - * @since version 1.0 - * @access public - * @param string $search folder to retrieve from - * @param array $options options to apply to retrieval - * @return array array of messages - */ + * get the Tasks in folder + * + * @since version 1.0 + * @access public + * @param string $search folder to retrieve from + * @param array $options options to apply to retrieval + * @return array array of messages + */ - public function getTasks ($search = 'in:tasks', $options = array('limit' => 50, 'fetch' => 'none')) + public function getTasks($search = 'in:tasks', $options = array('limit' => 50, 'fetch' => 'none')) { - $option_string = $this->buildOptionString( $options ); + $option_string = $this->buildOptionString($options); $soap = ' ' . $search . ' '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['SearchResponse'][0]; } else { return false; @@ -430,7 +420,6 @@ class Zimbra // end getTasks - /** * getMessageContent * @@ -441,15 +430,15 @@ class Zimbra * @param int $id id number of message to retrieve content of * @return array associative array with message content, valid for tasks, calendar entries, and email messages. */ - public function getMessageContent ($id) + public function getMessageContent($id) { $soap = ' * '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); $temp = $array['soap:Envelope'][0]['soap:Body'][0]['GetMsgResponse'][0]['m'][0]; $message = $temp['inv'][0]['comp'][0]; @@ -475,10 +464,10 @@ class Zimbra * @access public * @return array $subscribed */ - public function getSubscribedCalendars () + public function getSubscribedCalendars() { - $subscribed = array (); - if (is_array( $this->_account_info['link_attribute_name'] )) { + $subscribed = array(); + if (is_array($this->_account_info['link_attribute_name'])) { foreach ($this->_account_info['link_attribute_name'] as $i => $name) { if ($this->_account_info['link_attribute_view'][$i] == 'appointment') { $subscribed[$this->_account_info['link_attribute_id'][$i]] = $name; @@ -490,7 +479,6 @@ class Zimbra // end getSubscribedCalendars - /** * getSubscribedTaskLists * @@ -500,10 +488,10 @@ class Zimbra * @access public * @return array $subscribed or false */ - public function getSubscribedTaskLists () + public function getSubscribedTaskLists() { - $subscribed = array (); - if (is_array( $this->_account_info['link_attribute_name'] )) { + $subscribed = array(); + if (is_array($this->_account_info['link_attribute_name'])) { foreach ($this->_account_info['link_attribute_name'] as $i => $name) { if ($this->_account_info['link_attribute_view'][$i] == 'task') { $subscribed[$this->_account_info['link_attribute_id'][$i]] = $name; @@ -515,7 +503,6 @@ class Zimbra // end getSubscribedCalendars - /** * getFolder * @@ -526,7 +513,7 @@ class Zimbra * @param string $folder_options options for folder retrieval * @return array $folder or false */ - public function getFolder ($folderName, $folder_options = '') + public function getFolder($folderName, $folder_options = '') { //$folder_option_string = $this->buildOptionString($folder_options); @@ -535,14 +522,14 @@ class Zimbra $soap = ' '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); - $folder = (is_array( $array['soap:Envelope'][0]['soap:Body'][0]['GetFolderResponse'][0]['folder'][0] )) ? $array['soap:Envelope'][0]['soap:Body'][0]['GetFolderResponse'][0]['folder'][0] : $array['soap:Envelope'][0]['soap:Body'][0]['GetFolderResponse'][0]; + $folder = (is_array($array['soap:Envelope'][0]['soap:Body'][0]['GetFolderResponse'][0]['folder'][0])) ? $array['soap:Envelope'][0]['soap:Body'][0]['GetFolderResponse'][0]['folder'][0] : $array['soap:Envelope'][0]['soap:Body'][0]['GetFolderResponse'][0]; - $folder['u'] = (! isset( $folder['u'] )) ? $folder['folder_attribute_u'][0] : $folder['u']; - $folder['n'] = (! isset( $folder['n'] )) ? $folder['folder_attribute_n'][0] : $folder['n']; + $folder['u'] = (!isset($folder['u'])) ? $folder['folder_attribute_u'][0] : $folder['u']; + $folder['n'] = (!isset($folder['n'])) ? $folder['folder_attribute_n'][0] : $folder['n']; return $folder; } else { @@ -552,7 +539,6 @@ class Zimbra // end getFolder - /** * getPrefrences * @@ -563,13 +549,13 @@ class Zimbra * @example example XML: [ ] * @return array $prefs or false */ - public function getPreferences () + public function getPreferences() { $soap = ''; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $prefs = array (); - $array = $this->makeXMLTree( $response ); + $prefs = array(); + $array = $this->makeXMLTree($response); foreach ($array['soap:Envelope'][0]['soap:Body'][0]['GetPrefsResponse'][0]['pref'] as $k => $value) { $prefs[$array['soap:Envelope'][0]['soap:Body'][0]['GetPrefsResponse'][0]['pref_attribute_name'][$k]] = $value; } @@ -581,7 +567,6 @@ class Zimbra // end getPreferences - /** * setPrefrences * @@ -593,7 +578,7 @@ class Zimbra * @example example XML: [{value}...]+ * @return boolean */ - public function setPreferences ($options = '') + public function setPreferences($options = '') { $option_string = ''; foreach ($options as $name => $value) { @@ -603,7 +588,7 @@ class Zimbra $soap = ' ' . $option_string . ' '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { return true; } else { @@ -613,7 +598,6 @@ class Zimbra // end setPreferences - /** * emailChannel * @@ -622,30 +606,30 @@ class Zimbra * @since version 1.0 * @access public */ - public function emailChannel () + public function emailChannel() { require_once 'xtemplate.php'; - $tpl = new XTemplate( '/web/pscpages/webapp/portal/channel/email/templates/index.tpl' ); + $tpl = new XTemplate('/web/pscpages/webapp/portal/channel/email/templates/index.tpl'); - $tpl->parse( 'main.transition' ); + $tpl->parse('main.transition'); $total_messages = 0; $unread_messages = 0; - $messages = $this->getMessages( 'in:inbox' ); - if (is_array( $messages )) { + $messages = $this->getMessages('in:inbox'); + if (is_array($messages)) { $more = $messages['more']; foreach ($messages['m'] as $message) { - $clean_message = array (); + $clean_message = array(); - $clean_message['subject'] = (isset( $message['su'][0] ) && $message['su'][0] != '') ? htmlentities( $message['su'][0] ) : '[None]'; - $clean_message['subject'] = (strlen( $clean_message['subject'] ) > 20) ? substr( $clean_message['subject'], 0, 17 ) . '...' : $clean_message['subject']; + $clean_message['subject'] = (isset($message['su'][0]) && $message['su'][0] != '') ? htmlentities($message['su'][0]) : '[None]'; + $clean_message['subject'] = (strlen($clean_message['subject']) > 20) ? substr($clean_message['subject'], 0, 17) . '...' : $clean_message['subject']; $clean_message['body_fragment'] = $message['fr'][0]; $clean_message['from_email'] = $message['e_attribute_a'][0]; - $clean_message['from'] = ($message['e_attribute_p'][0]) ? htmlspecialchars( $message['e_attribute_p'][0] ) : $clean_message['from_email']; - $clean_message['size'] = $this->makeBytesPretty( $message['s'], 40 * 1024 * 1024 ); - $clean_message['date'] = date( 'n/j/y', ($message['d'] / 1000) ); + $clean_message['from'] = ($message['e_attribute_p'][0]) ? htmlspecialchars($message['e_attribute_p'][0]) : $clean_message['from_email']; + $clean_message['size'] = $this->makeBytesPretty($message['s'], 40 * 1024 * 1024); + $clean_message['date'] = date('n/j/y', ($message['d'] / 1000)); $clean_message['id'] = $message['id']; $clean_message['url'] = 'http://go.plymouth.edu/mymail/msg/' . $clean_message['id']; @@ -653,50 +637,49 @@ class Zimbra $clean_message['status'] = 'read'; $clean_message['deleted'] = false; $clean_message['flagged'] = false; - if (isset( $message['f'] )) { - $clean_message['attachment'] = (strpos( $message['f'], 'a' ) !== false) ? true : false; - $clean_message['status'] = (strpos( $message['f'], 'u' ) !== false) ? 'unread' : 'read'; + if (isset($message['f'])) { + $clean_message['attachment'] = (strpos($message['f'], 'a') !== false) ? true : false; + $clean_message['status'] = (strpos($message['f'], 'u') !== false) ? 'unread' : 'read'; ; - $clean_message['deleted'] = (strpos( $message['f'], '2' ) !== false) ? true : false; - $clean_message['flagged'] = (strpos( $message['f'], 'f' ) !== false) ? true : false; + $clean_message['deleted'] = (strpos($message['f'], '2') !== false) ? true : false; + $clean_message['flagged'] = (strpos($message['f'], 'f') !== false) ? true : false; } - $tpl->assign( 'message', $clean_message ); - $tpl->parse( 'main.message' ); + $tpl->assign('message', $clean_message); + $tpl->parse('main.message'); } - $inbox = $this->getFolder( array ('l' => 2 - ) ); + $inbox = $this->getFolder(array('l' => 2 + )); $total_messages = (int) $inbox['n']; $unread_messages = (int) $inbox['u']; } - $tpl->assign( 'total_messages', $total_messages ); - $tpl->assign( 'unread_messages', $unread_messages ); + $tpl->assign('total_messages', $total_messages); + $tpl->assign('unread_messages', $unread_messages); - $info = $this->getInfo( array ('sections' => 'mbox' - ) ); - if (is_array( $info['attrs'][0]['attr_attribute_name'] )) { - $quota = $info['attrs'][0]['attr'][array_search( 'zimbraMailQuota', $info['attrs'][0]['attr_attribute_name'] )]; - $size_text = $this->makeBytesPretty( $info['used'][0], ($quota * 0.75) ) . ' out of ' . $this->makeBytesPretty( $quota ); - $tpl->assign( 'size', $size_text ); + $info = $this->getInfo(array('sections' => 'mbox' + )); + if (is_array($info['attrs'][0]['attr_attribute_name'])) { + $quota = $info['attrs'][0]['attr'][array_search('zimbraMailQuota', $info['attrs'][0]['attr_attribute_name'])]; + $size_text = $this->makeBytesPretty($info['used'][0], ($quota * 0.75)) . ' out of ' . $this->makeBytesPretty($quota); + $tpl->assign('size', $size_text); } /* include_once 'portal_functions.php'; - $roles = getRoles($this->_username); + $roles = getRoles($this->_username); - if(in_array('faculty', $roles) || in_array('employee', $roles)) - { - $tpl->parse('main.away_message'); - } */ + if(in_array('faculty', $roles) || in_array('employee', $roles)) + { + $tpl->parse('main.away_message'); + } */ - $tpl->parse( 'main' ); - $tpl->out( 'main' ); + $tpl->parse('main'); + $tpl->out('main'); } // end emailChannel - /** * builOptionString * @@ -707,7 +690,7 @@ class Zimbra * @param array $options array of options to be parsed into a string * @return string $options_string */ - protected function buildOptionString ($options) + protected function buildOptionString($options) { $options_string = ''; foreach ($options as $k => $v) { @@ -718,7 +701,6 @@ class Zimbra // end buildOptionString - /** * extractAuthToken * @@ -729,11 +711,11 @@ class Zimbra * @param string $xml xml to have the auth token pulled from * @return string $auth_token */ - private function extractAuthToken ($xml) + private function extractAuthToken($xml) { - $auth_token = strstr( $xml, "" ); - $auth_token = substr( $auth_token, 1, strpos( $auth_token, "<" ) - 1 ); + $auth_token = strstr($xml, ""); + $auth_token = substr($auth_token, 1, strpos($auth_token, "<") - 1); return $auth_token; } @@ -747,20 +729,19 @@ class Zimbra * @param string $xml xml to have the session id pulled from * @return int $session_id */ - private function extractSessionID ($xml) + private function extractSessionID($xml) { //for testing purpose we are extracting lifetime instead of sessionid //$session_id = strstr($xml, "" ); - $session_id = substr( $session_id, 1, strpos( $session_id, "<" ) - 1 ); + $session_id = strstr($xml, ""); + $session_id = substr($session_id, 1, strpos($session_id, "<") - 1); return $session_id; } // end extractSessionID - /** * extractErrorCode * @@ -771,17 +752,16 @@ class Zimbra * @param string $xml xml to have the error code pulled from * @return int $session_id */ - private function extractErrorCode ($xml) + private function extractErrorCode($xml) { - $session_id = strstr( $xml, "" ); - $session_id = substr( $session_id, 1, strpos( $session_id, "<" ) - 1 ); + $session_id = strstr($xml, ""); + $session_id = substr($session_id, 1, strpos($session_id, "<") - 1); return $session_id; } // end extractErrorCode - /** * makeBytesPretty * @@ -793,14 +773,14 @@ class Zimbra * @param boolean $redlevel * @return int $size */ - private function makeBytesPretty ($bytes, $redlevel = false) + private function makeBytesPretty($bytes, $redlevel = false) { if ($bytes < 1024) { $size = $bytes . ' B'; } elseif ($bytes < 1024 * 1024) { - $size = round( $bytes / 1024, 1 ) . ' KB'; + $size = round($bytes / 1024, 1) . ' KB'; } else { - $size = round( ($bytes / 1024) / 1024, 1 ) . ' MB'; + $size = round(($bytes / 1024) / 1024, 1) . ' MB'; } if ($redlevel && $bytes > $redlevel) { $size = '' . $size . ''; @@ -811,7 +791,6 @@ class Zimbra // end makeBytesPretty - /** * message * @@ -821,7 +800,7 @@ class Zimbra * @access public * @param string $message message for debug */ - protected function message ($message) + protected function message($message) { if ($this->debug) { echo $message; @@ -830,7 +809,6 @@ class Zimbra // end message - /** * soapRequest * @@ -843,10 +821,10 @@ class Zimbra * @param boolean $footer * @return string $response */ - protected function soapRequest ($body, $header = false, $connecting = false) + protected function soapRequest($body, $header = false, $connecting = false) { - if (! $connecting && ! $this->_connected) { - throw new Exception( 'zimbra.class: soapRequest called without a connection to Zimbra server' ); + if (!$connecting && !$this->_connected) { + throw new Exception('zimbra.class: soapRequest called without a connection to Zimbra server'); } if ($header == false) { @@ -860,31 +838,30 @@ class Zimbra ' . $header . ' ' . $body . ' '; - $this->message( 'SOAP message:' ); + $this->message('SOAP message:'); - curl_setopt( $this->_curl, CURLOPT_POSTFIELDS, $soap_message ); + curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $soap_message); - if (! ($response = curl_exec( $this->_curl ))) { - $this->error = 'ERROR: curl_exec - (' . curl_errno( $this->_curl ) . ') ' . curl_error( $this->_curl ); + if (!($response = curl_exec($this->_curl))) { + $this->error = 'ERROR: curl_exec - (' . curl_errno($this->_curl) . ') ' . curl_error($this->_curl); return false; - } elseif (strpos( $response, '' ) !== false) { - $error_code = $this->extractErrorCode( $response ); + } elseif (strpos($response, '') !== false) { + $error_code = $this->extractErrorCode($response); $this->error = 'ERROR: ' . $error_code . ':'; - $this->message( $this->error ); - $aError = array ('error' => $error_code + $this->message($this->error); + $aError = array('error' => $error_code ); return $aError; //return false; } - $this->message( 'SOAP response:

' ); + $this->message('SOAP response:

'); - $this->_num_soap_calls ++; + $this->_num_soap_calls++; return $response; } // end soapRequest - /** * getNumSOAPCalls * @@ -894,14 +871,13 @@ class Zimbra * @access public * @return int $this->_num_soap_calls */ - public function getNumSOAPCalls () + public function getNumSOAPCalls() { return $this->_num_soap_calls; } // end getNumSOAPCalls - /** * makeXMLTree * @@ -912,45 +888,45 @@ class Zimbra * @param string $data data to be built into an array * @return array $ret */ - protected function makeXMLTree ($data) + protected function makeXMLTree($data) { // create parser $parser = xml_parser_create(); - xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 ); - xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 ); - xml_parse_into_struct( $parser, $data, $values, $tags ); - xml_parser_free( $parser ); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); + xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); + xml_parse_into_struct($parser, $data, $values, $tags); + xml_parser_free($parser); // we store our path here - $hash_stack = array (); + $hash_stack = array(); // this is our target - $ret = array (); + $ret = array(); foreach ($values as $key => $val) { switch ($val['type']) { case 'open': - array_push( $hash_stack, $val['tag'] ); - if (isset( $val['attributes'] )) { - $ret = $this->composeArray( $ret, $hash_stack, $val['attributes'] ); + array_push($hash_stack, $val['tag']); + if (isset($val['attributes'])) { + $ret = $this->composeArray($ret, $hash_stack, $val['attributes']); } else { - $ret = $this->composeArray( $ret, $hash_stack ); + $ret = $this->composeArray($ret, $hash_stack); } break; case 'close': - array_pop( $hash_stack ); + array_pop($hash_stack); break; case 'complete': - array_push( $hash_stack, $val['tag'] ); - $ret = $this->composeArray( $ret, $hash_stack, $val['value'] ); - array_pop( $hash_stack ); + array_push($hash_stack, $val['tag']); + $ret = $this->composeArray($ret, $hash_stack, $val['value']); + array_pop($hash_stack); // handle attributes - if (isset( $val['attributes'] )) { + if (isset($val['attributes'])) { foreach ($val['attributes'] as $a_k => $a_v) { $hash_stack[] = $val['tag'] . '_attribute_' . $a_k; - $ret = $this->composeArray( $ret, $hash_stack, $a_v ); - array_pop( $hash_stack ); + $ret = $this->composeArray($ret, $hash_stack, $a_v); + array_pop($hash_stack); } } break; @@ -961,7 +937,6 @@ class Zimbra // end makeXMLTree - /** * &composeArray * @@ -974,19 +949,19 @@ class Zimbra * @param array $value * @return array $array */ - private function &composeArray ($array, $elements, $value = array()) + private function &composeArray($array, $elements, $value = array()) { global $XML_LIST_ELEMENTS; // get current element - $element = array_shift( $elements ); + $element = array_shift($elements); // does the current element refer to a list - if (sizeof( $elements ) > 0) { - $array[$element][sizeof( $array[$element] ) - 1] = &$this->composeArray( $array[$element][sizeof( $array[$element] ) - 1], $elements, $value ); + if (sizeof($elements) > 0) { + $array[$element][sizeof($array[$element]) - 1] = &$this->composeArray($array[$element][sizeof($array[$element]) - 1], $elements, $value); } else { // if (is_array($value)) - $array[$element][sizeof( $array[$element] )] = $value; + $array[$element][sizeof($array[$element])] = $value; } return $array; @@ -994,7 +969,6 @@ class Zimbra // end composeArray - /** * noop * @@ -1004,9 +978,9 @@ class Zimbra * @access public * @return string xml response from the noop */ - public function noop () + public function noop() { - return $this->soapRequest( '' ); + return $this->soapRequest(''); } /** @@ -1023,9 +997,9 @@ class Zimbra * * */ - public function addAppointment ($serializeOp1) + public function addAppointment($serializeOp1) { - $unserializeOp1 = unserialize( $serializeOp1 ); + $unserializeOp1 = unserialize($serializeOp1); $username = $unserializeOp1['username']; $subject = $unserializeOp1['subject']; @@ -1044,17 +1018,17 @@ class Zimbra $ptst = $unserializeOp1['ptst']; $dateFormat = $allDay == "1" ? "Ymd" : "Ymd\THis"; - $startDate = date( $dateFormat, strtotime( $unserializeOp1['startDate'] ) ); - $endDate = date( $dateFormat, strtotime( $unserializeOp1['endDate'] ) ); + $startDate = date($dateFormat, strtotime($unserializeOp1['startDate'])); + $endDate = date($dateFormat, strtotime($unserializeOp1['endDate'])); $timeZone = $allDay == "1" ? "" : $unserializeOp1['tz']; - $explodeEmail = explode( ';', $userEmail ); - $explodeFriendlyName = explode( ';', $atFriendlyName ); - $countExplodeEmail = count( $explodeEmail ); + $explodeEmail = explode(';', $userEmail); + $explodeFriendlyName = explode(';', $atFriendlyName); + $countExplodeEmail = count($explodeEmail); $soap = ' ' . $subject . ''; - for ($i = 0; $i < $countExplodeEmail; $i ++) { + for ($i = 0; $i < $countExplodeEmail; $i++) { $soap .= ''; } $soap .= ' @@ -1062,7 +1036,7 @@ class Zimbra '; - for ($i = 0; $i < $countExplodeEmail; $i ++) { + for ($i = 0; $i < $countExplodeEmail; $i++) { $soap .= ''; } $soap .= ' @@ -1077,9 +1051,9 @@ class Zimbra '; //G::pr($soap);die; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['CreateAppointmentResponse']; } else { @@ -1089,7 +1063,6 @@ class Zimbra // end addAppointments - /** * addTask * @@ -1100,9 +1073,9 @@ class Zimbra * @param array $options array of options to apply to retrieval from calendar * @return array associative array of appointments */ - public function addTask ($serializeOp1) + public function addTask($serializeOp1) { - $unserializeOp1 = unserialize( $serializeOp1 ); + $unserializeOp1 = unserialize($serializeOp1); $subject = $unserializeOp1['subject']; $taskName = $unserializeOp1['taskName']; @@ -1112,7 +1085,7 @@ class Zimbra $allDay = $unserializeOp1['allDay']; $class = $unserializeOp1['class']; $location = $unserializeOp1['location']; - $dueDate = date( "Ymd", strtotime( $unserializeOp1['dueDate'] ) ); + $dueDate = date("Ymd", strtotime($unserializeOp1['dueDate'])); $status = $unserializeOp1['status']; $percent = $unserializeOp1['percent']; @@ -1138,10 +1111,10 @@ class Zimbra '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); //return $array['soap:Envelope'][0]['soap:Body'][0]['BatchResponse'][0]['CreateTaskRequest'][0]['appt']; return $array['soap:Envelope'][0]['soap:Body'][0]['CreateTaskResponse']; @@ -1152,7 +1125,6 @@ class Zimbra // end addTask - /** * addContacts * @@ -1167,9 +1139,9 @@ class Zimbra * * */ - public function addContacts ($serializeOp1) + public function addContacts($serializeOp1) { - $unserializeOp1 = unserialize( $serializeOp1 ); + $unserializeOp1 = unserialize($serializeOp1); $firstName = $unserializeOp1['firstName']; $lastName = $unserializeOp1['lastName']; @@ -1186,9 +1158,9 @@ class Zimbra '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['CreateContactResponse']; } else { @@ -1211,10 +1183,9 @@ class Zimbra * * */ - - public function addFolder ($serializeOp1) + public function addFolder($serializeOp1) { - $unserializeOp1 = unserialize( $serializeOp1 ); + $unserializeOp1 = unserialize($serializeOp1); $folderName = $unserializeOp1['folderName']; $folderColor = $unserializeOp1['color']; @@ -1224,9 +1195,9 @@ class Zimbra '; - $response = $this->soapRequest( $soap ); + $response = $this->soapRequest($soap); if ($response) { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['CreateFolderResponse']; } else { @@ -1249,8 +1220,7 @@ class Zimbra * * */ - - public function upload ($folderId, $UploadId, $fileVersion = '', $docId = '') + public function upload($folderId, $UploadId, $fileVersion = '', $docId = '') { if ($fileVersion == '' && $docId == '') { $soap = ' @@ -1266,13 +1236,13 @@ class Zimbra '; } - $response = $this->soapRequest( $soap ); - if (is_array( $response )) { - if (isset( $response['error'] )) { + $response = $this->soapRequest($soap); + if (is_array($response)) { + if (isset($response['error'])) { return $response; } } else { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['SaveDocumentResponse']; } @@ -1280,7 +1250,6 @@ class Zimbra // end uploadDocument - /** * getDocId * @@ -1295,19 +1264,19 @@ class Zimbra * * */ - public function getDocId ($folderId, $fileName) + public function getDocId($folderId, $fileName) { $soap = ' '; - $response = $this->soapRequest( $soap ); - if (is_array( $response )) { + $response = $this->soapRequest($soap); + if (is_array($response)) { if ($response['error']) { return false; } } else { - $array = $this->makeXMLTree( $response ); + $array = $this->makeXMLTree($response); return $array['soap:Envelope'][0]['soap:Body'][0]['GetItemResponse'][0]; } @@ -1321,7 +1290,6 @@ class Zimbra // I don't know how to make usort calls to internal OO functions // if someone knows how, please fix this :) - /** * zimbra_startSort * @@ -1333,7 +1301,7 @@ class Zimbra * @param array $task_b * @return int (($task_a['dueDate']-$task_a['dur']) < ($task_b['dueDate']-$task_b['dur'])) ? -1 : 1 */ -function zimbra_startSort ($task_a, $task_b) +function zimbra_startSort($task_a, $task_b) { if (($task_a['dueDate'] - $task_a['dur']) == ($task_b['dueDate'] - $task_b['dur'])) { return ($task_a['name'] < $task_b['name']) ? - 1 : 1; @@ -1352,7 +1320,7 @@ function zimbra_startSort ($task_a, $task_b) * @param array $task_b * @return int ($task_a['dueDate'] < $task_b['dueDate']) ? -1 : 1 */ -function zimbra_dueSort ($task_a, $task_b) +function zimbra_dueSort($task_a, $task_b) { if ($task_a['dueDate'] == $task_b['dueDate']) { return ($task_a['name'] < $task_b['name']) ? - 1 : 1; @@ -1371,7 +1339,7 @@ function zimbra_dueSort ($task_a, $task_b) * @param array $task_b * @return int ($task_a['name'] < $task_b['name']) ? -1 : 1 */ -function zimbra_nameSort ($task_a, $task_b) +function zimbra_nameSort($task_a, $task_b) { if ($task_a['name'] == $task_b['name']) { return 0; diff --git a/workflow/engine/classes/triggers/class.pmTrSharepoint.php b/workflow/engine/classes/triggers/class.pmTrSharepoint.php index bdeef6bb7..4e570e13b 100755 --- a/workflow/engine/classes/triggers/class.pmTrSharepoint.php +++ b/workflow/engine/classes/triggers/class.pmTrSharepoint.php @@ -3,7 +3,7 @@ /** * class.pmTrSharepoint.php */ -G::LoadSystem( "soapNtlm" ); +G::LoadSystem("soapNtlm"); class wscaller { @@ -14,33 +14,32 @@ class wscaller private $auth; private $clientStream; - function setAuthUser ($auth) + public function setAuthUser($auth) { //print "
- auth Setup"; $this->auth = $auth; } - function setwsdlurl ($wsdl) + public function setwsdlurl($wsdl) { //print "
- wsdl Setup"; $this->wsdlurl = $wsdl; //var_dump($wsdl); } - function loadSOAPClient () + public function loadSOAPClient() { try { // we unregister the current HTTP wrapper - stream_wrapper_unregister( 'http' ); + stream_wrapper_unregister('http'); // we register the new HTTP wrapper //$client = new PMServiceProviderNTLMStream($this->auth); - PMServiceProviderNTLMStream::setAuthStream( $this->auth ); - stream_wrapper_register( 'http', 'PMServiceProviderNTLMStream' ) or die( "Failed to register protocol" ); + PMServiceProviderNTLMStream::setAuthStream($this->auth); + stream_wrapper_register('http', 'PMServiceProviderNTLMStream') or die("Failed to register protocol"); // $this->client = new PMServiceNTLMSoapClient($this->wsdlurl, array('trace' => 1, 'auth' => $this->auth));// Hugo's code - $this->client = new PMServiceNTLMSoapClient( $this->wsdlurl, array ('trace' => 1 - ) ); // Ankit's Code - $this->client->setAuthClient( $this->auth ); + $this->client = new PMServiceNTLMSoapClient($this->wsdlurl, array('trace' => 1)); // Ankit's Code + $this->client->setAuthClient($this->auth); return true; } catch (Exception $e) { echo $e; @@ -48,30 +47,29 @@ class wscaller } } - function callWsMethod ($methodName, $paramArray) + public function callWsMethod($methodName, $paramArray) { try { if ($methodName == 'DeleteDws' || $methodName == 'GetListCollection') { $strResult = ""; - $strResult = $this->client->$methodName( $paramArray = "" ); + $strResult = $this->client->$methodName($paramArray = ""); return $strResult; } else { $strResult = ""; - $strResult = $this->client->$methodName( $paramArray ); + $strResult = $this->client->$methodName($paramArray); return $strResult; } } catch (SoapFault $fault) { echo 'Fault code: ' . $fault->faultcode; echo 'Fault string: ' . $fault->faultstring; } - stream_wrapper_restore( 'http' ); + stream_wrapper_restore('http'); } } class DestinationUrlCollection { - public $string; } @@ -88,146 +86,141 @@ class FieldInformationCollection class pmTrSharepointClass { - function __construct ($server, $auth) + + public function __construct($server, $auth) { - set_include_path( PATH_PLUGINS . 'pmTrSharepoint' . PATH_SEPARATOR . get_include_path() ); + set_include_path(PATH_PLUGINS . 'pmTrSharepoint' . PATH_SEPARATOR . get_include_path()); $this->server = $server; $this->auth = $auth; $this->dwsObj = new wscaller(); - $this->dwsObj->setAuthUser( $this->auth ); + $this->dwsObj->setAuthUser($this->auth); } - function createDWS ($name, $users, $title, $documents) + public function createDWS($name, $users, $title, $documents) { //print "
- Method createDWS"; - $this->dwsObj->setwsdlurl( $this->server . "/_vti_bin/Dws.asmx?WSDL" ); + $this->dwsObj->setwsdlurl($this->server . "/_vti_bin/Dws.asmx?WSDL"); $this->dwsObj->loadSOAPClient(); - $paramArray = array ('name' => '','users' => '','title' => $name,'documents' => '' - ); + $paramArray = array('name' => '', 'users' => '', 'title' => $name, 'documents' => ''); $methodName = 'CreateDws'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); $xml = $result->CreateDwsResult; // in Result we get string in Xml format - $xmlNew = simplexml_load_string( $xml ); // used to parse string to xml - $xmlArray = @G::json_decode( @G::json_encode( $xmlNew ), 1 ); // used to convert Objects to array + $xmlNew = simplexml_load_string($xml); // used to parse string to xml + $xmlArray = @G::json_decode(@G::json_encode($xmlNew), 1); // used to convert Objects to array $dwsUrl = $xmlArray['Url']; return "Dws with following Url is created:$dwsUrl"; /* $newResult = $result->CreateDwsResult; - $needleStart=''; - $urlStartPos = strpos($newResult, $needleStart); - $urlStart = $urlStartPos + 5; - $needleEnd=''; - $urlEndPos = strpos($newResult, $needleEnd); - $length = $urlEndPos - $urlStart; - $result = substr($newResult, $urlStart, $length); - return $result; */ + $needleStart=''; + $urlStartPos = strpos($newResult, $needleStart); + $urlStart = $urlStartPos + 5; + $needleEnd=''; + $urlEndPos = strpos($newResult, $needleEnd); + $length = $urlEndPos - $urlStart; + $result = substr($newResult, $urlStart, $length); + return $result; */ } - function deleteDWS ($dwsname) + public function deleteDWS($dwsname) { //print "
- Method createDWS"; $url = $this->server . "/" . $dwsname . "/_vti_bin/Dws.asmx?WSDL"; - $this->dwsObj->setwsdlurl( $url ); + $this->dwsObj->setwsdlurl($url); $this->dwsObj->loadSOAPClient(); $paramArray = null; $methodName = 'DeleteDws'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray = null ); - var_dump( $result ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray = null); + var_dump($result); return $result; - } - function createFolderDWS ($dwsname, $dwsFolderName) + public function createFolderDWS($dwsname, $dwsFolderName) { //print "
- Method createDWS"; - $this->dwsObj->setwsdlurl( $this->server . "/" . $dwsname . "/_vti_bin/Dws.asmx?WSDL" ); + $this->dwsObj->setwsdlurl($this->server . "/" . $dwsname . "/_vti_bin/Dws.asmx?WSDL"); $this->dwsObj->loadSOAPClient(); $url = "Shared Documents/$dwsFolderName"; - $paramArray = array ('url' => $url - ); + $paramArray = array('url' => $url); # $paramArray = array('name' => '', 'users' => '', 'title' => $name, 'documents' => ''); $methodName = 'CreateFolder'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); - var_dump( $result ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); + var_dump($result); return $result; } - function deleteFolderDWS ($dwsname, $folderName) + public function deleteFolderDWS($dwsname, $folderName) { //print "
- Method createDWS"; - $this->dwsObj->setwsdlurl( $this->server . "/" . $dwsname . "/_vti_bin/Dws.asmx?WSDL" ); + $this->dwsObj->setwsdlurl($this->server . "/" . $dwsname . "/_vti_bin/Dws.asmx?WSDL"); $this->dwsObj->loadSOAPClient(); $url = "Shared Documents/$folderName"; - $paramArray = array ('url' => $url - ); + $paramArray = array('url' => $url); # $paramArray = array('name' => '', 'users' => '', 'title' => $name, 'documents' => ''); $methodName = 'DeleteFolder'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); - var_dump( $result ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); + var_dump($result); return $result; } - function findDWSdoc ($dwsname, $guid) + public function findDWSdoc($dwsname, $guid) { //print "
- Method createDWS"; - $this->dwsObj->setwsdlurl( $this->server . $dwsName . "/_vti_bin/Dws.asmx?WSDL" ); + $this->dwsObj->setwsdlurl($this->server . $dwsName . "/_vti_bin/Dws.asmx?WSDL"); $this->dwsObj->loadSOAPClient(); - $paramArray = array ('id' => '$guid' - ); + $paramArray = array('id' => '$guid'); $methodName = 'FindDwsDoc'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); - var_dump( $result ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); + var_dump($result); } - function getDWSData ($newFileName, $dwsname, $lastUpdate) + public function getDWSData($newFileName, $dwsname, $lastUpdate) { //print "
- Method getDWSData
"; $url = $this->server . "/" . $dwsname . "/_vti_bin/Dws.asmx?WSDL"; - $this->dwsObj->setwsdlurl( $url ); + $this->dwsObj->setwsdlurl($url); if ($this->dwsObj->loadSOAPClient()) { $doc = "Shared Documents"; - $paramArray = array ('document' => '','lastUpdate' => '' - ); + $paramArray = array('document' => '', 'lastUpdate' => ''); $methodName = 'GetDwsData'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); - var_dump( $result ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); + var_dump($result); $sResult = $result->GetDwsDataResult; /* $xmlNew = simplexml_load_string($sResult);// used to parse string to xml $xmlArray = @G::json_decode(@G::json_encode($xmlNew),1);// used to convert Objects to array */ - $serializeResult = serialize( $sResult ); // serializing the Array for Returning. - var_dump( $serializeResult ); + $serializeResult = serialize($sResult); // serializing the Array for Returning. + var_dump($serializeResult); return $serializeResult; } else { return "The enter the Correct Dws Name"; } } - function uploadDocumentDWS ($dwsname, $folderName, $sourceUrl, $filename) + public function uploadDocumentDWS($dwsname, $folderName, $sourceUrl, $filename) { //print "
- Method createDWS"; $url = $this->server . "/" . $dwsname . "/_vti_bin/Copy.asmx?WSDL"; - $this->dwsObj->setwsdlurl( $url ); + $this->dwsObj->setwsdlurl($url); $this->dwsObj->loadSOAPClient(); $destUrlObj = new DestinationUrlCollection(); @@ -244,17 +237,17 @@ class pmTrSharepointClass $fieldInfoCollObj->FieldInformation = $fieldInfoObj; $imgfile = $sourceUrl . "/" . $filename; - $filep = fopen( $imgfile, "r" ); - $fileLength = filesize( $imgfile ); - $content = fread( $filep, $fileLength ); + $filep = fopen($imgfile, "r"); + $fileLength = filesize($imgfile); + $content = fread($filep, $fileLength); //$content = base64_encode($content); - $paramArray = array ('SourceUrl' => $imgfile,'DestinationUrls' => $destUrlObj,'Fields' => $fieldInfoCollObj,'Stream' => $content + $paramArray = array('SourceUrl' => $imgfile, 'DestinationUrls' => $destUrlObj, 'Fields' => $fieldInfoCollObj, 'Stream' => $content ); $methodName = 'CopyIntoItems'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); - var_dump( $result ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); + var_dump($result); $newResult = $result->Results->CopyResult->ErrorCode; if ($newResult == 'Success') { return "The document has been uploaded Successfully"; @@ -263,104 +256,100 @@ class pmTrSharepointClass } } - function getDWSMetaData ($newFileName, $dwsname, $id) + public function getDWSMetaData($newFileName, $dwsname, $id) { //print "
- Method createDWS"; $url = $this->server . "/" . $dwsname . "/_vti_bin/Dws.asmx?WSDL"; - $this->dwsObj->setwsdlurl( $url ); + $this->dwsObj->setwsdlurl($url); $this->dwsObj->loadSOAPClient(); $doc = "Shared Documents/$newFileName"; - $paramArray = array ('document' => $doc,'id' => '','minimal' => false - ); + $paramArray = array('document' => $doc, 'id' => '', 'minimal' => false); $methodName = 'GetDwsMetaData'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); $sResult = $result->GetDwsMetaDataResult; - $errorReturn = strpos( $sResult, "Error" ); - if (isset( $sResult ) && ! $errorReturn) { - $serializeResult = serialize( $sResult ); // serializing the Array for Returning. - var_dump( $serializeResult ); + $errorReturn = strpos($sResult, "Error"); + if (isset($sResult) && !$errorReturn) { + $serializeResult = serialize($sResult); // serializing the Array for Returning. + var_dump($serializeResult); return $serializeResult; } else { return $sResult; } } - function getDWSDocumentVersions ($newFileName, $dwsname) + public function getDWSDocumentVersions($newFileName, $dwsname) { //print "
- Method createDWS"; - $this->dwsObj->setwsdlurl( $this->server . "/" . $dwsname . "/_vti_bin/Versions.asmx?WSDL" ); + $this->dwsObj->setwsdlurl($this->server . "/" . $dwsname . "/_vti_bin/Versions.asmx?WSDL"); $this->dwsObj->loadSOAPClient(); $doc = "Shared Documents/$newFileName"; - $paramArray = array ('fileName' => $doc - ); + $paramArray = array('fileName' => $doc); $methodName = 'GetVersions'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); - var_dump( $result ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); + var_dump($result); return $result; } - function deleteDWSDocVersion ($newFileName, $dwsname, $versionNum) + public function deleteDWSDocVersion($newFileName, $dwsname, $versionNum) { //print "
- Method createDWS"; - $this->dwsObj->setwsdlurl( $this->server . "/" . $dwsname . "/_vti_bin/Versions.asmx?WSDL" ); + $this->dwsObj->setwsdlurl($this->server . "/" . $dwsname . "/_vti_bin/Versions.asmx?WSDL"); $this->dwsObj->loadSOAPClient(); $doc = "Shared Documents/$newFileName"; - $paramArray = array ('fileName' => $doc,'fileVersion' => $versionNum - ); + $paramArray = array('fileName' => $doc, 'fileVersion' => $versionNum); $methodName = 'DeleteVersion'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); if ($result) { $sResult = $result->DeleteVersionResult->any; - $xmlNew = simplexml_load_string( $sResult ); // used to parse string to xml - $xmlArray = @G::json_decode( @G::json_encode( $xmlNew ), 1 ); // used to convert Objects to array - $versionCount = count( $xmlArray['result'] ); + $xmlNew = simplexml_load_string($sResult); // used to parse string to xml + $xmlArray = @G::json_decode(@G::json_encode($xmlNew), 1); // used to convert Objects to array + $versionCount = count($xmlArray['result']); if ($versionCount > 1) { - for ($i = 0; $i < $versionCount; $i ++) { + for ($i = 0; $i < $versionCount; $i++) { $version[] = $xmlArray['result'][$i]['@attributes']['version']; } } else { $version[] = $xmlArray['result']['@attributes']['version']; } - $serializeResult = serialize( $version ); // serializing the Array for Returning. - var_dump( $serializeResult ); + $serializeResult = serialize($version); // serializing the Array for Returning. + var_dump($serializeResult); return $serializeResult; } else { return "The given Version could not be deleted."; } } - function deleteAllDWSDocVersion ($newFileName, $dwsname) + public function deleteAllDWSDocVersion($newFileName, $dwsname) { //print "
- Method createDWS"; - $this->dwsObj->setwsdlurl( $this->server . "/" . $dwsname . "/_vti_bin/Versions.asmx?WSDL" ); + $this->dwsObj->setwsdlurl($this->server . "/" . $dwsname . "/_vti_bin/Versions.asmx?WSDL"); $this->dwsObj->loadSOAPClient(); $doc = "Shared Documents/$newFileName"; - $paramArray = array ('fileName' => $doc - ); + $paramArray = array('fileName' => $doc); $methodName = 'DeleteAllVersions'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); if ($result) { $xml = $result->DeleteAllVersionsResult->any; // in Result we get string in Xml format - $xmlNew = simplexml_load_string( $xml ); // used to parse string to xml - $xmlArray = @G::json_decode( @G::json_encode( $xmlNew ), 1 ); // used to convert Objects to array + $xmlNew = simplexml_load_string($xml); // used to parse string to xml + $xmlArray = @G::json_decode(@G::json_encode($xmlNew), 1); // used to convert Objects to array $latestVersion = $xmlArray['result']['@attributes']['version']; return "All Versions are Deleted, except the latest i.e $latestVersion"; } else { @@ -368,61 +357,59 @@ class pmTrSharepointClass } } - function getDWSFolderItems ($dwsname, $strFolderUrl) + public function getDWSFolderItems($dwsname, $strFolderUrl) { $pmTrSharepointClassObj = new pmTrSharepointClass(); //print "
- Method getDWSFolderItems"; $url = $this->server . "/" . $dwsname . "/_vti_bin/SiteData.asmx?WSDL"; - $this->dwsObj->setwsdlurl( $this->server . "/" . $dwsname . "/_vti_bin/SiteData.asmx?WSDL" ); + $this->dwsObj->setwsdlurl($this->server . "/" . $dwsname . "/_vti_bin/SiteData.asmx?WSDL"); $this->dwsObj->loadSOAPClient(); #$doc = "Shared Documents/$newFileName"; - $paramArray = array ('strFolderUrl' => $strFolderUrl - ); + $paramArray = array('strFolderUrl' => $strFolderUrl); $methodName = 'EnumerateFolder'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); //$newResult = $result->vUrls->_sFPUrl->Url; - if (isset( $result->vUrls->_sFPUrl->Url )) { - $returnContent = $pmTrSharepointClassObj->getFolderUrlContent( $result->vUrls->_sFPUrl->Url ); - $serializeResult = serialize( $returnContent ); + if (isset($result->vUrls->_sFPUrl->Url)) { + $returnContent = $pmTrSharepointClassObj->getFolderUrlContent($result->vUrls->_sFPUrl->Url); + $serializeResult = serialize($returnContent); return $serializeResult; - } elseif (isset( $result->vUrls->_sFPUrl )) { - $itemCount = count( $result->vUrls->_sFPUrl ); - for ($i = 0; $i < $itemCount; $i ++) { + } elseif (isset($result->vUrls->_sFPUrl)) { + $itemCount = count($result->vUrls->_sFPUrl); + for ($i = 0; $i < $itemCount; $i++) { $aObjects = $result->vUrls->_sFPUrl[$i]->IsFolder; //$booleanStatus = $aObjects[$i]->IsFolder; if ($aObjects) { $listArr = $result->vUrls->_sFPUrl[$i]->Url; - $returnContent[] = $pmTrSharepointClassObj->getFolderUrlContent( $listArr ) . "(Is a Folder)"; + $returnContent[] = $pmTrSharepointClassObj->getFolderUrlContent($listArr) . "(Is a Folder)"; } else { $listArr = $result->vUrls->_sFPUrl[$i]->Url; - $returnContent[] = $pmTrSharepointClassObj->getFolderUrlContent( $listArr ) . "(Is a File)"; + $returnContent[] = $pmTrSharepointClassObj->getFolderUrlContent($listArr) . "(Is a File)"; } } - $serializeResult = serialize( $returnContent ); + $serializeResult = serialize($returnContent); return $serializeResult; } return "There is some error"; } - function downloadDocumentDWS ($dwsname, $fileName, $fileLocation) + public function downloadDocumentDWS($dwsname, $fileName, $fileLocation) { //print "
- Method createDWS"; $url = $this->server . "/" . $dwsname . "/_vti_bin/Copy.asmx?WSDL"; - $this->dwsObj->setwsdlurl( $url ); + $this->dwsObj->setwsdlurl($url); $this->dwsObj->loadSOAPClient(); $CompleteUrl = $this->server . "/" . $dwsname . "/Shared Documents/" . $fileName; - $paramArray = array ('Url' => $CompleteUrl - ); + $paramArray = array('Url' => $CompleteUrl); $methodName = 'GetItem'; - $result = $this->dwsObj->callWsMethod( $methodName, $paramArray ); + $result = $this->dwsObj->callWsMethod($methodName, $paramArray); $newResult = $result->Stream; //$latestResult = base64_decode($newResult); @@ -431,27 +418,27 @@ class pmTrSharepointClass * In the Below line of code, we are coping the files at our local Directory using the php file methods. */ $imgfile = $fileLocation . "/" . $fileName; - $filep = fopen( $imgfile, 'w' ); + $filep = fopen($imgfile, 'w'); //$content = fwrite($filep, $latestResult); - $content = fwrite( $filep, $newResult ); + $content = fwrite($filep, $newResult); return $content; } - function getFolderUrlContent ($newResult) + public function getFolderUrlContent($newResult) { $needleStart = '/'; - $needleCount = substr_count( $newResult, $needleStart ); + $needleCount = substr_count($newResult, $needleStart); - $urlStartPos = strpos( $newResult, $needleStart ); - $urlStartPos ++; + $urlStartPos = strpos($newResult, $needleStart); + $urlStartPos++; if ($needleCount == '2') { - $newResultPos = strpos( $newResult, $needleStart, $urlStartPos ); - $newResultPos ++; - $actualResult = substr( $newResult, $newResultPos ); + $newResultPos = strpos($newResult, $needleStart, $urlStartPos); + $newResultPos++; + $actualResult = substr($newResult, $newResultPos); return $actualResult; } else { - $actualResult = substr( $newResult, $urlStartPos ); + $actualResult = substr($newResult, $urlStartPos); return $actualResult; } } diff --git a/workflow/engine/methods/processes/clases_Test.php b/workflow/engine/methods/processes/clases_Test.php index 3077414d7..f244bf56f 100755 --- a/workflow/engine/methods/processes/clases_Test.php +++ b/workflow/engine/methods/processes/clases_Test.php @@ -1,4 +1,5 @@ executeDerivation($frm); - die; +$frm['APP_UID'] = '44706CAEA62AE0'; +$frm['DEL_INDEX'] = '1'; +$obj->executeDerivation($frm); +die; /* derivando el primer caso */ /* CREANDO UN NUEVO CASO */ /* - $frm['TAS_UID'] ='246F2CD0D4C79E'; - $frm['USER_UID'] ='00000000000000000000000000000001'; - $obj->startCase($frm); - die; + $frm['TAS_UID'] ='246F2CD0D4C79E'; + $frm['USER_UID'] ='00000000000000000000000000000001'; + $obj->startCase($frm); + die; -*/ + */ /* CREANDO UN NUEVO CASO END */ - /** Application */ - - //$frm['PRO_UID'] ='ssddsfse32dd23s'; -/* $frm['APP_PARENT'] ='135165FDS54654FD'; - $frm['PRO_UID'] ='SSDDSFSE32DD23S'; - $frm['APP_STATUS'] ='DRAFT'; - $frm['APP_PROC_STATUS']='TEST'; - $frm['APP_PARALLEL']='NO'; - $frm['APP_TITLE']='MAUI'; -*/ +/** Application */ +//$frm['PRO_UID'] ='ssddsfse32dd23s'; +/* $frm['APP_PARENT'] ='135165FDS54654FD'; + $frm['PRO_UID'] ='SSDDSFSE32DD23S'; + $frm['APP_STATUS'] ='DRAFT'; + $frm['APP_PROC_STATUS']='TEST'; + $frm['APP_PARALLEL']='NO'; + $frm['APP_TITLE']='MAUI'; + */ -/* $translation2 = $obj->generateFileTranslation(); - print_r($translation2);*/ +/* $translation2 = $obj->generateFileTranslation(); + print_r($translation2); */ - /*step */ - /*$frm['TAS_UID'] ='sss'; - $frm['STEP_NAME_OBJ'] ='DYNA'; -*/ - /*ReqDynaform */ -/* $frm['REQ_DYN_TITLE'] ='sss'; - $frm['REQ_DYN_DESCRIPTION'] ='eee'; - $frm['REQ_DYN_FILENAME'] ='33'; - $frm['REQ_DYN_UID']='346BB3D981FD9E';*/ +/* step */ +/* $frm['TAS_UID'] ='sss'; + $frm['STEP_NAME_OBJ'] ='DYNA'; + */ +/* ReqDynaform */ +/* $frm['REQ_DYN_TITLE'] ='sss'; + $frm['REQ_DYN_DESCRIPTION'] ='eee'; + $frm['REQ_DYN_FILENAME'] ='33'; + $frm['REQ_DYN_UID']='346BB3D981FD9E'; */ - /*ReqDocument */ -/* $frm['REQ_DOC_TITLE'] ='titulosssss'; - $frm['REQ_DOC_DESCRIPTION'] ='descripcions'; - //$frm['REQ_DOC_ORIGINAL'] ='1'; - $frm['REQ_DOC_UID']='646BB2F6BB2037'; -*/ - /*Task*/ - /*$frm['TAS_UID']='846BB16A0D9C7A'; - $frm['PRO_UID']='746B67A9CC9A0E'; - //$frm['TAS_TYPE'] ='332'; - $frm['TAS_TITLE'] ='titulito MAUI13ss'; - $frm['TAS_DESCRIPTION'] ='Descripción MAUI13'; - $frm['TAS_DEF_TITLE'] = "13"; - $frm['TAS_DEF_DESCRIPTION'] = "23"; - $frm['TAS_DEF_PROC_CODE'] = "33"; - $frm['TAS_DEF_MESSAGE'] = "43";*/ +/* ReqDocument */ +/* $frm['REQ_DOC_TITLE'] ='titulosssss'; + $frm['REQ_DOC_DESCRIPTION'] ='descripcions'; + //$frm['REQ_DOC_ORIGINAL'] ='1'; + $frm['REQ_DOC_UID']='646BB2F6BB2037'; + */ +/* Task */ +/* $frm['TAS_UID']='846BB16A0D9C7A'; + $frm['PRO_UID']='746B67A9CC9A0E'; + //$frm['TAS_TYPE'] ='332'; + $frm['TAS_TITLE'] ='titulito MAUI13ss'; + $frm['TAS_DESCRIPTION'] ='Descripci�n MAUI13'; + $frm['TAS_DEF_TITLE'] = "13"; + $frm['TAS_DEF_DESCRIPTION'] = "23"; + $frm['TAS_DEF_PROC_CODE'] = "33"; + $frm['TAS_DEF_MESSAGE'] = "43"; */ - /** SwimlanesElements*/ +/** SwimlanesElements */ /* - $frm['PRO_UID'] ='ssddsfse32dd23s'; - $frm['SWI_TEXT'] ='maui'; - $frm['SWI_TYPE'] ='TEXT'; - $frm['SWI_X'] ='2'; - $frm['SWI_UID']='746BB217D7805E'; + $frm['PRO_UID'] ='ssddsfse32dd23s'; + $frm['SWI_TEXT'] ='maui'; + $frm['SWI_TYPE'] ='TEXT'; + $frm['SWI_X'] ='2'; + $frm['SWI_UID']='746BB217D7805E'; -*/ - /** Route */ + */ +/** Route */ /* - $frm['PRO_UID'] ='ssddsfse32dd23s'; - $frm['TAS_UID'] ='cooo'; - $frm['ROU_NEXT_TASK'] ='654FD65S4F65SD'; - $frm['ROU_SOURCEANCHOR'] ='2'; - $frm['ROU_UID']='746BB8411A9C14'; -*/ + $frm['PRO_UID'] ='ssddsfse32dd23s'; + $frm['TAS_UID'] ='cooo'; + $frm['ROU_NEXT_TASK'] ='654FD65S4F65SD'; + $frm['ROU_SOURCEANCHOR'] ='2'; + $frm['ROU_UID']='746BB8411A9C14'; + */ - /*PROCESS*/ - /*$frm['PRO_UID'] = '446BB1B36E17FE'; - $frm['PRO_TITLE'] = 'PERDERD'; - $frm['PRO_PARENT']='746B67A9CC9ADDDDDDDD0E';*/ +/* PROCESS */ +/* $frm['PRO_UID'] = '446BB1B36E17FE'; + $frm['PRO_TITLE'] = 'PERDERD'; + $frm['PRO_PARENT']='746B67A9CC9ADDDDDDDD0E'; */ - /** END PROCESS*/ - - /*MESSAGE*/ +/** END PROCESS */ +/* MESSAGE */ /* - $frm['PRO_UID'] = '446BB1B36E17FE'; - $frm['MESS_UID'] = '146CDAC097D35A'; - $frm['MESS_TYPE'] = 'HTMLS'; - $frm['MESS_TITLE'] = 'título del mensaje'; - $frm['MESS_DESCRIPTION'] = 'estimado SrS.'; + $frm['PRO_UID'] = '446BB1B36E17FE'; + $frm['MESS_UID'] = '146CDAC097D35A'; + $frm['MESS_TYPE'] = 'HTMLS'; + $frm['MESS_TITLE'] = 't�tulo del mensaje'; + $frm['MESS_DESCRIPTION'] = 'estimado SrS.'; - /** END MESSAGE*/ - /*STEP*/ + /** END MESSAGE */ +/* STEP */ /* - $frm['PRO_UID'] = '446BB1B36E17FE'; - $frm['TAS_UID'] = '146CDAC097D35A'; - $frm['STEP_NAME_OBJ'] = 'HTM'; - $frm['STEP_TYPE_OBJ'] = 'OUTPUT_DOCUMENT'; - $frm['STEP_UID_OBJ'] = 'estimado SrS.'; -*/ - /** END MESSAGE*/ - - /** Delegation */ - - //$frm['PRO_UID'] ='ssddsfse32dd23s'; - /*$frm['APP_UID'] ='135165FDS54654FD'; - $frm['APP_PARENT'] ='135165FDS54654FD'; - $frm['PRO_UID'] ='SSDDSFSE32DD23S'; - $frm['APP_STATUS'] ='DRAFT'; - $frm['APP_PROC_STATUS']='TEST'; - $frm['APP_PARALLEL']='NO'; - $frm['APP_TITLE']='MAUI'; + $frm['PRO_UID'] = '446BB1B36E17FE'; + $frm['TAS_UID'] = '146CDAC097D35A'; + $frm['STEP_NAME_OBJ'] = 'HTM'; + $frm['STEP_TYPE_OBJ'] = 'OUTPUT_DOCUMENT'; + $frm['STEP_UID_OBJ'] = 'estimado SrS.'; + */ +/** END MESSAGE */ +/** Delegation */ +//$frm['PRO_UID'] ='ssddsfse32dd23s'; +/* $frm['APP_UID'] ='135165FDS54654FD'; + $frm['APP_PARENT'] ='135165FDS54654FD'; + $frm['PRO_UID'] ='SSDDSFSE32DD23S'; + $frm['APP_STATUS'] ='DRAFT'; + $frm['APP_PROC_STATUS']='TEST'; + $frm['APP_PARALLEL']='NO'; + $frm['APP_TITLE']='MAUI'; - $prouid = $obj->Save ($frm); - //$obj->load('746E99F0D23189'); print_r($obj->Fields); - $obj->delete('046E99A56954AE'); + $prouid = $obj->Save ($frm); + //$obj->load('746E99F0D23189'); print_r($obj->Fields); + $obj->delete('046E99A56954AE'); -die("eliminado YA - ".$prouid); -*/ -?> \ No newline at end of file + die("eliminado YA - ".$prouid); + */ + diff --git a/workflow/engine/methods/tools/methodsPermissions.php b/workflow/engine/methods/tools/methodsPermissions.php index 255d18f19..47acdce02 100755 --- a/workflow/engine/methods/tools/methodsPermissions.php +++ b/workflow/engine/methods/tools/methodsPermissions.php @@ -1,4 +1,5 @@ AddContent( 'view', 'tools/methodsPermissions' ); +$G_PUBLISH->AddContent('view', 'tools/methodsPermissions'); -G::RenderPage( 'publish' ); +G::RenderPage('publish'); diff --git a/workflow/engine/templates/tools/methodsPermissions.php b/workflow/engine/templates/tools/methodsPermissions.php index 055df6e90..17603f896 100755 --- a/workflow/engine/templates/tools/methodsPermissions.php +++ b/workflow/engine/templates/tools/methodsPermissions.php @@ -1,10 +1,10 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., + * + * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * + * */ - G::LoadClass('tree'); - /* - * Esto no deberias borrarlo - */ - $tree = new Tree(); +G::LoadClass('tree'); +/* + * Esto no deberias borrarlo + */ +$tree = new Tree(); - reView(PATH_TRUNK,$tree); - print( $tree->render() ); +reView(PATH_TRUNK, $tree); +print( $tree->render()); - function reView($path,&$tree) - { - $tree->name = $path; - $tree->value = $path . ' '. - setHeader('Set Header','setDirHeader("'.$path.'",this);'). - selectPermissions('Set Permission','setDirPermission("'.$path.'",this);'). - selectPermissions('Remove Permission','removeDirPermission("'.$path.'",this);'); +function reView($path, &$tree) +{ + $tree->name = $path; + $tree->value = $path . ' ' . + setHeader('Set Header', 'setDirHeader("' . $path . '",this);') . + selectPermissions('Set Permission', 'setDirPermission("' . $path . '",this);') . + selectPermissions('Remove Permission', 'removeDirPermission("' . $path . '",this);'); $tree->contracted = true; - foreach(glob($path.'*',GLOB_MARK) as $file) - { - if (is_dir($file)) - { - reView($file,$tree->addChild($file, $file )); - } - elseif (substr($file,-4,4)==='.php') - { - $nodeFile=&$tree->addChild - ( - $file, $file . ' '. - selectPermissions('Set Permission','setPermission("'.$file.'",this);'). - selectPermissions('Remove Permission','removePermission("'.$file.'",this);') - ); - $nodeFile->addChild("View Permissions",'
View Permissions
'); - $nodeFile->addChild("Add Line",'Add Permission
'); - $nodeFile->contracted = true; - } + foreach (glob($path . '*', GLOB_MARK) as $file) { + if (is_dir($file)) { + reView($file, $tree->addChild($file, $file)); + } elseif (substr($file, -4, 4) === '.php') { + $nodeFile = &$tree->addChild($file, $file . ' ' . + selectPermissions('Set Permission', 'setPermission("' . $file . '",this);') . + selectPermissions('Remove Permission', 'removePermission("' . $file . '",this);') + ); + $nodeFile->addChild("View Permissions", '
View Permissions
'); + $nodeFile->addChild("Add Line", 'Add Permission
'); + $nodeFile->contracted = true; + } } - } - function selectPermissions($label,$onchange) - { - return ''; - } - function setHeader($label,$onchange) - { - return ''; - } +} + +function selectPermissions($label, $onchange) +{ + return ''; +} + +function setHeader($label, $onchange) +{ + return ''; +} ?> \ No newline at end of file + var headerText = document.getElementById("headerText"); + var phpFile = WebResource('methodsPermissions_Ajax'); + function loadFile(file, div) + { + div.innerHTML = phpFile.get_permissions(file); + } + function switchViewEdit(txt, inp) + { + showHideElement(txt); + showHideElement(inp); + inp.focus(); + var file = inp.name.split('?')[0]; + var row = parseInt(inp.name.split('?')[1]); + //phpFile.modify_line(file,row,inp.value); + } + function switchEditView(txt, inp) + { + showHideElement(txt); + showHideElement(inp); + var file = inp.name.split('?')[0]; + var row = parseInt(inp.name.split('?')[1]); + var res = phpFile.modify_line(file, row, inp.value); + txt.innerHTML = res[0]; + inp.value = res[1]; + } + function addPermission(file, inp) + { + var res = phpFile.add_permission(file, inp.value); + document.getElementById('divPerms[' + file + ']').innerHTML = res; + } + function removeLine(btn) + { + var file = btn.name.split('?')[0]; + var row = parseInt(btn.name.split('?')[1]); + var res = phpFile.remove_line(file, row); + document.getElementById('divPerms[' + file + ']').innerHTML = res; + } + function setDirPermission(file, inp) + { + var res = phpFile.set_path_permission(file, inp.value); + inp.selectedIndex = 0; + } + function setDirHeader(file, inp) + { + var res = phpFile.set_path_header(file, headerText.value); + inp.selectedIndex = 0; + } + function removeDirPermission(file, inp) + { + var res = phpFile.remove_path_permission(file, headerText.value); + inp.selectedIndex = 0; + } + function setPermission(file, inp) + { + var res = phpFile.set_permission(file, inp.value); + document.getElementById('divPerms[' + file + ']').innerHTML = res; + inp.selectedIndex = 0; + } + function removePermission(file, inp) + { + var res = phpFile.remove_permission(file, inp.value); + document.getElementById('divPerms[' + file + ']').innerHTML = res; + inp.selectedIndex = 0; + } + \ No newline at end of file