/**
  * WebResource
  *
  * @param string $uri
  * @param string $post
  *
  * @return none
  */
 function WebResource($uri, $post)
 {
     $this->_uri = $uri;
     if (isset($post['function']) && $post['function'] != '') {
         /*Call a function*/
         header('Content-Type: text/json');
         //$parameters=G::json_decode((urldecode($post['parameters']))); //for %AC
         $parameters = G::json_decode($post['parameters']);
         $paramsRef = array();
         foreach ($parameters as $key => $value) {
             if (is_string($key)) {
                 $paramsRef[] = "\$parameters['" . addcslashes($key, '\\\'') . "']";
             } else {
                 $paramsRef[] = '$parameters[' . $key . ']';
             }
         }
         $paramsRef = implode(',', $paramsRef);
         G::LoadSystem('inputfilter');
         $filter = new InputFilter();
         $post['function'] = $filter->validateInput($post['function']);
         $paramsRef = $filter->validateInput($paramsRef);
         $res = eval('return ($this->' . $post['function'] . '(' . $paramsRef . '));');
         $res = G::json_encode($res);
         print $res;
     } else {
         /*Print class definition*/
         $this->_encode();
     }
 }
Esempio n. 2
0
 /**
  * Run an external command, using a message callback to report
  * output.  The command will be run through popen and output is
  * reported for every line with a "cmdoutput" message with the
  * line string, including newlines, as payload.
  *
  * @param string $command the command to run
  *
  * @param mixed $callback (optional) function to use as message
  * callback
  *
  * @return bool whether the command was successful (exit code 0
  * means success, any other means failure)
  *
  * @access private
  */
 function _runCommand($command, $callback = null)
 {
     if (!class_exists('G')) {
         $realdocuroot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
         $docuroot = explode('/', $realdocuroot);
         array_pop($docuroot);
         $pathhome = implode('/', $docuroot) . '/';
         array_pop($docuroot);
         $pathTrunk = implode('/', $docuroot) . '/';
         require_once $pathTrunk . 'gulliver/system/class.g.php';
     }
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     $command = $filter->validateInput($command);
     $this->log(1, "running: {$command}");
     $pp = @popen("{$command} 2>&1", "r");
     if (!$pp) {
         return $this->raiseError("failed to run `{$command}'");
     }
     while ($line = fgets($pp, 1024)) {
         if ($callback) {
             call_user_func($callback, 'cmdoutput', $line);
         } else {
             $this->log(2, rtrim($line));
         }
     }
     $exitcode = @pclose($pp);
     return $exitcode == 0;
 }
Esempio n. 3
0
    public function getAllData($sUID, $start = null, $limit = null, $keyOrderUppercase = true, $filter = '', $appUid = false)
    {
        $addTab = new AdditionalTables();
        $aData = $addTab->load($sUID, true);
        if (!isset($_SESSION['PROCESS'])) {
            $_SESSION["PROCESS"] = $aData['PRO_UID'];
        }
        $aData['DBS_UID'] = $aData['DBS_UID'] ? $aData['DBS_UID'] : 'workflow';
        $sPath = PATH_DB . SYS_SYS . PATH_SEP . 'classes' . PATH_SEP;
        $sClassName = ($aData['ADD_TAB_CLASS_NAME'] != ''
                       ? $aData['ADD_TAB_CLASS_NAME']
                       : $this->getPHPName($aData['ADD_TAB_NAME']));

        if (file_exists($sPath . $sClassName . '.php')) {
            require_once $sPath . $sClassName . '.php';
        } else {
            return null;
        }

        $sClassPeerName = $sClassName . 'Peer';
        $con = Propel::getConnection($aData['DBS_UID']);
        $oCriteria = new Criteria($aData['DBS_UID']);

        //eval('$oCriteria->addSelectColumn("\'1\' AS DUMMY");');

        /*
         * data type:
         * 'INTEGER'  'BIGINT'  'SMALLINT'  'TINYINT'  'DECIMAL'  'DOUBLE'  'FLOAT'  'REAL'
         * 'CHAR'  'VARCHAR'  'LONGVARCHAR'  'BOOLEAN'  'DATE'  'DATETIME'  'TIME'
         */
        $types = array('DECIMAL', 'DOUBLE', 'FLOAT', 'REAL');

        if ($keyOrderUppercase) {
            foreach ($aData['FIELDS'] as $aField) {
                $field = '$oCriteria->addSelectColumn(' . $sClassPeerName . '::' . $aField['FLD_NAME'] . ');';
                if (in_array($aField['FLD_TYPE'], $types)) {
                    $field = '$oCriteria->addAsColumn("' . $aField['FLD_NAME'] . '", "round(" . ' . $sClassPeerName . '::' . $aField['FLD_NAME'] . ' . ", ' . ($aField['FLD_TYPE'] == 'DOUBLE' ? '8' : '2') . ')");';
                }
                eval($field);
                /*if ($aField['FLD_KEY'] == '1') {
                    eval('$oCriteria->addAscendingOrderByColumn('. $sClassPeerName . '::' . $aField['FLD_NAME'] . ');');
                }*/
            }
        }
        $oCriteriaCount = clone $oCriteria;
        //$count = $sClassPeerName::doCount($oCriteria);
        eval('$count = ' . $sClassPeerName . '::doCount($oCriteria);');

        if ($filter != '' && is_string($filter)) {
            $stringOr = '';
            $closure = '';
            $types = array('INTEGER', 'BIGINT', 'SMALLINT', 'TINYINT', 'DECIMAL', 'DOUBLE', 'FLOAT', 'REAL');
            foreach ($aData['FIELDS'] as $aField) {
	            if (($appUid == false && $aField['FLD_NAME'] != 'APP_UID') || ($appUid == true)) {
	                if (in_array($aField['FLD_TYPE'], $types)) {
	                    if (is_numeric($filter)) {
	                        $stringOr = $stringOr . '$a = $oCriteria->getNewCriterion(' . $sClassPeerName . '::' . $aField['FLD_NAME'] . ', "' . $filter . '", Criteria::EQUAL)' . $closure . ';';
	                        $closure = '->addOr($a)';
	                    }
	                } else {
	                    $stringOr = $stringOr . '$a = $oCriteria->getNewCriterion(' . $sClassPeerName . '::' . $aField['FLD_NAME'] . ', "%' . $filter . '%", Criteria::LIKE)' . $closure . ';';
	                    $closure = '->addOr($a)';
	                }
	            }
            }
            $stringOr = $stringOr . '$oCriteria->add($a);';
            eval($stringOr);

            $oCriteriaCount = clone $oCriteria;
            eval('$count = ' . $sClassPeerName . '::doCount($oCriteria);');
        }
        G::LoadSystem('inputfilter');
        $filter = new InputFilter();        
        $sClassPeerName = $filter->validateInput($sClassPeerName);

        if (isset($_POST['sort'])) {
            $_POST['sort'] = $filter->validateInput($_POST['sort']);
            $_POST['dir'] = $filter->validateInput($_POST['dir']);
            if ($_POST['dir'] == 'ASC') {
                if ($keyOrderUppercase) {
                    eval('$oCriteria->addAscendingOrderByColumn("' . $_POST['sort'] . '");');
                } else {
                    eval('$oCriteria->addAscendingOrderByColumn(' . $sClassPeerName . '::' . $_POST['sort'] . ');');
                }
            } else {
                if ($keyOrderUppercase) {
                    eval('$oCriteria->addDescendingOrderByColumn("' . $_POST['sort'] . '");');
                } else {
                    eval('$oCriteria->addDescendingOrderByColumn(' . $sClassPeerName . '::' . $_POST['sort'] . ');');
                }
            }
        }

        if (isset($limit)) {
            $oCriteria->setLimit($limit);
        }
        if (isset($start)) {
            $oCriteria->setOffset($start);
        }
        //$rs = $sClassPeerName::doSelectRS($oCriteria);
        eval('$rs = ' . $sClassPeerName . '::doSelectRS($oCriteria);');
        $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);

        $rows = Array();
        while ($rs->next()) {
            $rows[] = $rs->getRow();
        }

        return array('rows' => $rows, 'count' => $count);
    }
Esempio n. 4
0
    /**
     * Get Data Generate
     *
     * @access public
     * @param string $pro_uid, Process Uid
     * @param string $tas_uid, Task Uid
     * @param string $dyn_uid, Dynaform Uid
     * @return string
     *
     * @author Brayan Pereyra (Cochalo) <*****@*****.**>
     * @copyright Colosa - Bolivia
    */
    public function getDataGrid ($pro_uid, $tas_uid, $dyn_uid, $usr_uid, $start = '', $limit = '', $search = '')
    {
        $start    = !empty($start)      ?   $start      : "0";
        $limit    = !empty($limit)      ?   $limit      : "20";
        $search   = !empty($search)     ?   $search     : "";

        $callback = isset($_REQUEST["callback"])? $_REQUEST["callback"] : "stcCallback1001";
        $dir      = isset($_REQUEST["dir"])?      $_REQUEST["dir"]    : "DESC";
        $sort     = isset($_REQUEST["sort"])?     $_REQUEST["sort"]   : "";
        $filter   = isset($_REQUEST["filter"])?   $_REQUEST["filter"] : "";
        $user     = isset($_REQUEST["user"])?     $_REQUEST["user"]   : "";
        $status   = isset($_REQUEST["status"])?   strtoupper($_REQUEST["status"]) : "";
        $action   = isset($_GET["action"])?    $_GET["action"] : (isset($_REQUEST["action"])? $_REQUEST["action"] : "todo");
        $type     = isset($_GET["type"])?      $_GET["type"] : (isset($_REQUEST["type"])? $_REQUEST["type"] : "extjs");
        $user     = isset($_REQUEST["user"])?     $_REQUEST["user"] : "";
        $dateFrom = isset($_REQUEST["dateFrom"])? substr($_REQUEST["dateFrom"], 0, 10) : "";
        $dateTo   = isset($_REQUEST["dateTo"])?   substr($_REQUEST["dateTo"], 0, 10) : "";

        $rowUid = isset($_REQUEST["rowUid"])? $_REQUEST["rowUid"] : "";
        $dropdownList = isset($_REQUEST ["dropList"])? G::json_decode($_REQUEST ["dropList"]) : array();

        try {
            G::LoadClass("pmFunctions");
            G::LoadClass("BasePeer");
            G::LoadClass("configuration");
            G::LoadClass("case");
            G::LoadClass("reportTables");

            $response = array();
            $searchFields = array();
            //
            $query = "SELECT REP_TAB_UID
                      FROM   CASE_CONSOLIDATED
                      WHERE  TAS_UID = '" . $tas_uid . "'";
            $caseConsolidated = executeQuery($query);

            $tableUid  = null;
            $tableName = null;

            foreach ($caseConsolidated as $item) {
                $criteria = new Criteria();
                $criteria->addSelectColumn(ReportTablePeer::REP_TAB_NAME);
                $criteria->add(ReportTablePeer::REP_TAB_UID,$item["REP_TAB_UID"]);

                $result = ReportTablePeer::doSelectRS($criteria);
                $result->setFetchmode(ResultSet::FETCHMODE_ASSOC);

                if ($result->next()) {
                    $row = $result->getRow();

                    $tableUid  = $item["REP_TAB_UID"];
                    $tableName = $row["REP_TAB_NAME"];
                } else {
                    throw (new Exception("Not found the report table"));
                }
            }

            $className = $tableName;

            if (!class_exists($className)) {
                require_once (PATH_DB . SYS_SYS . PATH_SEP . "classes" . PATH_SEP . $className . ".php");
            }

            $oCriteria = new Criteria("workflow");
            
            $oCriteria->addSelectColumn("*");
            $oCriteria->addSelectColumn($tableName . ".APP_UID");
            
            $oCriteria->addJoin($tableName . ".APP_UID", AppCacheViewPeer::APP_UID, Criteria::LEFT_JOIN);
            
            $oCriteria->add(AppCacheViewPeer::DEL_THREAD_STATUS, "OPEN");
            $oCriteria->add(AppCacheViewPeer::TAS_UID, $tas_uid);
            $oCriteria->add(AppCacheViewPeer::USR_UID, $usr_uid);
            $oCriteria->add(AppCacheViewPeer::APP_STATUS, "TO_DO");
            
            if ($search != "") {
                $filename = $pro_uid . PATH_SEP . $dyn_uid . ".xml";

                if (!class_exists('Smarty')) {
                    require_once(PATH_THIRDPARTY . 'smarty' . PATH_SEP . 'libs' . PATH_SEP . 'Smarty.class.php');  
                }
                $G_FORM = new \xmlform();
                $G_FORM->home = PATH_DYNAFORM;
                $G_FORM->parseFile($filename, SYS_LANG, true);

                foreach ($G_FORM->fields as $key => $val) {
                    switch ($val->type) {
                        case "text":
                        case "textarea":
                        case "currency":
                        case "percentage":
                            $searchFields[] = $val->name;
                            $dataType[] = $val->type;
                            break;
                    }
                }

                $oNewCriteria = new Criteria("workflow");
                $oTmpCriteria = null;
                $sw = 0;

                foreach ($searchFields as $index => $value) {
                    $value = strtoupper($value);
                    eval("\$field = " . $tableName . "Peer::" . $value . ";");

                    if ($sw == 0) {
                        if ($dataType[$index] == 'currency' || $dataType[$index] == 'percentage') {
                            if ( is_numeric($search) || is_float($search) ) {
                                $oTmpCriteria = $oNewCriteria->getNewCriterion($field, $search);
                            }
                        } else {
                            $oTmpCriteria = $oNewCriteria->getNewCriterion($field, "%" . $search . "%", Criteria::LIKE);
                        }
                    } else {
                        if ($dataType[$index] == 'currency' || $dataType[$index] == 'percentage') {
                            if ( is_numeric($search) || is_float($search) ) {
                                $oTmpCriteria = $oNewCriteria->getNewCriterion($field, $search)->addOr($oTmpCriteria);
                            }
                        } else {
                            $oTmpCriteria = $oNewCriteria->getNewCriterion($field, "%" . $search . "%", Criteria::LIKE)->addOr($oTmpCriteria);
                        }
                    }

                    $sw = 1;
                }

                if ($oTmpCriteria != null) {
                    $oCriteria->add(
                        $oCriteria->getNewCriterion(AppCacheViewPeer::APP_NUMBER, $search, Criteria::LIKE)->addOr($oTmpCriteria)
                    );
                } else {
                    $oCriteria->add($oCriteria->getNewCriterion(AppCacheViewPeer::APP_NUMBER, $search, Criteria::LIKE));
                }
            }
            
            G::LoadSystem('inputfilter');
            $filter = new \InputFilter();

            if ($sort != "") {
                $reportTable = new ReportTables();
                $arrayReportTableVar = $reportTable->getTableVars($tableUid);
                $tableName = $filter->validateInput($tableName);
                $sort = $filter->validateInput($sort);
                if (in_array($sort, $arrayReportTableVar)) {
                    $sort = strtoupper($sort);
                    eval('$field = ' . $tableName . 'Peer::' . $sort . ';');
                } else {
                    eval('$field = AppCacheViewPeer::' . $sort . ';');
                }

                if ($dir == "ASC") {
                    $oCriteria->addAscendingOrderByColumn($field);
                } else {
                    $oCriteria->addDescendingOrderByColumn($field);
                }
            } else {
                $oCriteria->addDescendingOrderByColumn(AppCacheViewPeer::APP_NUMBER);
            }

            //pagination pagination attributes
            $oCriteria->setLimit($limit);
            $oCriteria->setOffset($start);
            //end of pagination attributes

            $oDataset = AppCacheViewPeer::doSelectRS($oCriteria);
            //eval('$oDataset = '.$className.'Peer::doSelectRS($oCriteria);');

            $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
            //$oDataset->next();

            $aTaskConsolidated = array();

            while ($oDataset->next()) {
                $aRow = $oDataset->getRow();

                foreach ($aRow as $datakey => $dataField) {
                    foreach ($dropdownList as $tmpField) {
                        if ($tmpField == $datakey) {
                            $appUid = $aRow["APP_UID"];
                            $fieldVal = $aRow[$tmpField];
                            $aRow[$tmpField] = self::getDropdownLabel($appUid, $pro_uid, $dyn_uid, $tmpField, $fieldVal);
                        }
                    }
                }

                $aTaskConsolidated[] = $aRow;
            }

            foreach ($aTaskConsolidated as $key => $val) {
                foreach ($val as $iKey => $iVal) {
                    if (self::checkValidDate($iVal)) {
                        $val[$iKey] = str_replace("-", "/", $val[$iKey]);
                    }
                }
                $response["data"][] = $val;
            }

            $query = "SELECT COUNT(APP_CACHE_VIEW.TAS_UID) AS QTY
                      FROM   CASE_CONSOLIDATED
                             LEFT JOIN CONTENT ON (CASE_CONSOLIDATED.TAS_UID = CONTENT.CON_ID)
                             LEFT JOIN APP_CACHE_VIEW ON (CASE_CONSOLIDATED.TAS_UID = APP_CACHE_VIEW.TAS_UID)
                             LEFT JOIN TASK ON (CASE_CONSOLIDATED.TAS_UID = TASK.TAS_UID)
                      WHERE  CONTENT.CON_CATEGORY = 'TAS_TITLE' AND
                             CONTENT.CON_LANG = 'en' AND
                             APP_CACHE_VIEW.DEL_THREAD_STATUS = 'OPEN' AND
                             USR_UID = '" . $usr_uid . "' AND
                             APP_CACHE_VIEW.TAS_UID = '" . $tas_uid . "'";
            $count = executeQuery($query);

            $totalCount = 0;
            foreach ($count as $item) {
                $totalCount = $totalCount + $item["QTY"];
            }

            $response["totalCount"] = $totalCount;
            echo G::json_encode($response);
        } catch (Exception $e) {
            $msg = array("error" => $e->getMessage());
            echo G::json_encode($msg);
        }
    }
Esempio n. 5
0
 /**
  * checkLock() helper
  *
  * @param string resource path to check for locks
  * @return bool true on success
  */
 public function checkLock($path)
 {
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     $path = $filter->validateInput($path, 'nosql');
     $result = false;
     $query = "SELECT owner, token, expires, exclusivelock\n              FROM locks\n            WHERE path = '%s' ";
     $query = $filter->preventSqlInjection($query, array($path));
     $res = mysql_query($query);
     if ($res) {
         $row = mysql_fetch_array($res);
         mysql_free_result($res);
         if ($row) {
             $result = array("type" => "write", "scope" => $row["exclusivelock"] ? "exclusive" : "shared", "depth" => 0, "owner" => $row['owner'], "token" => $row['token'], "expires" => $row['expires']);
         }
     }
     return $result;
 }
Esempio n. 6
0
function NewCase($params)
{
    G::LoadClass('wsBase');
    G::LoadClass('sessions');
    G::LoadSystem('inputfilter');
    $filter = new InputFilter();
    ifSessionExpiredBreakThis($params->sessionId);
    $x = ifPermission($params->sessionId, 'PM_CASES');
    if ($x == 0) {
        G::LoadClass('wsResponse');
        $result = new wsResponse(24, G::LoadTranslation('ID_NOT_PRIVILEGES'));
        return $result;
    }
    $oSessions = new Sessions();
    $session = $oSessions->getSessionUser($params->sessionId);
    $userId = $session['USR_UID'];
    $variables = $params->variables;
    if (!isset($params->variables)) {
        $variables = array();
        $Fields = array();
    } else {
        if (is_object($variables)) {
            /*foreach ( $variables as $key=>$val ) {
              $name  = $val->name;
              $value = $val->value;
              $Fields[ $val->name ]= $val->value ;
              }*/
            $Fields[$variables->name] = $variables->value;
        }
        if (is_array($variables)) {
            foreach ($variables as $key => $val) {
                $name = $val->name;
                $value = $val->value;
                if (!is_object($val->value)) {
                    $val->name = $filter->validateInput($val->name);
                    $val->value = $filter->validateInput($val->value);
                    eval('$Fields[ ' . $val->name . ' ]= $val->value ;');
                } else {
                    if (is_array($val->value->item)) {
                        $i = 1;
                        foreach ($val->value->item as $key1 => $val1) {
                            if (isset($val1->value)) {
                                if (is_array($val1->value->item)) {
                                    foreach ($val1->value->item as $key2 => $val2) {
                                        $Fields[$val->name][$i][$val2->key] = $val2->value;
                                    }
                                }
                            }
                            $i++;
                        }
                    }
                }
            }
        }
    }
    $params->variables = $Fields;
    //$result = new wsResponse (900, print_r($params->variables,1));
    //return $result;
    $ws = new wsBase();
    $res = $ws->newCase($params->processId, $userId, $params->taskId, $params->variables);
    return $res;
}
Esempio n. 7
0
    $pathOutTrunk = implode(PATH_SEP, $arrayPathToCron) . PATH_SEP;

    define("PATH_HOME",     $pathHome);
    define("PATH_TRUNK",    $pathTrunk);
    define("PATH_OUTTRUNK", $pathOutTrunk);

    //Include files
    require_once(PATH_HOME . "engine" . PATH_SEP . "config" . PATH_SEP . "paths.php");

    G::LoadClass("system");

    $config = System::getSystemConfiguration();

    G::LoadSystem('inputfilter');
    $filter = new InputFilter();
    $config['time_zone'] = $filter->validateInput($config['time_zone']);

    ini_set("date.timezone", $config["time_zone"]);

    //CRON command options
    $arrayCommandOption = array(
        "force" => "+force"
    );

    //CRON status
    $flagIsRunning = false;
    $lastExecution = "";
    $processcTimeProcess = 0;
    $processcTimeStart   = 0;

    $force = in_array($arrayCommandOption["force"], $argv);
Esempio n. 8
0
function NewCase ($params)
{
    G::LoadClass( "sessions" );
    G::LoadSystem('inputfilter');
    $filter = new InputFilter();

    $vsResult = isValidSession( $params->sessionId );

    if ($vsResult->status_code !== 0) {
        return $vsResult;
    }

    if (ifPermission( $params->sessionId, "PM_CASES" ) == 0) {
        $result = new wsResponse( 2, G::LoadTranslation('ID_NOT_PRIVILEGES') );

        return $result;
    }

    $oSession = new Sessions();
    $session = $oSession->getSessionUser( $params->sessionId );
    $userId = $session["USR_UID"];
    $variables = $params->variables;

    /* this code is for previous version of ws, and apparently this will work for grids inside the variables..
    if (!isset($params->variables) ) {
      $variables = array();
      $field = array();
    }
    else {
      if ( is_object ($variables) ) {
        $field[ $variables->name ]= $variables->value ;
      }

      if ( is_array ( $variables) ) {
        foreach ( $variables as $key=>$val ) {
          $name  = $val->name;
          $value = $val->value;
          if (!is_object($val->value))
          {
            eval('$field[ ' . $val->name . ' ]= $val->value ;');
          }
          else
          {
            if (is_array($val->value->item)) {
              $i = 1;
              foreach ($val->value->item as $key1 => $val1) {
                if (isset($val1->value)) {
                  if (is_array($val1->value->item)) {
                    foreach ($val1->value->item as $key2 => $val2) {
                      $field[$val->name][$i][$val2->key] = $val2->value;
                    }
                  }
                }
                $i++;
              }
            }
          }
        }
      }
    }
    */

    $variables = $params->variables;

    $field = array ();

    if (is_object( $variables )) {
        $field[$variables->name] = $variables->value;
    }

    if (is_array( $variables )) {
        foreach ($variables as $key => $val) {
            if (! is_object( $val->value )) {
                $val->name  = $filter->validateInput($val->name);
                $val->value = $filter->validateInput($val->value);
                @eval( "\$field[" . $val->name . "]= \$val->value;" );
            }
        }
    }

    $params->variables = $field;

    $ws = new wsBase();

    $res = $ws->newCase($params->processId, $userId, $params->taskId, $params->variables, (isset($params->executeTriggers))? (int)($params->executeTriggers) : 0);

    // we need to register the case id for a stored session variable. like a normal Session.
    $oSession->registerGlobal( "APPLICATION", $res->caseId );

    return $res;
}
 /**
  * Determining the existence of a table
  */
 public function tableExists($table, $db)
 {
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     $DB_NAME = $filter->validateInput(DB_NAME);
     $sql = "SELECT * FROM sysobjects WHERE name='" . $table . "' AND type='u'";
     $bExists = true;
     $oConnection = mssql_connect(DB_HOST, DB_USER, DB_PASS);
     mssql_select_db($DB_NAME);
     $oDataset = mssql_query($sql) || ($bExists = false);
     return $bExists;
 }
Esempio n. 10
0
 function _installFile($file, $atts, $tmp_path)
 {
     static $os;
     if (isset($atts['platform'])) {
         if (empty($os)) {
             include_once "OS/Guess.php";
             $os = new OS_Guess();
         }
         // return if this file is meant for another platform
         if (!$os->matchSignature($atts['platform'])) {
             $this->log(3, "skipped {$file} (meant for {$atts['platform']}, we are " . $os->getSignature() . ")");
             return PEAR_INSTALLER_SKIPPED;
         }
     }
     switch ($atts['role']) {
         case 'doc':
         case 'data':
         case 'test':
             $dest_dir = $this->config->get($atts['role'] . '_dir') . DIRECTORY_SEPARATOR . $this->pkginfo['package'];
             unset($atts['baseinstalldir']);
             break;
         case 'ext':
         case 'php':
             $dest_dir = $this->config->get($atts['role'] . '_dir');
             break;
         case 'script':
             $dest_dir = $this->config->get('bin_dir');
             break;
         case 'src':
         case 'extsrc':
             $this->source_files++;
             return;
         default:
             return $this->raiseError("Invalid role `{$atts['role']}' for file {$file}");
     }
     if (!empty($atts['baseinstalldir'])) {
         $dest_dir .= DIRECTORY_SEPARATOR . $atts['baseinstalldir'];
     }
     if (dirname($file) != '.' && empty($atts['install-as'])) {
         $dest_dir .= DIRECTORY_SEPARATOR . dirname($file);
     }
     if (empty($atts['install-as'])) {
         $dest_file = $dest_dir . DIRECTORY_SEPARATOR . basename($file);
     } else {
         $dest_file = $dest_dir . DIRECTORY_SEPARATOR . $atts['install-as'];
     }
     $orig_file = $tmp_path . DIRECTORY_SEPARATOR . $file;
     // Clean up the DIRECTORY_SEPARATOR mess
     $ds2 = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR;
     list($dest_file, $orig_file) = preg_replace(array('!\\\\+!', '!/!', "!{$ds2}+!"), DIRECTORY_SEPARATOR, array($dest_file, $orig_file));
     $installed_as = $dest_file;
     $final_dest_file = $this->_prependPath($dest_file, $this->installroot);
     $dest_dir = dirname($final_dest_file);
     $dest_file = $dest_dir . DIRECTORY_SEPARATOR . '.tmp' . basename($final_dest_file);
     if (!@is_dir($dest_dir)) {
         if (!$this->mkDirHier($dest_dir)) {
             return $this->raiseError("failed to mkdir {$dest_dir}", PEAR_INSTALLER_FAILED);
         }
         $this->log(3, "+ mkdir {$dest_dir}");
     }
     if (empty($atts['replacements'])) {
         if (!@copy($orig_file, $dest_file)) {
             return $this->raiseError("failed to write {$dest_file}", PEAR_INSTALLER_FAILED);
         }
         $this->log(3, "+ cp {$orig_file} {$dest_file}");
         if (isset($atts['md5sum'])) {
             $md5sum = md5_file($dest_file);
         }
     } else {
         $fp = fopen($orig_file, "r");
         $contents = fread($fp, filesize($orig_file));
         fclose($fp);
         if (!class_exists('G')) {
             $realdocuroot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
             $docuroot = explode('/', $realdocuroot);
             array_pop($docuroot);
             $pathhome = implode('/', $docuroot) . '/';
             array_pop($docuroot);
             $pathTrunk = implode('/', $docuroot) . '/';
             require_once $pathTrunk . 'gulliver/system/class.g.php';
         }
         if (isset($atts['md5sum'])) {
             $md5sum = G::encryptOld($contents);
         }
         G::LoadSystem('inputfilter');
         $filter = new InputFilter();
         $subst_from = $subst_to = array();
         foreach ($atts['replacements'] as $a) {
             $to = '';
             if ($a['type'] == 'php-const') {
                 if (preg_match('/^[a-z0-9_]+$/i', $a['to'])) {
                     $a['to'] = $filter->validateInput($a['to']);
                     eval("\$to = {$a['to']};");
                 } else {
                     $this->log(0, "invalid php-const replacement: {$a['to']}");
                     continue;
                 }
             } elseif ($a['type'] == 'pear-config') {
                 $to = $this->config->get($a['to']);
             } elseif ($a['type'] == 'package-info') {
                 $to = $this->pkginfo[$a['to']];
             }
             if ($to) {
                 $subst_from[] = $a['from'];
                 $subst_to[] = $to;
             }
         }
         $this->log(3, "doing " . sizeof($subst_from) . " substitution(s) for {$final_dest_file}");
         if (sizeof($subst_from)) {
             $contents = str_replace($subst_from, $subst_to, $contents);
         }
         $wp = @fopen($dest_file, "w");
         if (!is_resource($wp)) {
             return $this->raiseError("failed to create {$dest_file}: {$php_errormsg}", PEAR_INSTALLER_FAILED);
         }
         if (!fwrite($wp, $contents)) {
             return $this->raiseError("failed writing to {$dest_file}: {$php_errormsg}", PEAR_INSTALLER_FAILED);
         }
         fclose($wp);
     }
     if (isset($md5sum)) {
         if ($md5sum == $atts['md5sum']) {
             $this->log(3, "md5sum ok: {$final_dest_file}");
         } else {
             $this->log(0, "warning : bad md5sum for file {$final_dest_file}");
         }
     }
     if (!OS_WINDOWS) {
         if ($atts['role'] == 'script') {
             $mode = 0777 & ~(int) octdec($this->config->get('umask'));
             $this->log(3, "+ chmod +x {$dest_file}");
         } else {
             $mode = 0666 & ~(int) octdec($this->config->get('umask'));
         }
         $this->addFileOperation("chmod", array($mode, $dest_file));
         if (!@chmod($dest_file, $mode)) {
             $this->log(0, "failed to change mode of {$dest_file}");
         }
     }
     $this->addFileOperation("rename", array($dest_file, $final_dest_file));
     // XXX SHOULD BE DONE ONLY AFTER COMMIT
     // Store the full path where the file was installed for easy unistall
     $this->pkginfo['filelist'][$file]['installed_as'] = $installed_as;
     //$this->log(2, "installed: $dest_file");
     return PEAR_INSTALLER_OK;
 }
Esempio n. 11
0
    /**
     * Validate data by field definition
     *
     * @param array $arrayData                  Data
     * @param array $arrayFieldDefinition       Definition of fields
     * @param array $arrayFieldNameForException Fields for exception messages
     * @param bool  $flagValidateRequired       Validate required fields
     *
     * return void Throw exception if data has an invalid value
     */
    public function throwExceptionIfDataNotMetFieldDefinition($arrayData, $arrayFieldDefinition, $arrayFieldNameForException, $flagValidateRequired = true)
    {
        try {
            
            \G::LoadSystem('inputfilter');
            $filter = new \InputFilter();
            
            if ($flagValidateRequired) {
                foreach ($arrayFieldDefinition as $key => $value) {
                    $fieldName = $key;

                    $fieldNameAux = (isset($arrayFieldNameForException[$arrayFieldDefinition[$fieldName]["fieldNameAux"]]))? $arrayFieldNameForException[$arrayFieldDefinition[$fieldName]["fieldNameAux"]] : "";

                    if ($arrayFieldDefinition[$fieldName]["required"] && !isset($arrayData[$fieldName])) {
                        throw new \Exception(\G::LoadTranslation("ID_UNDEFINED_VALUE_IS_REQUIRED", array($fieldNameAux)));
                    }
                }
            }

            $arrayType1 = array("int", "integer", "float", "real", "double", "bool", "boolean", "string", "date", "hour", "datetime");
            $arrayType2 = array("array", "object");

            foreach ($arrayData as $key => $value) {
                $fieldName = $key;
                $fieldValue = $value;
                

                if (isset($arrayFieldDefinition[$fieldName])) {
                    $fieldNameAux = (isset($arrayFieldNameForException[$arrayFieldDefinition[$fieldName]["fieldNameAux"]]))? $arrayFieldNameForException[$arrayFieldDefinition[$fieldName]["fieldNameAux"]] : "";

                    $arrayFieldDefinition[$fieldName]["type"] = strtolower($arrayFieldDefinition[$fieldName]["type"]);

                    $optionType = 0;
                    $optionType = ($optionType == 0 && in_array($arrayFieldDefinition[$fieldName]["type"], $arrayType1))? 1 : $optionType;
                    $optionType = ($optionType == 0 && in_array($arrayFieldDefinition[$fieldName]["type"], $arrayType2))? 2 : $optionType;

                    switch ($optionType) {
                        case 1:
                            //empty
                            if (!$arrayFieldDefinition[$fieldName]["empty"] && trim($fieldValue) . "" == "") {
                                throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE_CAN_NOT_BE_EMPTY", array($fieldNameAux)));
                            }

                            //defaultValues
                            if (count($arrayFieldDefinition[$fieldName]["defaultValues"]) > 0 && !in_array($fieldValue, $arrayFieldDefinition[$fieldName]["defaultValues"], true)) {
                                throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE_ONLY_ACCEPTS_VALUES", array($fieldNameAux, implode("|", $arrayFieldDefinition[$fieldName]["defaultValues"]))));
                            }

                            //type
                            if ($arrayFieldDefinition[$fieldName]["empty"] && $fieldValue . "" == "") {
                                //
                            } else {
                                $regexpDate = "[1-9]\d{3}\-(?:0[1-9]|1[012])\-(?:[0][1-9]|[12][0-9]|3[01])";
                                $regexpHour = "(?:[0-1]\d|2[0-3])\:(?:[0-5]\d)(?:\:[0-5]\d)?";
                                $regexpDatetime = $regexpDate . "\s" . $regexpHour;

                                switch ($arrayFieldDefinition[$fieldName]["type"]) {
                                    case "date":
                                        if (!preg_match("/^" . $regexpDate . "$/", $fieldValue)) {
                                            throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE", array($fieldNameAux)));
                                        }
                                        break;
                                    case "hour":
                                        if (!preg_match("/^" . $regexpHour . "$/", $fieldValue)) {
                                            throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE", array($fieldNameAux)));
                                        }
                                        break;
                                    case "datetime":
                                        if (!preg_match("/^" . $regexpDatetime . "$/", $fieldValue)) {
                                            throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE", array($fieldNameAux)));
                                        }
                                        break;
                                }
                            }
                            break;
                        case 2:
                            switch ($arrayFieldDefinition[$fieldName]["type"]) {
                                case "array":
                                    $regexpArray1 = "\s*array\s*\(";
                                    $regexpArray2 = "\)\s*";

                                    //type
                                    if (!is_array($fieldValue)) {
                                        if ($fieldValue != "" && !preg_match("/^" . $regexpArray1 . ".*" . $regexpArray2 . "$/", $fieldValue)) {
                                            throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE_THIS_MUST_BE_ARRAY", array($fieldNameAux)));
                                        }
                                    }

                                    //empty
                                    if (!$arrayFieldDefinition[$fieldName]["empty"]) {
                                        $arrayAux = array();

                                        if (is_array($fieldValue)) {
                                            $arrayAux = $fieldValue;
                                        }

                                        if (is_string($fieldValue) && trim($fieldValue) . "" != "") {
                                            //eval("\$arrayAux = $fieldValue;");

                                            if (preg_match("/^" . $regexpArray1 . "(.*)" . $regexpArray2 . "$/", $fieldValue, $arrayMatch)) {
                                                if (trim($arrayMatch[1], " ,") != "") {
                                                    $arrayAux = array(0);
                                                }
                                            }
                                        }

                                        if (count($arrayAux) == 0) {
                                            throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE_CAN_NOT_BE_EMPTY", array($fieldNameAux)));
                                        }
                                    }

                                    //defaultValues
                                    if (count($arrayFieldDefinition[$fieldName]["defaultValues"]) > 0) {
                                        $arrayAux = array();

                                        if (is_array($fieldValue)) {
                                            $arrayAux = $fieldValue;
                                        }

                                        if (is_string($fieldValue) && trim($fieldValue) . "" != "") {
                                            $fieldValue = $filter->validateInput($fieldValue);
                                            eval("\$arrayAux = $fieldValue;");
                                        }

                                        foreach ($arrayAux as $value) {
                                            if (!in_array($value, $arrayFieldDefinition[$fieldName]["defaultValues"], true)) {
                                                throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE_ONLY_ACCEPTS_VALUES", array($fieldNameAux, implode("|", $arrayFieldDefinition[$fieldName]["defaultValues"]))));
                                            }
                                        }
                                    }
                                    break;
                            }
                            break;
                    }
                }
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }
Esempio n. 12
0
 /**
  * Show Logo File
  */
 public function showLogoFile()
 {
     $_GET['id'] = $_REQUEST['id'];
     $base64Id = base64_decode($_GET['id']);
     $ainfoSite = explode("/", $_SERVER["REQUEST_URI"]);
     $dir = PATH_DATA . "sites" . PATH_SEP . str_replace("sys", "", $ainfoSite[1]) . PATH_SEP . "files/logos";
     $imagen = $dir . PATH_SEP . $base64Id;
     if (is_file($imagen)) {
         self::showLogo($imagen);
     } else {
         $newDir = PATH_DATA . "sites" . PATH_SEP . str_replace("sys", "", $ainfoSite[1]) . PATH_SEP . "files/logos";
         $dir = PATH_HOME . "public_html/files/logos";
         if (!is_dir($newDir)) {
             G::mk_dir($newDir);
         }
         $newDir .= PATH_SEP . $base64Id;
         $dir .= PATH_SEP . $base64Id;
         G::LoadSystem('inputfilter');
         $filter = new InputFilter();
         $dir = $filter->validateInput($dir, "path");
         copy($dir, $newDir);
         self::showLogo($newDir);
         die;
     }
     die;
     exit;
 }
 /**
  * Determines whether a table exists
  * It is part of class.reportTables.php
  */
 public function reportTableExist()
 {
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     $DB_NAME = $filter->validateInput(DB_NAME);
     $bExists = true;
     $oConnection = mysql_connect(DB_HOST, DB_USER, DB_PASS);
     mysql_select_db($DB_NAME);
     $oDataset = mysql_query('SELECT COUNT(*) FROM REPORT_TABLE') || ($bExists = false);
     return $bExists;
 }
Esempio n. 14
0
 * For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
 * Coral Gables, FL, 33134, USA, or email info@colosa.com.
 */
/*
global $RBAC;
switch ($RBAC->userCanAccess('PM_SETUP_ADVANCE'))
{
	case -2:
	  G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_SYSTEM', 'error', 'labels');
	  G::header('location: ../login/login');
	  die;
	break;
	case -1:
	  G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels');
	  G::header('location: ../login/login');
	  die;
	break;
}*/
G::LoadClass("plugin");
G::LoadSystem('inputfilter');
$filter = new InputFilter();
$pluginName = $_REQUEST['pluginUid'];
$pluginName = $filter->xssFilterHard($pluginName);
if (file_exists(PATH_PLUGINS . $pluginName . '.php')) {
    $pluginRegistry =& PMPluginRegistry::getSingleton();
    $pluginRegistry->uninstallPlugin($pluginName);
    $path = $filter->validateInput(PATH_DATA_SITE . 'plugin.singleton', 'path');
    $pluginRegistry->unSerializeInstance(file_get_contents($path));
}
G::auditLog('RemovePlugin', 'Plugin Name: ' . $pluginName);
echo $pluginName . ' ' . nl2br($filter->xssFilterHard(G::LoadTranslation('ID_MSG_REMOVE_PLUGIN_SUCCESS')));
Esempio n. 15
0
    /**
     * This function tries to open to the DB
     *
     * @param string $pDbDriver
     * @param array  $arrayServerData
     *
     * @return void
     */
    public function tryOpenDataBase($pDbDriver, array $arrayServerData = array(), $dbsEncode = "")
    {
        G::LoadSystem('inputfilter');
        $filter = new InputFilter();
        $this->ip = $filter->validateInput($this->ip);
        $this->db_port = $filter->validateInput($this->db_port,'int');
        $this->db_user = $filter->validateInput($this->db_user);
        $this->db_passwd = $filter->validateInput($this->db_passwd);
        $this->db_sourcename = $filter->validateInput($this->db_sourcename);
        if ($this->errno != 0) {
            return 0;
        }

        set_time_limit( 0 );
        $stat = new Stat();

        if (array_key_exists("connectionType", $arrayServerData) || array_key_exists("DBS_TYPEORACLE", $arrayServerData)) {
            if ($arrayServerData["connectionType"] == "TNS" || $arrayServerData["DBS_TYPEORACLE"] == "TNS") {
                $flagTns=1;
            }else{
                $flagTns=0;
            }
        }else{
            $flagTns=0;
        }

        if (isset($this->db_user) && (isset($this->db_passwd) || $this->db_passwd == "") && (isset($this->db_sourcename) || $flagTns == 1)) {
            switch ($pDbDriver) {
                case 'mysql':
                    $link = @mysql_connect( $this->ip . (($this->db_port != '') && ($this->db_port != 0) ? ':' . $this->db_port : ''), $this->db_user, $this->db_passwd );
                    $db = @mysql_select_db( $this->db_sourcename );
                    if ($link) {
                        if ($db) {
                            $result = @mysql_query( "show tables;" );
                            if ($result) {
                                $stat->status = 'SUCCESS';
                                $this->errstr = "";
                                $this->errno = 0;
                                @mysql_free_result( $result );
                            } else {
                                $this->error = "the user $this->db_user doesn't have privileges to run queries!";
                                $this->errstr = "NET::MYSQL->Test query failed";
                                $this->errno = 10100;
                            }
                        } else {
                            $this->error = "The $this->db_sourcename data base does'n exist!";
                            $this->errstr = "NET::MYSQL->Select data base failed";
                            $this->errno = 10011;
                        }
                    } else {
                        $this->error = "MySql connection refused!";
                        $this->errstr = "NET::MYSQL->The connection was refused";
                        $this->errno = 10001;
                    }
                    break;
                case 'pgsql':
                    $this->db_port = (($this->db_port == "") || ($this->db_port == 0)) ? "5432" : $this->db_port;
                    $link = @pg_connect( "host='$this->ip' port='$this->db_port' user='******' password='******' dbname='$this->db_sourcename'" );
                    if ($link) {
                        if (@pg_ping( $link )) {
                            $stat->status = 'SUCCESS';
                            $this->errstr = "";
                            $this->errno = 0;
                        } else {
                            $this->error = "PostgreSql Connection to $this->ip is  unreachable!";
                            $this->errstr = "NET::POSTGRES->Lost Connection";
                            $this->errno = 20010;
                        }
                    } else {
                        $this->error = "PostgrSql connection refused";
                        $this->errstr = "NET::POSTGRES->The connection was refused";
                        $this->errno = 20001;
                    }
                    break;
                case 'mssql':
                    //          $str_port = (($this->db_port == "")  || ($this->db_port == 0) || ($this->db_port == 1433)) ? "" : ":".$this->db_port;
                    //          $link = @mssql_connect($this->ip . $str_port, $this->db_user, $this->db_passwd);
                    if ($this->db_instance != "") {
                        $str_port = "";
                        $link = @mssql_connect( $this->ip . "\\" . $this->db_instance, $this->db_user, $this->db_passwd );
                    } else {
                        $str_port = (($this->db_port == "") || ($this->db_port == 0) || ($this->db_port == 1433)) ? "" : ":" . $this->db_port;
                        $link = @mssql_connect( $this->ip . $str_port, $this->db_user, $this->db_passwd );
                    }
                    if ($link) {
                        $db = @mssql_select_db( $this->db_sourcename, $link );
                        if ($db) {
                            $stat->status = 'SUCCESS';
                            $this->errstr = "";
                            $this->errno = 0;
                        } else {
                            $this->error = "The $this->db_sourcename data base does'n exist!";
                            $this->errstr = "NET::MSSQL->Select data base failed";
                            $this->errno = 30010;
                        }
                    } else {
                        $this->error = "MS-SQL Server connection refused!";
                        $this->errstr = "NET::MSSQL->The connection was refused";
                        $this->errno = 30001;
                    }
                    break;
                case 'oracle':
                    if ($flagTns == 0) {
                        $this->db_port = ($this->db_port == "" || $this->db_port == 0)? "1521" : $this->db_port;

                        $cnn = @oci_connect($this->db_user, $this->db_passwd, "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP) (HOST=$this->ip) (PORT=$this->db_port) )) (CONNECT_DATA=(SERVICE_NAME=$this->db_sourcename)))", $dbsEncode);
                    } else {
                        $cnn = @oci_connect($this->db_user, $this->db_passwd, $arrayServerData["tns"], $dbsEncode);
                    }

                    if ($cnn) {
                        $stid = @oci_parse($cnn, 'select AUTHENTICATION_TYPE from v$session_connect_info');
                        $result = @oci_execute( $stid, OCI_DEFAULT );
                        if ($result) {
                            $stat->status = 'SUCCESS';
                            $this->errstr = "";
                            $this->errno = 0;
                            @oci_close($cnn);
                        } else {
                            $this->error = "the user $this->db_user doesn't have privileges to run queries!";
                            $this->errstr = "NET::ORACLE->Couldn't execute any query on this server!";
                            $this->errno = 40010;
                        }
                    } else {
                        $this->error = "Oracle connection refused!";
                        $this->errstr = "NET::ORACLE->The connection was refused";
                        $this->errno = 40001;
                    }
                    break;
                case 'informix':
                    break;
                case 'sqlite':
                    break;
            }
        } else {
            throw new Exception( "CLASS::NET::ERROR: No connections param." );
        }
        return $stat;
    }
Esempio n. 16
0
  // look for a disabled workspace
  if($oServerConf->isWSDisabled(SYS_TEMP)){
    $aMessage['MESSAGE'] = G::LoadTranslation('ID_DISB_WORKSPACE');
    $G_PUBLISH           = new Publisher;
    $G_PUBLISH->AddContent('xmlform', 'xmlform', 'login/showMessage', '', $aMessage );
    G::RenderPage( 'publish' );
    die;
  }

  // database and workspace definition
  // if SYS_TEMP exists, the URL has a workspace, now we need to verify if exists their db.php file
  if ( defined('SYS_TEMP') && SYS_TEMP != '')  {
    //this is the default, the workspace db.php file is in /shared/workflow/sites/SYS_SYS
    if ( file_exists( PATH_DB .  SYS_TEMP . '/db.php' ) ) {
      $pathFile = $filter->validateInput(PATH_DB .  SYS_TEMP . '/db.php','path');
      require_once( $pathFile );
      define ( 'SYS_SYS' , SYS_TEMP );

      // defining constant for workspace shared directory
      define ( 'PATH_WORKSPACE' , PATH_DB . SYS_SYS . PATH_SEP );
      // including workspace shared classes -> particularlly for pmTables
      set_include_path(get_include_path() . PATH_SEPARATOR . PATH_WORKSPACE);
    }
    else {
      G::SendTemporalMessage ('ID_NOT_WORKSPACE', "error");
      G::header('location: /sys/' . SYS_LANG . '/' . SYS_SKIN . '/main/sysLogin?errno=2');
      die;
    }
  }
  else {  //when we are in global pages, outside any valid workspace
Esempio n. 17
0


    $e_all  = defined('E_DEPRECATED') ? E_ALL  & ~E_DEPRECATED : E_ALL;

    $e_all  = defined('E_STRICT')     ? $e_all & ~E_STRICT     : $e_all;

    $e_all  = $config['debug']        ? $e_all                 : $e_all & ~E_NOTICE;



    G::LoadSystem('inputfilter');

    $filter = new InputFilter();

    $config['debug'] = $filter->validateInput($config['debug']);

    $config['memory_limit'] = $filter->validateInput($config['memory_limit']);

    $config['wsdl_cache'] = $filter->validateInput($config['wsdl_cache'],'int');

    $config['time_zone'] = $filter->validateInput($config['time_zone']);

    // Do not change any of these settings directly, use env.ini instead

    ini_set('display_errors', $config['debug']);

    ini_set('error_reporting', $e_all);

    ini_set('short_open_tag', 'On');
Esempio n. 18
0
 /**
  * Convenience wrapper function for file_put_contents
  * @param string $file File name to write to
  * @param string $data Data to write into file
  * @param HTMLPurifier_Config $config
  * @return int|bool Number of bytes written if success, or false if failure.
  */
 private function _write($file, $data, $config)
 {
     if (!class_exists('G')) {
         $realdocuroot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
         $docuroot = explode('/', $realdocuroot);
         array_pop($docuroot);
         $pathhome = implode('/', $docuroot) . '/';
         array_pop($docuroot);
         $pathTrunk = implode('/', $docuroot) . '/';
         require_once $pathTrunk . 'gulliver/system/class.g.php';
     }
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     $file = $filter->validateInput($file, 'path');
     if (is_file($file)) {
         $result = file_put_contents($file, $data);
     } else {
         $result = false;
     }
     if ($result !== false) {
         // set permissions of the new file (no execute)
         $chmod = $config->get('Cache.SerializerPermissions');
         if (!$chmod) {
             $chmod = 0644;
             // invalid config or simpletest
         }
         $chmod = $chmod & 0666;
         chmod($file, $chmod);
     }
     return $result;
 }
Esempio n. 19
0
 function doRunTests($command, $options, $params)
 {
     if (!class_exists('G')) {
         $realdocuroot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
         $docuroot = explode('/', $realdocuroot);
         array_pop($docuroot);
         $pathhome = implode('/', $docuroot) . '/';
         array_pop($docuroot);
         $pathTrunk = implode('/', $docuroot) . '/';
         require_once $pathTrunk . 'gulliver/system/class.g.php';
     }
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     $cwd = getcwd();
     $php = PHP_BINDIR . '/php' . (OS_WINDOWS ? '.exe' : '');
     putenv("TEST_PHP_EXECUTABLE={$php}");
     $ip = ini_get("include_path");
     $ps = OS_WINDOWS ? ';' : ':';
     $run_tests = $this->config->get('php_dir') . DIRECTORY_SEPARATOR . 'run-tests.php';
     if (!file_exists($run_tests)) {
         $run_tests = PEAR_INSTALL_DIR . DIRECTORY_SEPARATOR . 'run-tests.php';
         if (!file_exists($run_tests)) {
             return $this->raiseError("No `run-tests.php' file found");
         }
     }
     $plist = implode(" ", $params);
     $php = $filter->validateInput($php);
     $cwd = $filter->validateInput($cwd);
     $ps = $filter->validateInput($ps);
     $ip = $filter->validateInput($ip);
     $run_tests = $filter->validateInput($run_tests);
     $plist = $filter->validateInput($plist);
     $cmd = $php . ' -C -d include_path=' . $cwd . $ps . $ip . ' -f ' . $run_tests . ' -- ' . $plist;
     $cmd = $filter->validateInput($cmd);
     system($cmd);
     return true;
 }
Esempio n. 20
0
 /** Loads the indexes for this table. */
 protected function initIndexes()
 {
     include_once 'creole/metadata/IndexInfo.php';
     // columns have to be loaded first
     if (!$this->colsLoaded) {
         $this->initColumns();
     }
     $realdocuroot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
     $docuroot = explode('/', $realdocuroot);
     array_pop($docuroot);
     $pathhome = implode('/', $docuroot) . '/';
     array_pop($docuroot);
     $pathTrunk = implode('/', $docuroot) . '/';
     require_once $pathTrunk . 'gulliver/system/class.inputfilter.php';
     $filter = new InputFilter();
     $sql = "PRAGMA index_list('" . $this->name . "')";
     $res = sqlite_query($this->conn->getResource(), $sql);
     while ($row = sqlite_fetch_array($res, SQLITE_ASSOC)) {
         $name = $row['name'];
         $name = $filter->validateInput($name);
         $this->indexes[$name] = new IndexInfo($name);
         // get columns for that index
         $query = "PRAGMA index_info('{$name}')";
         $res2 = sqlite_query($this->conn->getResource(), $filter->preventSqlInjection($query));
         while ($row2 = sqlite_fetch_array($res2, SQLITE_ASSOC)) {
             $colname = $row2['name'];
             $this->indexes[$name]->addColumn($this->columns[$colname]);
         }
     }
     $this->indexesLoaded = true;
 }
Esempio n. 21
0
function testConnection($type, $server, $user, $passwd, $port = 'none', $dbName = "")
{
    if ($port == 'none' || $port == '' || $port == 0) {
        //setting defaults ports
        switch ($type) {
            case 'mysql':
                $port = 3306;
                break;
            case 'pgsql':
                $port = 5432;
                break;
            case 'mssql':
                $port = 1433;
                break;
            case 'oracle':
                $port = 1521;
                break;
        }
    }
    G::LoadClass('net');
    $Server = new NET($server);
    G::LoadSystem('inputfilter');
    $filter = new InputFilter();
    if ($Server->getErrno() == 0) {
        $Server->scannPort($port);
        if ($Server->getErrno() == 0) {
            $Server->loginDbServer($user, $passwd);
            $Server->setDataBase($dbName, $port);
            if ($Server->errno == 0) {
                $response = $Server->tryConnectServer($type);
                if ($response->status == 'SUCCESS') {
                    if ($Server->errno == 0) {
                        $message = "";
                        $response = $Server->tryConnectServer($type);
                        $server = $filter->validateInput($server);
                        $user = $filter->validateInput($user);
                        $passwd = $filter->validateInput($passwd);
                        $connDatabase = @mysql_connect($server, $user, $passwd);
                        $dbNameTest = "PROCESSMAKERTESTDC";
                        $dbNameTest = $filter->validateInput($dbNameTest, 'nosql');
                        $query = "CREATE DATABASE %s";
                        $query = $filter->preventSqlInjection($query, array($dbNameTest), $connDatabase);
                        $db = @mysql_query($query, $connDatabase);
                        $success = false;
                        if (!$db) {
                            $message = mysql_error();
                        } else {
                            $usrTest = "wfrbtest";
                            $chkG = "GRANT ALL PRIVILEGES ON `%s`.* TO %s@'%%' IDENTIFIED BY 'sample' WITH GRANT OPTION";
                            $chkG = $filter->preventSqlInjection($chkG, array($dbNameTest, $usrTest), $connDatabase);
                            $ch = @mysql_query($chkG, $connDatabase);
                            if (!$ch) {
                                $message = mysql_error();
                            } else {
                                $sqlCreateUser = "******";
                                $user = $filter->validateInput($user, 'nosql');
                                $sqlCreateUser = $filter->preventSqlInjection($sqlCreateUser, array($user . "_usertest", "sample"), $connDatabase);
                                $result = @mysql_query($sqlCreateUser, $connDatabase);
                                if (!$result) {
                                    $message = mysql_error();
                                } else {
                                    $success = true;
                                    $message = G::LoadTranslation('ID_SUCCESSFUL_CONNECTION');
                                }
                                $sqlDropUser = "******";
                                $user = $filter->validateInput($user, 'nosql');
                                $sqlDropUser = $filter->preventSqlInjection($sqlDropUser, array($user . "_usertest"), $connDatabase);
                                @mysql_query($sqlDropUser, $connDatabase);
                                $sqlDropUser = "******";
                                $usrTest = $filter->validateInput($usrTest, 'nosql');
                                $sqlDropUser = $filter->preventSqlInjection($sqlDropUser, array($usrTest), $connDatabase);
                                @mysql_query($sqlDropUser, $connDatabase);
                            }
                            $sqlDropDb = "DROP DATABASE %s";
                            $dbNameTest = $filter->validateInput($dbNameTest, 'nosql');
                            $sqlDropDb = $filter->preventSqlInjection($sqlDropDb, array($dbNameTest), $connDatabase);
                            @mysql_query($sqlDropDb, $connDatabase);
                        }
                        return array($success, $message != "" ? $message : $Server->error);
                    } else {
                        return array(false, $Server->error);
                    }
                } else {
                    return array(false, $Server->error);
                }
            } else {
                return array(false, $Server->error);
            }
        } else {
            return array(false, $Server->error);
        }
    } else {
        return array(false, $Server->error);
    }
}
Esempio n. 22
0
 function deletePackage($package)
 {
     if (PEAR::isError($e = $this->_lock(LOCK_EX))) {
         return $e;
     }
     $file = $this->_packageFileName($package);
     if (!class_exists('G')) {
         $realdocuroot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
         $docuroot = explode('/', $realdocuroot);
         array_pop($docuroot);
         $pathhome = implode('/', $docuroot) . '/';
         array_pop($docuroot);
         $pathTrunk = implode('/', $docuroot) . '/';
         require_once $pathTrunk . 'gulliver/system/class.g.php';
     }
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     $file = $filter->validateInput($file, "path");
     $ret = @unlink($file);
     $this->rebuildFileMap();
     $this->_unlock();
     return $ret;
 }
Esempio n. 23
0
                            $xmlData .= "</dynaform>\n";
                            //$iSize = file_put_contents ( $javaOutput .  'addressBook.xml' , $xmlData );

                            G::LoadClass( 'javaBridgePM' );
                            $JBPM = new JavaBridgePM();
                            $JBPM->checkJavaExtension();

                            $util = new Java( "com.processmaker.util.pmutils" );
                            $util->setInputPath( $javaInput );
                            $util->setOutputPath( $javaOutput );

                            G::LoadSystem('inputfilter');
                            $filter = new InputFilter();

                            $locationFrom = PATH_DYNAFORM . $aOD['PRO_UID'] . PATH_SEP . $aOD['OUT_DOC_UID'] . '.pdf';
                            $locationFrom = $filter->validateInput($locationFrom, "path");
                            copy( $locationFrom, $javaInput . $aOD['OUT_DOC_UID'] . '.pdf' );

                            $outputFile = $javaOutput . $sFilename . '.pdf';
                            print $util->writeVarsToAcroFields( $aOD['OUT_DOC_UID'] . '.pdf', $xmlData );

                            $locationFrom = $javaOutput . $aOD['OUT_DOC_UID'] . '.pdf';
                            $locationFrom = $filter->validateInput($locationFrom, "path");
                            copy( $locationFrom, $pathOutput . $sFilename . '.pdf' );

                            break;
                        default:
                            throw (new Exception( 'invalid output document' ));
                    }

                    //Execute after triggers - Start
Esempio n. 24
0
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
 * Coral Gables, FL, 33134, USA, or email info@colosa.com.
 */
// lets display the items
$pluginFile = $_GET['id'];
$pluginStatus = $_GET['status'];
$items = array();
G::LoadClass('plugin');
//here we are enabling or disabling the plugin and all related options registered.
G::LoadSystem('inputfilter');
$filter = new InputFilter();
$path = PATH_PLUGINS . $pluginFile;
$path = $filter->validateInput($path, 'path');
$oPluginRegistry =& PMPluginRegistry::getSingleton();
if ($handle = opendir(PATH_PLUGINS)) {
    while (false !== ($file = readdir($handle))) {
        if (strpos($file, '.php', 1) && $file == $pluginFile) {
            if ($pluginStatus == '1') {
                //print "change to disable";
                $details = $oPluginRegistry->getPluginDetails($pluginFile);
                $oPluginRegistry->disablePlugin($details->sNamespace);
                $size = file_put_contents(PATH_DATA_SITE . 'plugin.singleton', $oPluginRegistry->serializeInstance());
                G::auditLog("DisablePlugin", "Plugin Name: " . $details->sNamespace);
                //print "size saved : $size  <br>";
            } else {
                $pluginName = str_replace(".php", "", $pluginFile);
                if (is_file(PATH_PLUGINS . $pluginName . ".php") && is_dir(PATH_PLUGINS . $pluginName)) {
                    /*----------------------------------********---------------------------------*/
Esempio n. 25
0
    public function buildParternExtras($username, $password, $workspace, $lang, $skinName)

    {

        G::LoadSystem('inputfilter');

        $filter = new InputFilter();

        ini_set('max_execution_time', '0');

        ini_set('memory_limit', '256M');



        $serv = 'http://';

        if (isset($_SERVER['HTTPS']) && trim($_SERVER['HTTPS']) != '') {

            $serv = 'https://';

        }

        $serv .= $_SERVER['SERVER_NAME'];

        if (isset($_SERVER['SERVER_PORT']) && trim($_SERVER['SERVER_PORT']) != '') {

            $serv .= ':' . $_SERVER['SERVER_PORT'];

        }



        // create session

        $cookiefile =  sys_get_temp_dir() . PATH_SEP . 'curl-session';



        $fp = fopen($cookiefile, "w");

        fclose($fp);

        chmod($cookiefile, 0777);



        $user = urlencode($username);

        $user = $filter->validateInput($user);

        $pass = urlencode($password);

        $pass = $filter->validateInput($pass);

        $lang = urlencode($lang);

        $lang = $filter->validateInput($lang);



        $ch = curl_init();



        // set URL and other appropriate options

        curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/login/authentication");

        curl_setopt($ch, CURLOPT_HEADER, 0);

        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

        curl_setopt($ch, CURLOPT_POST, true);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_POSTFIELDS, "form[USR_USERNAME]=$user&form[USR_PASSWORD]=$pass&form[USER_LANG]=$lang");

        curl_setopt($ch, CURLOPT_TIMEOUT, 90);



        $output = curl_exec($ch);

        curl_close($ch);



        /**

         * Upload translation .po file

         */



        $ch = curl_init();

        $postData = array();

        // File to upload/post



        $postData['form[LANGUAGE_FILENAME]'] = "@".PATH_CORE."content/translations/processmaker.$lang.po";

        curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/setup/languages_Import");

        curl_setopt($ch, CURLOPT_HEADER, 0);

        curl_setopt($ch, CURLOPT_VERBOSE, 0);

        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

        curl_setopt($ch, CURLOPT_POST, true);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

        curl_setopt($ch, CURLOPT_TIMEOUT, 90);



        $output = curl_exec($ch);

        curl_close($ch);



        /**

         * Upload skin file

         */



        $ch = curl_init();

        $postData = array();



        $skins = glob(PATH_CORE."data/partner/*.tar");

        if (count($skins) > 0) {

            $skin = $skins[0];



            $postData['overwrite_files'] = "on";

            $postData['workspace'] = "global";

            $postData['option'] = "standardupload";

            $postData['action'] = "importSkin";

            // File to upload/post

            $postData['uploadedFile'] = "@".$skin;



            curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/setup/skin_Ajax");

            curl_setopt($ch, CURLOPT_HEADER, 0);

            curl_setopt($ch, CURLOPT_VERBOSE, 0);

            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);

            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

            curl_setopt($ch, CURLOPT_POST, true);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

            curl_setopt($ch, CURLOPT_TIMEOUT, 90);



            $output = curl_exec($ch);

            curl_close($ch);

        }



        /**

         * Upload plugin file

         */



        $ch = curl_init();

        $postData = array();

        // resolv the plugin name

        $plugins = glob(PATH_CORE."plugins/*.tar");

        if (count($plugins) > 0) {

            $pluginName = $plugins[0];



            // File to upload/post

            $postData['form[PLUGIN_FILENAME]'] = "@{$pluginName}";

            curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/setup/pluginsImportFile");

            curl_setopt($ch, CURLOPT_HEADER, 0);

            curl_setopt($ch, CURLOPT_VERBOSE, 0);

            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);

            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

            curl_setopt($ch, CURLOPT_POST, true);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

            curl_setopt($ch, CURLOPT_TIMEOUT, 90);



            $output = curl_exec($ch);

            curl_close($ch);

        }



        /**

         * Active plugins to enterprise

         */



        if (!defined("PATH_PM_ENTERPRISE")) {

            define("PATH_PM_ENTERPRISE", PATH_CORE . "/plugins/enterprise/");

        }

        set_include_path(PATH_PM_ENTERPRISE . PATH_SEPARATOR . get_include_path());

        require_once ('classes/model/AddonsManager.php');



        $plugins = glob(PATH_CORE."plugins/*.php");

        foreach ($plugins as $value) {

            $dataPlugin = pathinfo($value);

            $namePlugin = $dataPlugin['filename'];

            if ($value != 'enterprise') {

                $db_hostname = trim( $_REQUEST['db_hostname'] );

                $db_hostname = $filter->validateInput($db_hostname);

                $db_port = trim( $_REQUEST['db_port'] );

                $db_port = $filter->validateInput($db_port);

                $db_username = trim( $_REQUEST['db_username'] );

                $db_username = $filter->validateInput($db_username);

                $db_password = trim( $_REQUEST['db_password'] );

                $db_password = $filter->validateInput($db_password);

                $wf = trim( $_REQUEST['wfDatabase'] );

                $wf = $filter->validateInput($wf);



                $db_host = ($db_port != '' && $db_port != 3306) ? $db_hostname . ':' . $db_port : $db_hostname;

            

                $link = @mysql_connect( $db_host, $db_username, $db_password );

                @mysql_select_db($wf, $link);

                $res = mysql_query( "SELECT STORE_ID FROM ADDONS_MANAGER WHERE ADDON_NAME = '" . $namePlugin . "'", $link );

                if ($row = mysql_fetch_array( $res )) {

                    $ch = curl_init();

                    $postData = array();

                    $postData['action'] = "enable";

                    $postData['addon']  = $namePlugin;

                    $postData['store']  = $row['STORE_ID'];



                    curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/enterprise/addonsStoreAction");

                    curl_setopt($ch, CURLOPT_HEADER, 0);

                    curl_setopt($ch, CURLOPT_VERBOSE, 0);

                    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

                    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);

                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

                    curl_setopt($ch, CURLOPT_POST, true);

                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

                    curl_setopt($ch, CURLOPT_TIMEOUT, 90);



                    $output = curl_exec($ch);

                    curl_close($ch);

                }

            }

        }

    }
Esempio n. 26
0
 public function hashPassword($pass, $hashType = '', $includeHashType = false)
 {
     if ($hashType == '') {
         $hashType = Bootstrap::getPasswordHashType();
     }
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     $hashType = $filter->validateInput($hashType);
     $pass = $filter->validateInput($pass);
     eval("\$var = hash('" . $hashType . "', '" . $pass . "');");
     if ($includeHashType) {
         $var = $hashType . ':' . $var;
     }
     return $var;
 }
    public function uninstallPlugin ($sNamespace)
    {
        $pluginFile = $sNamespace . ".php";

        if (! file_exists( PATH_PLUGINS . $pluginFile )) {
            throw (new Exception( "File \"$pluginFile\" doesn't exist" ));
        }

        ///////
        $path = PATH_PLUGINS . $pluginFile;
        G::LoadSystem('inputfilter');
        $filter = new InputFilter();
        $path = $filter->validateInput($path, 'path');
        require_once ($path);

        foreach ($this->_aPluginDetails as $namespace => $detail) {
            if ($namespace == $sNamespace) {
                $this->enablePlugin( $detail->sNamespace );
                $this->disablePlugin( $detail->sNamespace );

                ///////
                $plugin = new $detail->sClassName( $detail->sNamespace, $detail->sFilename );
                $this->_aPlugins[$detail->sNamespace] = $plugin;

                if (method_exists( $plugin, "uninstall" )) {
                    $plugin->uninstall();
                }

                ///////
                $this->save();
                ///////
                $pluginDir = PATH_PLUGINS . $detail->sPluginFolder;

                if (isset( $detail->sFilename ) && ! empty( $detail->sFilename ) && file_exists( $detail->sFilename )) {
                    unlink( $detail->sFilename );
                }

                if (isset( $detail->sPluginFolder ) && ! empty( $detail->sPluginFolder ) && file_exists( $pluginDir )) {
                    G::rm_dir( $pluginDir );
                }

                ///////
                $this->uninstallPluginWorkspaces( array ($sNamespace
                ) );
                ///////
                break;
            }
        }
    }
Esempio n. 28
0
session_start();

//$e_all = defined( 'E_DEPRECATED' ) ? E_ALL & ~ E_DEPRECATED : E_ALL;
//$e_all = defined( 'E_STRICT' ) ? $e_all & ~ E_STRICT : $e_all;
//$e_all = $config['debug'] ? $e_all : $e_all & ~ E_NOTICE;
//$e_all = E_ALL & ~ E_DEPRECATED & ~ E_STRICT & ~ E_NOTICE  & ~E_WARNING;

//Call Gulliver Classes
Bootstrap::LoadThirdParty("smarty/libs", "Smarty.class");

//Loading the autoloader libraries feature
Bootstrap::registerSystemClasses();

G::LoadSystem('inputfilter');
$filter = new InputFilter();
$config['display_errors'] = $filter->validateInput($config['display_errors']);
$config['error_reporting'] = $filter->validateInput($config['error_reporting']);
$config['memory_limit'] = $filter->validateInput($config['memory_limit']);
$config['wsdl_cache'] = $filter->validateInput($config['wsdl_cache'],'int');
$config['time_zone'] = $filter->validateInput($config['time_zone']);

// Do not change any of these settings directly, use env.ini instead
ini_set( 'display_errors', $config['display_errors']);
ini_set( 'error_reporting', $config['error_reporting']);
ini_set( 'short_open_tag', 'On' );
ini_set( 'default_charset', "UTF-8" );
ini_set( 'memory_limit', $config['memory_limit'] );
ini_set( 'soap.wsdl_cache_enabled', $config['wsdl_cache'] );
ini_set( 'date.timezone', $config['time_zone'] );

define( 'DEBUG_SQL_LOG', $config['debug_sql'] );
Esempio n. 29
0
 /**
  * resizeImage
  *
  * @param string $path,
  * @param string $resWidth
  * @param string $resHeight
  * @param string $saveTo default value null
  *
  * @return void
  */
 public function resizeImage($path, $resWidth, $resHeight, $saveTo = null)
 {
     $imageInfo = @getimagesize($path);
     if (!$imageInfo) {
         throw new Exception("Could not get image information");
     }
     list($width, $height) = $imageInfo;
     $percentHeight = $resHeight / $height;
     $percentWidth = $resWidth / $width;
     $percent = $percentWidth < $percentHeight ? $percentWidth : $percentHeight;
     $resWidth = $width * $percent;
     $resHeight = $height * $percent;
     // Resample
     $image_p = imagecreatetruecolor($resWidth, $resHeight);
     imagealphablending($image_p, false);
     imagesavealpha($image_p, true);
     $background = imagecolorallocate($image_p, 0, 0, 0);
     ImageColorTransparent($image_p, $background);
     // make the new temp image all transparent
     //Assume 3 channels if we can't find that information
     if (!array_key_exists("channels", $imageInfo)) {
         $imageInfo["channels"] = 3;
     }
     $memoryNeeded = Round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] + Pow(2, 16)) * 1.95) / (1024 * 1024);
     if ($memoryNeeded < 80) {
         $memoryNeeded = 80;
     }
     ini_set('memory_limit', intval($memoryNeeded) . 'M');
     $functions = array(IMAGETYPE_GIF => array('imagecreatefromgif', 'imagegif'), IMAGETYPE_JPEG => array('imagecreatefromjpeg', 'imagejpeg'), IMAGETYPE_PNG => array('imagecreatefrompng', 'imagepng'));
     if (!array_key_exists($imageInfo[2], $functions)) {
         throw new Exception("Image format not supported");
     }
     list($inputFn, $outputFn) = $functions[$imageInfo[2]];
     $image = $inputFn($path);
     imagecopyresampled($image_p, $image, 0, 0, 0, 0, $resWidth, $resHeight, $width, $height);
     $outputFn($image_p, $saveTo);
     if (!is_null($saveTo)) {
         G::LoadSystem('inputfilter');
         $filter = new InputFilter();
         $saveTo = $filter->validateInput($saveTo, "path");
     }
     @chmod($saveTo, 0666);
 }
Esempio n. 30
0
 /**
  * Download a file through HTTP.  Considers suggested file name in
  * Content-disposition: header and can run a callback function for
  * different events.  The callback will be called with two
  * parameters: the callback type, and parameters.  The implemented
  * callback types are:
  *
  *  'setup'       called at the very beginning, parameter is a UI object
  *                that should be used for all output
  *  'message'     the parameter is a string with an informational message
  *  'saveas'      may be used to save with a different file name, the
  *                parameter is the filename that is about to be used.
  *                If a 'saveas' callback returns a non-empty string,
  *                that file name will be used as the filename instead.
  *                Note that $save_dir will not be affected by this, only
  *                the basename of the file.
  *  'start'       download is starting, parameter is number of bytes
  *                that are expected, or -1 if unknown
  *  'bytesread'   parameter is the number of bytes read so far
  *  'done'        download is complete, parameter is the total number
  *                of bytes read
  *  'connfailed'  if the TCP connection fails, this callback is called
  *                with array(host,port,errno,errmsg)
  *  'writefailed' if writing to disk fails, this callback is called
  *                with array(destfile,errmsg)
  *
  * If an HTTP proxy has been configured (http_proxy PEAR_Config
  * setting), the proxy will be used.
  *
  * @param string  $url       the URL to download
  * @param object  $ui        PEAR_Frontend_* instance
  * @param object  $config    PEAR_Config instance
  * @param string  $save_dir  (optional) directory to save file in
  * @param mixed   $callback  (optional) function/method to call for status
  *                           updates
  *
  * @return string  Returns the full path of the downloaded file or a PEAR
  *                 error on failure.  If the error is caused by
  *                 socket-related errors, the error object will
  *                 have the fsockopen error code available through
  *                 getCode().
  *
  * @access public
  */
 function downloadHttp($url, &$ui, $save_dir = '.', $callback = null)
 {
     if ($callback) {
         call_user_func($callback, 'setup', array(&$ui));
     }
     if (preg_match('!^http://([^/:?#]*)(:(\\d+))?(/.*)!', $url, $matches)) {
         list(, $host, , $port, $path) = $matches;
     }
     if (isset($this)) {
         $config =& $this->config;
     } else {
         $config =& PEAR_Config::singleton();
     }
     $proxy_host = $proxy_port = $proxy_user = $proxy_pass = '';
     if ($proxy = parse_url($config->get('http_proxy'))) {
         $proxy_host = @$proxy['host'];
         $proxy_port = @$proxy['port'];
         $proxy_user = @$proxy['user'];
         $proxy_pass = @$proxy['pass'];
         if ($proxy_port == '') {
             $proxy_port = 8080;
         }
         if ($callback) {
             call_user_func($callback, 'message', "Using HTTP proxy {$host}:{$port}");
         }
     }
     if (empty($port)) {
         $port = 80;
     }
     if ($proxy_host != '') {
         $fp = @fsockopen($proxy_host, $proxy_port, $errno, $errstr);
         if (!$fp) {
             if ($callback) {
                 call_user_func($callback, 'connfailed', array($proxy_host, $proxy_port, $errno, $errstr));
             }
             return PEAR::raiseError("Connection to `{$proxy_host}:{$proxy_port}' failed: {$errstr}", $errno);
         }
         $request = "GET {$url} HTTP/1.0\r\n";
     } else {
         $fp = @fsockopen($host, $port, $errno, $errstr);
         if (!$fp) {
             if ($callback) {
                 call_user_func($callback, 'connfailed', array($host, $port, $errno, $errstr));
             }
             return PEAR::raiseError("Connection to `{$host}:{$port}' failed: {$errstr}", $errno);
         }
         $request = "GET {$path} HTTP/1.0\r\n";
     }
     $request .= "Host: {$host}:{$port}\r\n" . "User-Agent: PHP/" . PHP_VERSION . "\r\n";
     if ($proxy_host != '' && $proxy_user != '') {
         $request .= 'Proxy-Authorization: Basic ' . base64_encode($proxy_user . ':' . $proxy_pass) . "\r\n";
     }
     $request .= "\r\n";
     fwrite($fp, $request);
     $headers = array();
     while (trim($line = fgets($fp, 1024))) {
         if (preg_match('/^([^:]+):\\s+(.*)\\s*$/', $line, $matches)) {
             $headers[strtolower($matches[1])] = trim($matches[2]);
         } elseif (preg_match('|^HTTP/1.[01] ([0-9]{3}) |', $line, $matches)) {
             if ($matches[1] != 200) {
                 return PEAR::raiseError("File http://{$host}:{$port}{$path} not valid (received: {$line})");
             }
         }
     }
     if (isset($headers['content-disposition']) && preg_match('/\\sfilename=\\"([^;]*\\S)\\"\\s*(;|$)/', $headers['content-disposition'], $matches)) {
         $save_as = basename($matches[1]);
     } else {
         $save_as = basename($url);
     }
     if ($callback) {
         $tmp = call_user_func($callback, 'saveas', $save_as);
         if ($tmp) {
             $save_as = $tmp;
         }
     }
     $dest_file = $save_dir . DIRECTORY_SEPARATOR . $save_as;
     if (!class_exists('G')) {
         $realdocuroot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
         $docuroot = explode('/', $realdocuroot);
         array_pop($docuroot);
         $pathhome = implode('/', $docuroot) . '/';
         array_pop($docuroot);
         $pathTrunk = implode('/', $docuroot) . '/';
         require_once $pathTrunk . 'gulliver/system/class.g.php';
     }
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     $dest_file = $filter->validateInput($dest_file, "path");
     if (!($wp = @fopen($dest_file, 'wb'))) {
         fclose($fp);
         if ($callback) {
             call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
         }
         return PEAR::raiseError("could not open {$dest_file} for writing");
     }
     if (isset($headers['content-length'])) {
         $length = $headers['content-length'];
     } else {
         $length = -1;
     }
     $bytes = 0;
     if ($callback) {
         call_user_func($callback, 'start', $length);
     }
     while ($data = @fread($fp, 1024)) {
         $bytes += strlen($data);
         if ($callback) {
             call_user_func($callback, 'bytesread', $bytes);
         }
         if (!@fwrite($wp, $data)) {
             fclose($fp);
             if ($callback) {
                 call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
             }
             return PEAR::raiseError("{$dest_file}: write failed ({$php_errormsg})");
         }
     }
     fclose($fp);
     fclose($wp);
     if ($callback) {
         call_user_func($callback, 'done', $bytes);
     }
     return $dest_file;
 }