Beispiel #1
0
        for ($i = 0; $i < 6; $i++) {
            $n = rand(0, strlen($seed) - 1);
            $password .= substr($seed, $n, 1);
        }
        require_once '../../INTER-Mediator.php';
        // Set the valid path to INTER-Mediator.php
        $contextDef = array("name" => "authuser", "view" => "authuser", "table" => "dummydummy", "records" => 1, 'send-mail' => array('read' => array('to' => 'email', 'bcc' => '*****@*****.**', 'subject-constant' => 'ユーザ登録を完了しました', 'from-constant' => 'Masayuki Nii <*****@*****.**>', 'body-template' => 'confirmmail.txt', 'body-fields' => "email,realname,@{$password}", 'f-option' => true, 'body-wrap' => 78)));
        $dbInstance = new DB_Proxy();
        $dbInstance->initialize(array($contextDef), array(), array("db-class" => "PDO"), 2);
        $result = $dbInstance->userEnrollmentActivateUser($_GET['c'], $password);
        if ($result === false) {
            $ermessage .= '確認しましたが、該当する申し込みがありません。';
        } else {
            $message .= 'アカウントを発行し、そのご案内をメールでお送りしました。';
            $contextDef["query"][0]["value"] = $result;
            $dbInstance = new DB_Proxy();
            $dbInstance->initialize(array($contextDef), array(), array("db-class" => "PDO"), 2, "authuser");
            $dbInstance->dbSettings->addExtraCriteria("id", "=", $result);
            $dbInstance->processingRequest("read");
        }
    }
}
header('Content-Type: text/html;charset="UTF-8"');
?>
<!DOCTYPE html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
    <title>登録確認</title>
<body>
<h1>登録確認</h1>
<p style="color:black;font-weight:900"><?php 
if (count($_POST) > 0) {
    if ($_POST['ad1'] != $_POST['ad2']) {
        $message .= '2つのメールアドレスが異なっています。';
    } else {
        if (preg_match($pattern, $_POST['ad1']) !== 1) {
            $message .= 'メールアドレスの形式が正しくありません。';
        } else {
            require_once '../../INTER-Mediator.php';
            // Set the valid path to INTER-Mediator.php
            $dbInstance = new DB_Proxy();
            $dbInstance->initialize(array(), array('authentication' => array('email-as-username' => true)), array("db-class" => "PDO"), 2);
            $result = $dbInstance->resetPasswordSequenceStart($_POST['ad1']);
            if ($result === false) {
                $message .= 'パスワードのリセット処理に問題が発生しました。登録されたメールアドレスでない可能性があります。';
            } else {
                $dbInstance = new DB_Proxy();
                $dbInstance->initialize(array(array("name" => "authuser", "view" => "authuser", "table" => "dummydummy", "records" => 1, "query" => array(array("field" => "email", "operator" => "=", "value" => $_POST['ad1'])), 'send-mail' => array('read' => array('to' => 'email', 'bcc' => '*****@*****.**', 'subject-constant' => 'パスワードのリセットを受付ました', 'from-constant' => 'Masayuki Nii <*****@*****.**>', 'body-template' => 'requestmail.txt', 'body-fields' => "@{$_POST['ad1']},@{$result['randdata']}", 'f-option' => true, 'body-wrap' => 78)))), array(), array("db-class" => "PDO"), 2, "authuser");
                $dbInstance->processingRequest("read");
                $message .= '<span style="color:black">';
                $message .= 'パスワードのリセットをご案内するメールが、指定されたメールアドレスに送信されました。';
                $message .= '</span>';
                $mail = $_POST['ad1'];
                $account = $result['username'];
            }
        }
    }
}
header('Content-Type: text/html;charset="UTF-8"');
header('Cache-Control: no-store,no-cache,must-revalidate,post-check=0,pre-check=0');
header('Expires: 0');
?>
Beispiel #3
0
 public function afterAuth()
 {
     $this->errorMessage = array();
     if (!isset($_REQUEST['code'])) {
         $this->errorMessage[] = "This isn't redirected from the providers site.";
         return false;
     }
     $tokenID = $this->decodeIDToken($_REQUEST['code']);
     if ($tokenID === false || strlen($tokenID["username"]) < 1 || strlen($tokenID["email"]) < 1) {
         $this->errorMessage[] = "Nothing to get from the authenticating server. tokenID=" . var_export($tokenID, true);
         return false;
     }
     $this->userInfo = array("username" => $tokenID["username"], "realname" => $tokenID["realname"], "email" => $tokenID["email"]);
     $dbProxy = new DB_Proxy();
     $dbProxy->initialize(null, null, null, false);
     $dbProxy->dbSettings->setLDAPExpiringSeconds(3600 * 24);
     $credential = $dbProxy->generateCredential(30);
     $param = array("username" => $tokenID["username"], "hashedpasswd" => $credential, "realname" => $tokenID["realname"], "email" => $tokenID["email"]);
     $this->isCreate = $dbProxy->dbClass->authSupportOAuthUserHandling($param);
     if ($this->debugMode) {
         $this->errorMessage[] = "authSupportOAuthUserHandling sends " . var_export($param, true) . ", returns {$this->isCreate}.";
         $this->errorMessage = array_merge($this->errorMessage, $dbProxy->logger->getDebugMessages());
     }
     $this->errorMessage = array_merge($this->errorMessage, $dbProxy->logger->getErrorMessages());
     $oAuthStoring = isset($_COOKIE["_im_oauth_storing"]) ? $_COOKIE["_im_oauth_storing"] : "";
     $oAuthStoring = $oAuthStoring == 'session-storage' ? "true" : "false";
     $oAuthRealm = isset($_COOKIE["_im_oauth_realm"]) ? $_COOKIE["_im_oauth_realm"] : "";
     $this->jsCode = '';
     $this->jsCode .= 'function setAnyStore(key, val) {';
     $this->jsCode .= "var isSession = {$oAuthStoring}, realm = '{$oAuthRealm}';";
     $this->jsCode .= 'var d, isFinish = false, ex = 3600, authKey;';
     $this->jsCode .= 'd = new Date();d.setTime(d.getTime() + ex * 1000);';
     $this->jsCode .= 'authKey = key + ((realm.length > 0) ? ("_" + realm) : "");';
     $this->jsCode .= 'try {if (isSession){sessionStorage.setItem(authKey, val);isFinish = true;}}';
     $this->jsCode .= 'catch(ex){}';
     $this->jsCode .= 'if (!isFinish) {document.cookie = authKey + "=" + encodeURIComponent(val)';
     $this->jsCode .= '+ ";path=/;" + "max-age=" + ex + ";expires=" + d.toUTCString() + ";"';
     $this->jsCode .= '+ ((document.URL.substring(0, 8) == "https://") ? "secure;" : "")}}';
     $this->jsCode .= "setAnyStore('_im_username', '" . $tokenID["username"] . "');";
     $this->jsCode .= "setAnyStore('_im_credential', '" . $credential . "');";
     $this->jsCode .= "setAnyStore('_im_openidtoken', '" . $this->id_token . "');";
     if (count($this->errorMessage) < 1 && !(!$this->doRedirect && $this->isCreate)) {
         $this->jsCode .= "location.href = '" . $_COOKIE["_im_oauth_backurl"] . "';";
         return true;
     }
     return true;
 }
Beispiel #4
0
<?php

/**
 * INTER-Mediator
 * Copyright (c) INTER-Mediator Directive Committee (http://inter-mediator.org)
 * This project started at the end of 2009 by Masayuki Nii msyk@msyk.net.
 *
 * INTER-Mediator is supplied under MIT License.
 * Please see the full license for details:
 * https://github.com/INTER-Mediator/INTER-Mediator/blob/master/dist-docs/License.txt
 *
 * @copyright     Copyright (c) INTER-Mediator Directive Committee (http://inter-mediator.org)
 * @link          https://inter-mediator.com/
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
require_once dirname(__FILE__) . '/../../INTER-Mediator.php';
spl_autoload_register('loadClass');
$pid = mb_eregi_replace("/[^0-9]/", "", $_GET["id"]);
if ($pid < 1) {
    echo json_encode(array("ERROR" => "Invalid Product Number."));
    exit;
}
$contextDef = array(array('records' => 10, 'name' => 'product', 'key' => 'id', 'query' => array(array('field' => 'name', 'value' => '%', 'operator' => 'LIKE')), 'sort' => array(array('field' => 'name', 'direction' => 'ASC'))));
$dbInstance = new DB_Proxy();
$dbInstance->initialize($contextDef, array(), array("db-class" => "PDO"), 2, "product");
$dbInstance->dbSettings->addExtraCriteria("id", "=", $pid);
$dbInstance->processingRequest("read");
$pInfo = $dbInstance->getDatabaseResult();
$logInfo = $dbInstance->logger->getMessagesForJS();
echo json_encode(array("data" => $pInfo, "log" => $logInfo));
 public function processing($datasource, $options, $dbspec, $debug)
 {
     $dbProxyInstance = new DB_Proxy();
     $this->db = $dbProxyInstance;
     $dbProxyInstance->initialize($datasource, $options, $dbspec, $debug, $_POST["_im_contextname"]);
     if (!isset($options['media-root-dir'])) {
         if (isset($_POST["_im_redirect"])) {
             header("Location: {$_POST["_im_redirect"]}");
         } else {
             $dbProxyInstance->logger->setErrorMessage("'media-root-dir' isn't specified");
             $dbProxyInstance->processingRequest($options, "noop");
             $dbProxyInstance->finishCommunication();
             $dbProxyInstance->exportOutputDataAsJSON();
         }
         return;
     }
     // requires media-root-dir specification.
     $fileRoot = $options['media-root-dir'];
     if (substr($fileRoot, strlen($fileRoot) - 1, 1) != '/') {
         $fileRoot .= '/';
     }
     if (count($_FILES) < 1) {
         if (isset($_POST["_im_redirect"])) {
             header("Location: {$_POST["_im_redirect"]}");
         } else {
             $dbProxyInstance->logger->setErrorMessage("No file wasn't uploaded.");
             $dbProxyInstance->processingRequest($options, "noop");
             $dbProxyInstance->finishCommunication();
             $dbProxyInstance->exportOutputDataAsJSON();
         }
         return;
     }
     foreach ($_FILES as $fn => $fileInfo) {
     }
     $fileRoot = $options['media-root-dir'];
     if (substr($fileRoot, strlen($fileRoot) - 1, 1) != '/') {
         $fileRoot .= '/';
     }
     $filePathInfo = pathinfo(str_replace('\\0', '', basename($fileInfo['name'])));
     $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;
         }
     }
     $result = move_uploaded_file($fileInfo['tmp_name'], $filePath);
     if (!$result) {
         if (isset($_POST["_im_redirect"])) {
             header("Location: {$_POST["_im_redirect"]}");
         } 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"];
     $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));
     $dbProxyInstance->dbSettings->setValue(array($filePath));
     $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);
         }
     }
     $dbProxyInstance->processingRequest($options, "update");
     $relatedContext = null;
     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, "new", true);
                 //    $relatedContext->finishCommunication(true);
                 //    $relatedContext->exportOutputDataAsJSON();
             }
         }
     }
     //        echo "dbresult='{$filePath}';";
     $dbProxyInstance->addOutputData('dbresult', $filePath);
     $dbProxyInstance->finishCommunication();
     $dbProxyInstance->exportOutputDataAsJSON();
     if (isset($_POST["_im_redirect"])) {
         header("Location: {$_POST["_im_redirect"]}");
     }
 }
function IM_Entry($datasource, $options, $dbspecification, $debug = false)
{
    global $g_dbInstance, $g_serverSideCall;
    spl_autoload_register('loadClass');
    // check required PHP extensions
    $requiredFunctions = array('mbstring' => 'mb_internal_encoding');
    if (isset($options) && is_array($options)) {
        foreach ($options as $key => $option) {
            if ($key == 'authentication' && isset($option['user']) && is_array($option['user']) && array_search('database_native', $option['user']) !== false) {
                // Native Authentication requires BC Math functions
                $requiredFunctions = array_merge($requiredFunctions, array('bcmath' => 'bcadd'));
                break;
            }
        }
    }
    foreach ($requiredFunctions as $key => $value) {
        if (!function_exists($value)) {
            $generator = new GenerateJSCode();
            $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug);
            $generator->generateErrorMessageJS("PHP extension \"" . $key . "\" is required for running INTER-Mediator.");
            return;
        }
    }
    if ($debug) {
        $dc = new DefinitionChecker();
        $defErrorMessage = $dc->checkDefinitions($datasource, $options, $dbspecification);
        if (strlen($defErrorMessage) > 0) {
            $generator = new GenerateJSCode();
            $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug);
            $generator->generateErrorMessageJS($defErrorMessage);
            return;
        }
    }
    if (isset($g_serverSideCall) && $g_serverSideCall) {
        $dbInstance = new DB_Proxy();
        $dbInstance->initialize($datasource, $options, $dbspecification, $debug);
        $dbInstance->processingRequest($options, "NON");
        $g_dbInstance = $dbInstance;
    } else {
        if (!isset($_POST['access']) && isset($_GET['uploadprocess'])) {
            $fileUploader = new FileUploader();
            $fileUploader->processInfo();
        } else {
            if (!isset($_POST['access']) && isset($_GET['media'])) {
                $dbProxyInstance = new DB_Proxy();
                $dbProxyInstance->initialize($datasource, $options, $dbspecification, $debug);
                $mediaHandler = new MediaAccess();
                if (isset($_GET['attach'])) {
                    $mediaHandler->asAttachment();
                }
                $mediaHandler->processing($dbProxyInstance, $options, $_GET['media']);
            } else {
                if (isset($_POST['access']) && $_POST['access'] == 'uploadfile' || isset($_GET['access']) && $_GET['access'] == 'uploadfile') {
                    $fileUploader = new FileUploader();
                    $fileUploader->processing($datasource, $options, $dbspecification, $debug);
                } else {
                    if (!isset($_POST['access']) && !isset($_GET['media'])) {
                        $generator = new GenerateJSCode();
                        $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug);
                    } else {
                        $dbInstance = new DB_Proxy();
                        $dbInstance->initialize($datasource, $options, $dbspecification, $debug);
                        if ($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
                            $dbInstance->processingRequest($options);
                            $dbInstance->finishCommunication(false);
                        } else {
                            $dbInstance->addOutputData('debugMessages', 'Invalid Request Error.');
                            $dbInstance->addOutputData('errorMessages', array('Invalid Request Error.'));
                        }
                        $dbInstance->exportOutputDataAsJSON();
                    }
                }
            }
        }
    }
}
<?php

/*
 * INTER-Mediator
 * Copyright (c) INTER-Mediator Directive Committee (http://inter-mediator.org)
 * This project started at the end of 2009 by Masayuki Nii msyk@msyk.net.
 *
 * INTER-Mediator is supplied under MIT License.
 * Please see the full license for details:
 * https://github.com/INTER-Mediator/INTER-Mediator/blob/master/dist-docs/License.txt
 */
if (isset($_GET['m']) && strlen($_GET['m']) > 0) {
    require_once '../../INTER-Mediator.php';
    // Set the valid path to INTER-Mediator.php
    $contextDef = array('name' => 'authuser', 'key' => 'id', 'query' => array(array('field' => 'email', 'operator' => '=', 'value' => $_GET['m'])));
    $dbInstance = new DB_Proxy();
    $dbInstance->initialize(array($contextDef), array(), array("db-class" => "PDO"), false, "authuser");
    $dbInstance->processingRequest("read");
    $result = $dbInstance->getDatabaseResult();
    echo count($result);
    exit;
}
echo 0;
function IM_Entry($datasource, $options, $dbspecification, $debug = false)
{
    global $g_dbInstance, $g_serverSideCall;
    // check required PHP extensions
    $requiredFunctions = array('mbstring' => 'mb_internal_encoding');
    if (isset($options) && is_array($options)) {
        foreach ($options as $key => $option) {
            if ($key == 'authentication' && isset($option['user']) && is_array($option['user']) && array_search('database_native', $option['user']) !== false) {
                // Native Authentication requires BC Math functions
                $requiredFunctions = array_merge($requiredFunctions, array('bcmath' => 'bcadd'));
                break;
            }
        }
    }
    foreach ($requiredFunctions as $key => $value) {
        if (!function_exists($value)) {
            $generator = new GenerateJSCode();
            $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug);
            $generator->generateErrorMessageJS("PHP extension \"" . $key . "\" is required for running INTER-Mediator.");
            return;
        }
    }
    if ($debug) {
        $dc = new DefinitionChecker();
        $defErrorMessage = $dc->checkDefinitions($datasource, $options, $dbspecification);
        if (strlen($defErrorMessage) > 0) {
            $generator = new GenerateJSCode();
            $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug);
            $generator->generateErrorMessageJS($defErrorMessage);
            return;
        }
    }
    //    file_put_contents("/tmp/php2.log", "POST: " . var_export($_POST, true), FILE_APPEND);
    //    file_put_contents("/tmp/php2.log", "GET: " . var_export($_GET, true), FILE_APPEND);
    //    file_put_contents("/tmp/php2.log", "FILES: " . var_export($_FILES, true), FILE_APPEND);
    //    file_put_contents("/tmp/php2.log", "SERVER: " . var_export($_SERVER, true), FILE_APPEND);
    if (isset($g_serverSideCall) && $g_serverSideCall) {
        $dbInstance = new DB_Proxy();
        $dbInstance->initialize($datasource, $options, $dbspecification, $debug);
        $dbInstance->processingRequest("NON");
        $g_dbInstance = $dbInstance;
    } else {
        if (!isset($_POST['access']) && isset($_GET['uploadprocess'])) {
            $fileUploader = new FileUploader();
            $fileUploader->processInfo();
        } else {
            if (!isset($_POST['access']) && isset($_GET['media'])) {
                $dbProxyInstance = new DB_Proxy();
                $dbProxyInstance->initialize($datasource, $options, $dbspecification, $debug);
                $mediaHandler = new MediaAccess();
                if (isset($_GET['attach'])) {
                    $mediaHandler->asAttachment();
                }
                $mediaHandler->processing($dbProxyInstance, $options, $_GET['media']);
            } else {
                if (isset($_POST['access']) && $_POST['access'] == 'uploadfile' || isset($_GET['access']) && $_GET['access'] == 'uploadfile') {
                    $fileUploader = new FileUploader();
                    if (IMUtil::guessFileUploadError()) {
                        $fileUploader->processingAsError($datasource, $options, $dbspecification, $debug);
                    } else {
                        $fileUploader->processing($datasource, $options, $dbspecification, $debug);
                    }
                } else {
                    if (!isset($_POST['access']) && !isset($_GET['media'])) {
                        $generator = new GenerateJSCode();
                        $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug);
                    } else {
                        $dbInstance = new DB_Proxy();
                        $dbInstance->initialize($datasource, $options, $dbspecification, $debug);
                        $util = new IMUtil();
                        if ($util->protectCSRF() === TRUE) {
                            $dbInstance->processingRequest();
                            $dbInstance->finishCommunication(false);
                        } else {
                            $dbInstance->addOutputData('debugMessages', 'Invalid Request Error.');
                            $dbInstance->addOutputData('errorMessages', array('Invalid Request Error.'));
                        }
                        $dbInstance->exportOutputDataAsJSON();
                    }
                }
            }
        }
    }
}
function IM_Entry($datasource, $options, $dbspecification, $debug = false)
{
    global $g_dbInstance, $g_serverSideCall;
    spl_autoload_register('loadClass');
    // check required PHP extensions
    $requiredFunctions = array('mbstring' => 'mb_internal_encoding');
    foreach ($requiredFunctions as $key => $value) {
        if (!function_exists($value)) {
            $generator = new GenerateJSCode();
            $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug);
            $generator->generateErrorMessageJS("PHP extension \"" . $key . "\" is required for running INTER-Mediator.");
            return;
        }
    }
    if ($debug) {
        $dc = new DefinitionChecker();
        $defErrorMessage = $dc->checkDefinitions($datasource, $options, $dbspecification);
        if (strlen($defErrorMessage) > 0) {
            $generator = new GenerateJSCode();
            $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug);
            $generator->generateErrorMessageJS($defErrorMessage);
            return;
        }
    }
    if (isset($g_serverSideCall) && $g_serverSideCall) {
        $dbInstance = new DB_Proxy();
        $dbInstance->initialize($datasource, $options, $dbspecification, $debug);
        $dbInstance->processingRequest($options, "NON");
        $g_dbInstance = $dbInstance;
    } else {
        if (!isset($_POST['access']) && isset($_GET['uploadprocess'])) {
            $fileUploader = new FileUploader();
            $fileUploader->processInfo();
        } else {
            if (!isset($_POST['access']) && isset($_GET['media'])) {
                $dbProxyInstance = new DB_Proxy();
                $dbProxyInstance->initialize($datasource, $options, $dbspecification, $debug);
                $mediaHandler = new MediaAccess();
                if (isset($_GET['attach'])) {
                    $mediaHandler->asAttachment();
                }
                $mediaHandler->processing($dbProxyInstance, $options, $_GET['media']);
            } else {
                if (isset($_POST['access']) && $_POST['access'] == 'uploadfile' || isset($_GET['access']) && $_GET['access'] == 'uploadfile') {
                    $fileUploader = new FileUploader();
                    $fileUploader->processing($datasource, $options, $dbspecification, $debug);
                } else {
                    if (!isset($_POST['access']) && !isset($_GET['media'])) {
                        $generator = new GenerateJSCode();
                        $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug);
                    } else {
                        $dbInstance = new DB_Proxy();
                        $dbInstance->initialize($datasource, $options, $dbspecification, $debug);
                        $dbInstance->processingRequest($options);
                        $dbInstance->finishCommunication(false);
                    }
                }
            }
        }
    }
}
 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);
     }
 }