Example #1
0
 /**
  * @param $datasource
  * @param $options
  * @param $dbspec
  * @param $debug
  * @param null $target
  * @return bool
  */
 function initialize($datasource, $options, $dbspec, $debug, $target = null)
 {
     $this->setUpSharedObjects();
     $currentDir = dirname(__FILE__) . DIRECTORY_SEPARATOR;
     $currentDirParam = $currentDir . 'params.php';
     $parentDirParam = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'params.php';
     if (file_exists($parentDirParam)) {
         include $parentDirParam;
     } else {
         if (file_exists($currentDirParam)) {
             include $currentDirParam;
         }
     }
     $this->clientPusherAvailable = isset($_POST["pusher"]) && $_POST["pusher"] == "yes";
     $this->dbSettings->setDataSource($datasource);
     $this->dbSettings->setOptions($options);
     $this->dbSettings->setDbSpec($dbspec);
     $this->dbSettings->setSeparator(isset($options['separator']) ? $options['separator'] : '@');
     $this->formatter->setFormatter(isset($options['formatter']) ? $options['formatter'] : null);
     $this->dbSettings->setDataSourceName(!is_null($target) ? $target : (isset($_POST['name']) ? $_POST['name'] : "_im_auth"));
     $context = $this->dbSettings->getDataSourceTargetArray();
     $dbClassName = 'DB_' . (isset($context['db-class']) ? $context['db-class'] : (isset($dbspec['db-class']) ? $dbspec['db-class'] : (isset($dbClass) ? $dbClass : '')));
     $this->dbSettings->setDbSpecServer(isset($context['server']) ? $context['server'] : (isset($dbspec['server']) ? $dbspec['server'] : (isset($dbServer) ? $dbServer : '')));
     $this->dbSettings->setDbSpecPort(isset($context['port']) ? $context['port'] : (isset($dbspec['port']) ? $dbspec['port'] : (isset($dbPort) ? $dbPort : '')));
     $this->dbSettings->setDbSpecUser(isset($context['user']) ? $context['user'] : (isset($dbspec['user']) ? $dbspec['user'] : (isset($dbUser) ? $dbUser : '')));
     $this->dbSettings->setDbSpecPassword(isset($context['password']) ? $context['password'] : (isset($dbspec['password']) ? $dbspec['password'] : (isset($dbPassword) ? $dbPassword : '')));
     $this->dbSettings->setDbSpecDataType(isset($context['datatype']) ? $context['datatype'] : (isset($dbspec['datatype']) ? $dbspec['datatype'] : (isset($dbDataType) ? $dbDataType : '')));
     $this->dbSettings->setDbSpecDatabase(isset($context['database']) ? $context['database'] : (isset($dbspec['database']) ? $dbspec['database'] : (isset($dbDatabase) ? $dbDatabase : '')));
     $this->dbSettings->setDbSpecProtocol(isset($context['protocol']) ? $context['protocol'] : (isset($dbspec['protocol']) ? $dbspec['protocol'] : (isset($dbProtocol) ? $dbProtocol : '')));
     $this->dbSettings->setDbSpecOption(isset($context['option']) ? $context['option'] : (isset($dbspec['option']) ? $dbspec['option'] : (isset($dbOption) ? $dbOption : '')));
     if (isset($options['authentication']) && isset($options['authentication']['issuedhash-dsn'])) {
         $this->dbSettings->setDbSpecDSN($options['authentication']['issuedhash-dsn']);
     } else {
         $this->dbSettings->setDbSpecDSN(isset($context['dsn']) ? $context['dsn'] : (isset($dbspec['dsn']) ? $dbspec['dsn'] : (isset($dbDSN) ? $dbDSN : '')));
     }
     $pusherParams = null;
     if (isset($pusherParameters)) {
         $pusherParams = $pusherParameters;
     } else {
         if (isset($options['pusher'])) {
             $pusherParams = $options['pusher'];
         }
     }
     if (!is_null($pusherParams)) {
         $this->dbSettings->pusherAppId = $pusherParams['app_id'];
         $this->dbSettings->pusherKey = $pusherParams['key'];
         $this->dbSettings->pusherSecret = $pusherParams['secret'];
         if (isset($pusherParams['channel'])) {
             $this->dbSettings->pusherChannel = $pusherParams['channel'];
         }
     }
     /* Setup Database Class's Object */
     require_once "{$dbClassName}.php";
     $this->dbClass = new $dbClassName();
     if ($this->dbClass == null) {
         $this->logger->setErrorMessage("The database class [{$dbClassName}] that you specify is not valid.");
         echo implode('', $this->logger->getMessagesForJS());
         return false;
     }
     $this->dbClass->setUpSharedObjects($this);
     $this->dbClass->setupConnection();
     if ((!isset($prohibitDebugMode) || !$prohibitDebugMode) && $debug) {
         $this->logger->setDebugMode($debug);
     }
     $this->logger->setDebugMessage("The class '{$dbClassName}' was instanciated.", 2);
     $this->dbSettings->setAggregationSelect(isset($context['aggregation-select']) ? $context['aggregation-select'] : null);
     $this->dbSettings->setAggregationFrom(isset($context['aggregation-from']) ? $context['aggregation-from'] : null);
     $this->dbSettings->setAggregationGroupBy(isset($context['aggregation-group-by']) ? $context['aggregation-group-by'] : null);
     /* Authentication and Authorization Judgement */
     $challengeDSN = null;
     if (isset($options['authentication']) && isset($options['authentication']['issuedhash-dsn'])) {
         $challengeDSN = $options['authentication']['issuedhash-dsn'];
     } else {
         if (isset($issuedHashDSN)) {
             $challengeDSN = $issuedHashDSN;
         }
     }
     if (!is_null($challengeDSN)) {
         require_once "DB_PDO.php";
         $this->authDbClass = new DB_PDO();
         $this->authDbClass->setUpSharedObjects($this);
         $this->authDbClass->setupWithDSN($challengeDSN);
         $this->logger->setDebugMessage("The class 'DB_PDO' was instanciated for issuedhash with {$challengeDSN}.", 2);
     } else {
         $this->authDbClass = $this->dbClass;
     }
     $this->dbSettings->notifyServer = null;
     if ($this->clientPusherAvailable) {
         require_once "NotifyServer.php";
         $this->dbSettings->notifyServer = new NotifyServer();
         if (isset($_POST['notifyid']) && $this->dbSettings->notifyServer->initialize($this->authDbClass, $this->dbSettings, $_POST['notifyid'])) {
             $this->logger->setDebugMessage("The NotifyServer was instanciated.", 2);
         }
     }
     $this->dbSettings->setCurrentDataAccess($this->dbClass);
     if (isset($context['extending-class'])) {
         $className = $context['extending-class'];
         $this->userExpanded = new $className();
         if ($this->userExpanded === null) {
             $this->logger->setErrorMessage("The class '{$className}' wasn't instanciated.");
         } else {
             $this->logger->setDebugMessage("The class '{$className}' was instanciated.", 2);
         }
         if (is_subclass_of($this->userExpanded, 'DB_UseSharedObjects')) {
             $this->userExpanded->setUpSharedObjects($this);
         }
     }
     $this->dbSettings->setPrimaryKeyOnly(isset($_POST['pkeyonly']));
     $this->dbSettings->setCurrentUser(isset($_POST['authuser']) ? $_POST['authuser'] : null);
     $this->dbSettings->setAuthentication(isset($options['authentication']) ? $options['authentication'] : null);
     $this->dbSettings->setStart(isset($_POST['start']) ? $_POST['start'] : 0);
     $this->dbSettings->setRecordCount(isset($_POST['records']) ? $_POST['records'] : 10000000);
     for ($count = 0; $count < 10000; $count++) {
         if (isset($_POST["condition{$count}field"])) {
             $this->dbSettings->addExtraCriteria($_POST["condition{$count}field"], isset($_POST["condition{$count}operator"]) ? $_POST["condition{$count}operator"] : '=', isset($_POST["condition{$count}value"]) ? $_POST["condition{$count}value"] : null);
         } else {
             break;
         }
     }
     for ($count = 0; $count < 10000; $count++) {
         if (isset($_POST["sortkey{$count}field"])) {
             $this->dbSettings->addExtraSortKey($_POST["sortkey{$count}field"], $_POST["sortkey{$count}direction"]);
         } else {
             break;
         }
     }
     for ($count = 0; $count < 10000; $count++) {
         if (!isset($_POST["foreign{$count}field"])) {
             break;
         }
         $this->dbSettings->addForeignValue($_POST["foreign{$count}field"], $_POST["foreign{$count}value"]);
     }
     for ($i = 0; $i < 1000; $i++) {
         if (!isset($_POST["field_{$i}"])) {
             break;
         }
         $this->dbSettings->addTargetField($_POST["field_{$i}"]);
     }
     for ($i = 0; $i < 1000; $i++) {
         if (!isset($_POST["value_{$i}"])) {
             break;
         }
         $value = IMUtil::removeNull(filter_var($_POST["value_{$i}"]));
         $this->dbSettings->addValue(get_magic_quotes_gpc() ? stripslashes($value) : $value);
     }
     if (isset($options['authentication']) && isset($options['authentication']['email-as-username'])) {
         $this->dbSettings->setEmailAsAccount($options['authentication']['email-as-username']);
     } else {
         if (isset($emailAsAliasOfUserName) && $emailAsAliasOfUserName) {
             $this->dbSettings->setEmailAsAccount($emailAsAliasOfUserName);
         }
     }
     for ($i = 0; $i < 1000; $i++) {
         if (!isset($_POST["assoc{$i}"])) {
             break;
         }
         $this->dbSettings->addAssociated($_POST["assoc{$i}"], $_POST["asfield{$i}"], $_POST["asvalue{$i}"]);
     }
     if (isset($options['smtp'])) {
         $this->dbSettings->setSmtpConfiguration($options['smtp']);
     }
     $this->paramAuthUser = isset($_POST['authuser']) ? $_POST['authuser'] : "";
     $this->paramResponse = isset($_POST['response']) ? $_POST['response'] : "";
     $this->paramCryptResponse = isset($_POST['cresponse']) ? $_POST['cresponse'] : "";
     $this->clientId = isset($_POST['clientid']) ? $_POST['clientid'] : (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : "Non-browser-client");
 }
Example #2
0
 public function test_removeNull()
 {
     $str = IMUtil::removeNull("INTER-Mediator");
     $this->assertEquals($str, "INTER-Mediator");
 }
 function processing($dbProxyInstance, $options, $file)
 {
     try {
         // It the $file ('media'parameter) isn't specified, it doesn't respond an error.
         if (strlen($file) === 0) {
             $this->exitAsError(204);
         }
         // If the media parameter is an URL, the variable isURL will be set to true.
         $schema = array("https:", "http:", "class:");
         $isURL = false;
         foreach ($schema as $scheme) {
             if (strpos($file, $scheme) === 0) {
                 $isURL = true;
                 break;
             }
         }
         list($file, $isURL) = $this->checkForFileMakerMedia($dbProxyInstance, $options, $file, $isURL);
         /*
          * If the FileMaker's object field is storing a PDF, the $file could be "http://server:16000/...
          * style URL. In case of an image, $file is just the path info as like above.
          */
         $util = new IMUtil();
         $file = $util->removeNull($file);
         if (strpos($file, '../') !== false) {
             return;
         }
         $target = $isURL ? $file : "{$options['media-root-dir']}/{$file}";
         if (isset($options['media-context'])) {
             $this->checkAuthentication($dbProxyInstance, $options, $target);
         }
         $content = false;
         $dq = '"';
         if (!$isURL) {
             // File path.
             if (!empty($file) && !file_exists($target)) {
                 $this->exitAsError(500);
             }
             $content = file_get_contents($target);
             $fileName = basename($file);
             $qPos = strpos($fileName, "?");
             if ($qPos !== false) {
                 $fileName = substr($fileName, 0, $qPos);
             }
             header("Content-Type: " . $this->getMimeType($fileName));
             header("Content-Length: " . strlen($content));
             header("Content-Disposition: {$this->disposition}; filename={$dq}" . urlencode($fileName) . $dq);
             header('X-XSS-Protection: 1; mode=block');
             header('X-Frame-Options: SAMEORIGIN');
             $this->outputImage($content);
         } else {
             if (stripos($target, 'http://') === 0 || stripos($target, 'https://') === 0) {
                 // http or https
                 if (intval(get_cfg_var('allow_url_fopen')) === 1) {
                     $content = file_get_contents($target);
                 } else {
                     if (function_exists('curl_init')) {
                         $session = curl_init($target);
                         curl_setopt($session, CURLOPT_HEADER, false);
                         curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
                         $content = curl_exec($session);
                         curl_close($session);
                     } else {
                         $this->exitAsError(500);
                     }
                 }
                 $fileName = basename($file);
                 $qPos = strpos($fileName, "?");
                 if ($qPos !== false) {
                     $fileName = str_replace("%20", " ", substr($fileName, 0, $qPos));
                 }
                 header("Content-Type: " . $this->getMimeType($fileName));
                 header("Content-Length: " . strlen($content));
                 header("Content-Disposition: {$this->disposition}; filename={$dq}" . str_replace("+", "%20", urlencode($fileName)) . $dq);
                 header('X-XSS-Protection: 1; mode=block');
                 header('X-Frame-Options: SAMEORIGIN');
                 $this->outputImage($content);
             } else {
                 if (stripos($target, 'class://') === 0) {
                     // class
                     $noscheme = substr($target, 8);
                     $className = substr($noscheme, 0, strpos($noscheme, "/"));
                     $processingObject = new $className();
                     $processingObject->processing($this->contextRecord, $options);
                 }
             }
         }
     } catch (Exception $ex) {
         // do nothing
     }
 }
 public function processing($datasource, $options, $dbspec, $debug)
 {
     $dbProxyInstance = new DB_Proxy();
     $this->db = $dbProxyInstance;
     $dbProxyInstance->initialize($datasource, $options, $dbspec, $debug, $_POST["_im_contextname"]);
     $useContainer = FALSE;
     $dbProxyContext = $dbProxyInstance->dbSettings->getDataSourceTargetArray();
     if ($dbspec['db-class'] === 'FileMaker_FX' && isset($dbProxyContext['file-upload'])) {
         foreach ($dbProxyContext['file-upload'] as $item) {
             if (isset($item['container']) && (bool) $item['container'] === TRUE) {
                 $useContainer = TRUE;
             }
         }
     }
     $url = NULL;
     if (isset($_POST['_im_redirect'])) {
         $url = $this->getRedirectUrl($_POST['_im_redirect']);
         if (is_null($url)) {
             header("HTTP/1.1 500 Internal Server Error");
             $dbProxyInstance->logger->setErrorMessage('Header may not contain more than a single header, new line detected.');
             $dbProxyInstance->processingRequest($options, 'noop');
             $dbProxyInstance->finishCommunication();
             $dbProxyInstance->exportOutputDataAsJSON();
             return;
         }
     }
     if (!isset($options['media-root-dir']) && $useContainer === FALSE) {
         if (!is_null($url)) {
             header('Location: ' . $url);
         } else {
             $dbProxyInstance->logger->setErrorMessage("'media-root-dir' isn't specified");
             $dbProxyInstance->processingRequest($options, "noop");
             $dbProxyInstance->finishCommunication();
             $dbProxyInstance->exportOutputDataAsJSON();
         }
         return;
     }
     if ($useContainer === FALSE) {
         // requires media-root-dir specification.
         $fileRoot = $options['media-root-dir'];
         if (substr($fileRoot, strlen($fileRoot) - 1, 1) !== '/') {
             $fileRoot .= '/';
         }
     }
     if (count($_FILES) < 1) {
         if (!is_null($url)) {
             header('Location: ' . $url);
         } else {
             $dbProxyInstance->logger->setErrorMessage("No file wasn't uploaded.");
             $dbProxyInstance->processingRequest($options, "noop");
             $dbProxyInstance->finishCommunication();
             $dbProxyInstance->exportOutputDataAsJSON();
         }
         return;
     }
     foreach ($_FILES as $fn => $fileInfo) {
     }
     $util = new IMUtil();
     $filePathInfo = pathinfo($util->removeNull(basename($fileInfo['name'])));
     if ($useContainer === FALSE) {
         $fileRoot = $options['media-root-dir'];
         if (substr($fileRoot, strlen($fileRoot) - 1, 1) != '/') {
             $fileRoot .= '/';
         }
         $dirPath = str_replace('.', '_', urlencode($_POST["_im_contextname"])) . '/' . str_replace('.', '_', urlencode($_POST["_im_keyfield"])) . "=" . str_replace('.', '_', urlencode($_POST["_im_keyvalue"])) . '/' . str_replace('.', '_', urlencode($_POST["_im_field"]));
         $rand4Digits = rand(1000, 9999);
         $filePartialPath = $dirPath . '/' . $filePathInfo['filename'] . '_' . $rand4Digits . '.' . $filePathInfo['extension'];
         $filePath = $fileRoot . $filePartialPath;
         if (strpos($filePath, $fileRoot) !== 0) {
             $dbProxyInstance->logger->setErrorMessage("Invalid Path Error.");
             $dbProxyInstance->processingRequest($options, "noop");
             $dbProxyInstance->finishCommunication();
             $dbProxyInstance->exportOutputDataAsJSON();
             return;
         }
         if (!file_exists($fileRoot . $dirPath)) {
             $result = mkdir($fileRoot . $dirPath, 0744, true);
             if (!$result) {
                 $dbProxyInstance->logger->setErrorMessage("Can't make directory. [{$dirPath}]");
                 $dbProxyInstance->processingRequest($options, "noop");
                 $dbProxyInstance->finishCommunication();
                 $dbProxyInstance->exportOutputDataAsJSON();
                 return;
             }
         }
     }
     if ($useContainer === TRUE) {
         // for uploading to FileMaker's container field
         $fileName = $filePathInfo['filename'] . '.' . $filePathInfo['extension'];
         $tmpDir = ini_get('upload_tmp_dir');
         if ($tmpDir === '') {
             $tmpDir = sys_get_temp_dir();
         }
         if (mb_substr($tmpDir, 1) === DIRECTORY_SEPARATOR) {
             $filePath = $tmpDir . $fileName;
         } else {
             $filePath = $tmpDir . DIRECTORY_SEPARATOR . $fileName;
         }
     }
     $result = move_uploaded_file($util->removeNull($fileInfo['tmp_name']), $filePath);
     if (!$result) {
         if (!is_null($url)) {
             header('Location: ' . $url);
         } else {
             $dbProxyInstance->logger->setErrorMessage("Fail to move the uploaded file in the media folder.");
             $dbProxyInstance->processingRequest($options, "noop");
             $dbProxyInstance->finishCommunication();
             $dbProxyInstance->exportOutputDataAsJSON();
         }
         return;
     }
     $targetFieldName = $_POST["_im_field"];
     if ($useContainer === FALSE) {
         $dbProxyContext = $dbProxyInstance->dbSettings->getDataSourceTargetArray();
         if (isset($dbProxyContext['file-upload'])) {
             foreach ($dbProxyContext['file-upload'] as $item) {
                 if (isset($item['field']) && !isset($item['context'])) {
                     $targetFieldName = $item['field'];
                 }
             }
         }
     }
     $dbKeyValue = $_POST["_im_keyvalue"];
     $dbProxyInstance = new DB_Proxy();
     $dbProxyInstance->initialize($datasource, $options, $dbspec, $debug, $_POST["_im_contextname"]);
     $dbProxyInstance->dbSettings->addExtraCriteria($_POST["_im_keyfield"], "=", $dbKeyValue);
     $dbProxyInstance->dbSettings->setTargetFields(array($targetFieldName));
     $fileContent = file_get_contents($filePath, false, null, 0, 30);
     $headerTop = strpos($fileContent, "data:");
     $endOfHeader = strpos($fileContent, ",");
     if ($headerTop === 0 && $endOfHeader > 0) {
         $tempFilePath = $filePath . ".temp";
         rename($filePath, $tempFilePath);
         $step = 1024;
         if (strpos($fileContent, ";base64") !== false) {
             $fw = fopen($filePath, "w");
             $fp = fopen($tempFilePath, "r");
             fread($fp, $endOfHeader + 1);
             while ($str = fread($fp, $step)) {
                 fwrite($fw, base64_decode($str));
             }
             fclose($fp);
             fclose($fw);
             unlink($tempFilePath);
         }
     }
     if ($useContainer === FALSE) {
         $dbProxyInstance->dbSettings->setValue(array($filePath));
     } else {
         $dbProxyInstance->dbSettings->setValue(array($fileName . "\n" . base64_encode(file_get_contents($filePath))));
     }
     $dbProxyInstance->processingRequest($options, "update");
     $relatedContext = null;
     if ($useContainer === FALSE) {
         if (isset($dbProxyContext['file-upload'])) {
             foreach ($dbProxyContext['file-upload'] as $item) {
                 if ($item['field'] == $_POST["_im_field"]) {
                     $relatedContext = new DB_Proxy();
                     $relatedContext->initialize($datasource, $options, $dbspec, $debug, isset($item['context']) ? $item['context'] : null);
                     $relatedContextInfo = $relatedContext->dbSettings->getDataSourceTargetArray();
                     $fields = array();
                     $values = array();
                     if (isset($relatedContextInfo["query"])) {
                         foreach ($relatedContextInfo["query"] as $cItem) {
                             if ($cItem['operator'] == "=" || $cItem['operator'] == "eq") {
                                 $fields[] = $cItem['field'];
                                 $values[] = $cItem['value'];
                             }
                         }
                     }
                     if (isset($relatedContextInfo["relation"])) {
                         foreach ($relatedContextInfo["relation"] as $cItem) {
                             if ($cItem['operator'] == "=" || $cItem['operator'] == "eq") {
                                 $fields[] = $cItem['foreign-key'];
                                 $values[] = $dbKeyValue;
                             }
                         }
                     }
                     $fields[] = "path";
                     $values[] = $filePartialPath;
                     $relatedContext->dbSettings->setTargetFields($fields);
                     $relatedContext->dbSettings->setValue($values);
                     $relatedContext->processingRequest($options, "create", true);
                     //    $relatedContext->finishCommunication(true);
                     //    $relatedContext->exportOutputDataAsJSON();
                 }
             }
         }
     }
     if ($useContainer === FALSE) {
         $dbProxyInstance->addOutputData('dbresult', $filePath);
     } else {
         $dbProxyInstance->addOutputData('dbresult', '/fmi/xml/cnt/' . $fileName . '?-db=' . urlencode($dbProxyInstance->dbSettings->getDbSpecDatabase()) . '&-lay=' . urlencode($datasource[0]['name']) . '&-recid=' . intval($_POST['_im_keyvalue']) . '&-field=' . urlencode($targetFieldName));
     }
     $dbProxyInstance->finishCommunication();
     $dbProxyInstance->exportOutputDataAsJSON();
     if (!is_null($url)) {
         header('Location: ' . $url);
     }
 }