Exemple #1
0
function gConfig($key)
{
    static $config = null;
    if ($config == null) {
        $config = readConfig();
    }
    $ret = isset($config[$key]) ? $config[$key] : "";
    return $ret;
}
 /**
  * sets up the database connection and provides it to PHPUnit
  *
  * @see <https://phpunit.de/manual/current/en/database.html#database.configuration-of-a-phpunit-database-testcase>
  * @return \PHPUnit_Extensions_Database_DB_IDatabaseConnection PHPUnit database connection interface
  **/
 public final function getConnection()
 {
     // if the connection hasn't been established, create it
     if ($this->connection === null) {
         // connect to mySQL and provide the interface to PHPUnit
         $config = readConfig("/etc/apache2/data-design/dmcdonald21.ini");
         $pdo = connectToEncryptedMySQL("/etc/apache2/data-design/dmcdonald21.ini");
         $this->connection = $this->createDefaultDBConnection($pdo, $config["database"]);
     }
     return $this->connection;
 }
Exemple #3
0
 /**
  * sets up the database connection and provides it to PHPUnit
  *
  * @see <https://phpunit.de/manual/current/en/database.html#database.configuration-of-a-phpunit-database-testcase>
  * @return \PHPUnit_Extensions_Database_DB_IDatabaseConnection PHPUnit database connection interface
  */
 public final function getConnection()
 {
     //If the connection has not been established yet, create it
     if ($this->connection === null) {
         //connect to mySQL and provide the interface to PHPUnit
         $config = readConfig("/etc/apache2/capstone-mysql/jpegery.ini");
         $pdo = connectToEncryptedMySQL("/etc/apache2/capstone-mysql/jpegery.ini");
         $this->connection = $this->createDefaultDBConnection($pdo, $config["database"]);
     }
     return $this->connection;
 }
 /**
  * sets up the database connection and provides it to PHPUnit
  *
  * @see <https://phpunit.de/manual/current/en/database.html#database.configuration-of-a-phpunit-database-testcase>
  * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection PHPUnit database connection interface
  **/
 public final function getConnection()
 {
     // if the connection hasn't been established, create it
     if ($this->connection === null) {
         // grab the encrypted mySQL properties file and create the DSN
         $config = readConfig("/etc/apache2/data-design/dmcdonald21.ini");
         $dsn = "mysql:host=" . $config["hostname"] . ";dbname=" . $config["database"];
         $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
         // provide the interface to PHPUnit
         $pdo = new PDO($dsn, $config["username"], $config["password"], $options);
         $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         $this->connection = $this->createDefaultDBConnection($pdo, $config["database"]);
     }
     return $this->connection;
 }
Exemple #5
0
function phptemplate_preprocess_page(&$vars) {
    include_once("readConfig.php");
    $config = readConfig();
    $vars['scripts'] = $config['scripts'] . $vars['scripts'];
    $vars['styles'] = $config['styles'] . $vars['styles'];

    $suggestions = array();
    if (module_exists('path')) {
        $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));

        if(stristr($alias, "layer/")) {
            $suggestions = array();
            $suggestions[] = "page-layer";
            $vars['template_files'] = $suggestions;
        }

        if($alias == "map") {
            $suggestions = array();
            $suggestions[] = "page-map";
            $vars['template_files'] = $suggestions;
        }
    }
}
                    echo "<p>* * * SIX OF THIRTEEN SKIPPED THIS GAME * * *</p>" . PHP_EOL;
                }
            }
        }
    }
} catch (Exception $exception) {
    echo "Something went wrong: " . $exception->getMessage() . PHP_EOL;
} catch (TypeError $typeError) {
    echo "Something went wrong: " . $typeError->getMessage() . PHP_EOL;
}
//downloader for players NFL
try {
    $seasoning = ["2015", "2016"];
    foreach ($seasoning as $season) {
        $pdo = connectToEncryptedMySQL("/etc/apache2/capstone-mysql/sprots.ini");
        $config = readConfig("/etc/apache2/capstone-mysql/sprots.ini");
        $apiKeys = json_decode($config["fantasyData"]);
        $opts = array('http' => array('method' => "GET", 'header' => "Content-Type: application/json\r\nOcp-Apim-Subscription-key: " . $apiKeys->NFL, 'content' => "{body}"));
        $context = stream_context_create($opts);
        //response from Api
        $response = file_get_contents("https://api.fantasydata.net/nfl/v2/JSON/Players/{$season}", false, $context);
        $data = json_decode($response);
        $stats = ["PlayerID  ", "Team", "Number ", "FirstName ", "LastName", "Status ", "Height ", "Weight", "BirthDate ", "College ", "Experience ", "Active ", "PositionCategory ", "Name", "Age ", "ExperienceString ", "BirthDateString", "PhotoUrl ", "ByeWeek  ", "UpcomingGameOpponent ", "UpcomingGameWeek", "ShortName  ", "AverageDraftPosition ", "DepthPositionCategory  ", "DepthPosition ", "DepthOrder  ", "DepthDisplayOrder ", "CurrentTeam  ", "HeightFeet  ", "UpcomingOpponentRank ", "UpcomingOpponentPositionRank ", "CurrentStatus"];
        $sport = Sport::getSportBySportLeague($pdo, "NFL");
        foreach ($data as $player) {
            $team = Team::getTeamByTeamApiId($pdo, $player->TeamID);
            if ($team !== null) {
                $playerToInsert = new Player(null, $player->PlayerID, $team->getTeamId(), $sport->getSportId(), $player->FirstName . " " . $player->LastName);
                $playerToInsert->insert($pdo);
                $game = Game::getGameByGameFirstTeamId($pdo, $team->getTeamId());
                if ($game === null) {
Exemple #7
0
test('Cached value should exist');
asrt(apc_exists("configList"), "configList does not exist");
test('Should set cached value');
$list = apc_fetch("configList");
$passed = in_array('register', $list) && in_array('login', $list);
asrt($passed, http_build_query($list));
$writeconfig = file('register.example');
$readconfig = file('login.example');
require_once 'functions_main.inc';
testSuite('Read config test');
test('Should throw error on empty parameters');
readConfig(false);
throws("no action provided");
test('Should throw error on nonexistent action');
readConfig('some_weird_action');
throws("unrecognized action");
test('Action exists, but no file for it');
readConfig('login');
throws("unable to find config for this action");
test('Action exists, but no file for it');
$passed = readConfig('login', '.example');
asrt(startsWith($passed[0], 'IMPORT'), $passed[0]);
testSuite('Test import');
test('Should throw error on empty parameters');
$toParse[0] = 'IMPORT login.example';
$toParse[1] = 'DBCONFIG best : mana';
$parsed = doIMPORT($toParse);
$dbConfig = getDbConfigs($parsed);
$passed = $dbConfig['best'] == 'mana' && $dbConfig['user'] == 'loginreader';
asrt($passed, http_build_query($dbConfig));
finish();
Exemple #8
0
<?php

require_once 'functions_utility.inc';
require_once 'functions_main.inc';
$configLinesWithoutIncludes = readConfig($_GET["action"]);
checkIfError();
$configLinesWithIncludes = doIMPORT($configLinesWithoutIncludes);
checkIfError();
$linesToParse = stripComments($configLinesWithIncludes);
checkIfError();
checkMETHOD($linesToParse);
checkIfError();
$passedVariables = MapVariables($linesToParse);
checkIfError();
doCHECK($linesToParse, $passedVariables);
checkIfError();
$sqlConnection = initDB($linesToParse);
checkIfError();
doDBCHECK($linesToParse, $sqlConnection);
checkIfError();
doACTION($linesToParse, $sqlConnection);
checkIfError();
Exemple #9
0
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, $data, $values, $tags);
    xml_parser_free($parser);
    // loop through the structures
    foreach ($tags as $key => $val) {
        if ($key == "node") {
            $noderanges = $val;
            // each contiguous pair of array entries are the
            // lower and upper range for each node definition
            for ($i = 0; $i < count($noderanges); $i += 2) {
                $offset = $noderanges[$i] + 1;
                $len = $noderanges[$i + 1] - $offset;
                $tdb[] = parseXML(array_slice($values, $offset, $len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}
function parseXML($mvalues)
{
    for ($i = 0; $i < count($mvalues); $i++) {
        $node[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
    }
    return new DataNode($node);
}
$db = readConfig("config.xml");
print_r($db);
require_once dirname(dirname(dirname(__DIR__))) . "/vendor/autoload.php";
require_once dirname(dirname(__DIR__)) . "/classes/misquote.php";
require_once dirname(dirname(__DIR__)) . "/lib/xsrf.php";
require_once "/etc/apache2/data-design/encrypted-config.php";
// start the session and create a XSRF token
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
// prepare an empty reply
$reply = new stdClass();
$reply->status = 200;
$reply->data = null;
try {
    // create the Pusher connection
    $config = readConfig("/etc/apache2/data-design/misquote.ini");
    $pusherConfig = json_decode($config["pusher"]);
    $pusher = new Pusher($pusherConfig->key, $pusherConfig->secret, $pusherConfig->id, ["encrypted" => true]);
    // determine which HTTP method was used
    $method = array_key_exists("HTTP_X_HTTP_METHOD", $_SERVER) ? $_SERVER["HTTP_X_HTTP_METHOD"] : $_SERVER["REQUEST_METHOD"];
    // sanitize the id
    $id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
    if (($method === "DELETE" || $method === "PUT") && (empty($id) === true || $id < 0)) {
        throw new InvalidArgumentException("id cannot be empty or negative", 405);
    }
    // grab the mySQL connection
    $pdo = connectToEncryptedMySQL("/etc/apache2/data-design/misquote.ini");
    // handle all RESTful calls to Misquote
    // get some or all Misquotes
    if ($method === "GET") {
        // set an XSRF cookie on GET requests
Exemple #11
0
 *
 * @category VuFind
 * @package  Utilities
 * @author   Tuan Nguyen <*****@*****.**>
 * @license  http://opensource.org/licenses/gpl-2.0.php GNU General Public License
 * @link     http://vufind.org/wiki Wiki
 */
ini_set('memory_limit', '50M');
ini_set('max_execution_time', '3600');
/**
 * Set up util environment
 */
require_once 'util.inc.php';
require_once 'sys/ConnectionManager.php';
// Read Config file
$configArray = readConfig();
// Setup Solr Connection
$solr = ConnectionManager::connectToIndex('SolrReserves');
// Connect to ILS
$catalog = ConnectionManager::connectToCatalog();
// Records to index
$index = array();
// Get instructors
$instructors = $catalog->getInstructors();
// Get Courses
$courses = $catalog->getCourses();
// Get Departments
$departments = $catalog->getDepartments();
// Get all reserve records
$reserves = $catalog->findReserves('', '', '');
if (!empty($instructors) && !empty($courses) && !empty($departments) && !empty($reserves)) {
Exemple #12
0
 * @link     http://vufind.org/wiki/migration_notes Wiki
 */
// Die if we don't have enough parameters:
if (!isset($argv[3]) || !isset($argv[2]) || !isset($argv[1])) {
    die("\n\nMissing command line parameter... aborting database upgrade.\n\n");
}
$mysql_admin_user = $argv[1];
$mysql_admin_pw = $argv[2];
$old_config = $argv[3];
// Try to read the ini file:
$basePath = $old_config . '/web/conf';
if (!file_exists($basePath . '/config.ini')) {
    die("\n\nCan't open {$basePath}/config.ini; aborting database upgrade.\n\n");
}
require_once dirname(__FILE__) . '/../web/sys/ConfigArray.php';
$configArray = readConfig($basePath);
?>

#### Database upgrade ####

This script will upgrade your VuFind database from the previous version to the new
release.  It is recommended that you make a backup before proceeding with this
script, just to be on the safe side!

<?php 
// get connection credentials from config.ini
$match = preg_match("/mysql:\\/\\/([^:]+):([^@]+)@([^\\/]+)\\/(.+)/", $configArray['Database']['database'], $mysql_conn);
if (!$match) {
    echo "Can't determine data needed to access your MySQL database. You have " . $configArray['Database']['database'] . "\nas connection string in your config.ini.\n";
    exit(0);
}
Exemple #13
0
/**
 * controller/api for the listing class
 *
 * @author Kimberly Keller keller.kimberly@gmail.com>
 */
//verify the xsrf challenge
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
//prepare an empty reply
$reply = new stdClass();
$reply->status = 200;
$reply->data = null;
try {
    // create the Pusher connection
    $config = readConfig("/etc/apache2/capstone-mysql/breadbasket.ini");
    $pusherConfig = json_decode($config["pusher"]);
    $pusher = new Pusher($pusherConfig->key, $pusherConfig->secret, $pusherConfig->id, ["debug" => true, "encrypted" => true]);
    //grab the mySQL connection
    $pdo = connectToEncryptedMySql("/etc/apache2/capstone-mysql/breadbasket.ini");
    //if the volunteer session is empty, the user is not logged in, throw an exception
    if (empty($_SESSION["volunteer"]) === true) {
        setXsrfCookie("/");
        throw new RuntimeException("Please log-in or sign up", 401);
    }
    //determine which HTTP method was used
    $method = array_key_exists("HTTP_X_HTTP_METHOD", $_SERVER) ? $_SERVER["HTTP_X_HTTP_METHOD"] : $_SERVER["REQUEST_METHOD"];
    //if a put and a volunteer, temporarily give admin access to the user
    if ($method === "PUT") {
        $_SESSION["volunteer"]->setVolIsAdmin(true);
    }
 /**
  * Send due date reminders
  *
  * @return void
  */
 public function send()
 {
     global $configArray;
     global $interface;
     global $translator;
     $iso8601 = 'Y-m-d\\TH:i:s\\Z';
     ini_set('display_errors', true);
     $configArray = $mainConfig = readConfig();
     $datasourceConfig = getExtraConfigArray('datasources');
     $siteLocal = $configArray['Site']['local'];
     // Set up time zone. N.B. Don't use msg() or other functions requiring date before this.
     date_default_timezone_set($configArray['Site']['timezone']);
     $this->msg('Sending due date reminders');
     // Setup Local Database Connection
     ConnectionManager::connectToDatabase();
     // And index
     $db = ConnectionManager::connectToIndex();
     // Initialize Mailer
     $mailer = new VuFindMailer();
     // Find all scheduled alerts
     $sql = 'SELECT * FROM "user" WHERE "due_date_reminder" > 0 ORDER BY id';
     $user = new User();
     $user->query($sql);
     $this->msg('Processing ' . $user->N . ' users');
     $interface = false;
     $institution = false;
     $todayTime = new DateTime();
     $catalog = ConnectionManager::connectToCatalog();
     while ($user->fetch()) {
         if (!$user->email || trim($user->email) == '') {
             $this->msg('User ' . $user->username . ' does not have an email address, bypassing due date reminders');
             continue;
         }
         // Initialize settings and interface
         $userInstitution = reset(explode(':', $user->username, 2));
         if (!$institution || $institution != $userInstitution) {
             $institution = $userInstitution;
             if (!isset($datasourceConfig[$institution])) {
                 foreach ($datasourceConfig as $code => $values) {
                     if (isset($values['institution']) && strcasecmp($values['institution'], $institution) == 0) {
                         $institution = $code;
                         break;
                     }
                 }
             }
             if (!($configArray = $this->readInstitutionConfig($institution))) {
                 continue;
             }
             // Start Interface
             $interface = new UInterface($siteLocal);
             $validLanguages = array_keys($configArray['Languages']);
             $dateFormat = new VuFindDate();
         }
         $language = $user->language;
         if (!in_array($user->language, $validLanguages)) {
             $language = $configArray['Site']['language'];
         }
         $translator = new I18N_Translator(array($configArray['Site']['local'] . '/lang', $configArray['Site']['local'] . '/lang_local'), $language, $configArray['System']['debug']);
         $interface->setLanguage($language);
         // Go through accounts and check loans
         $account = new User_account();
         $account->user_id = $user->id;
         if (!$account->find(false)) {
             continue;
         }
         $remindLoans = array();
         while ($account->fetch()) {
             $patron = $catalog->patronLogin($account->cat_username, $account->cat_password);
             if ($patron === null || PEAR::isError($patron)) {
                 $this->msg('Catalog login failed for user ' . $user->id . ', account ' . $account->id . ' (' . $account->cat_username . '): ' . ($patron ? $patron->getMessage() : 'patron not found'));
                 continue;
             }
             $loans = $catalog->getMyTransactions($patron);
             if (PEAR::isError($loans)) {
                 $this->msg('Could not fetch loans for user ' . $user->id . ', account ' . $account->id . ' (' . $account->cat_username . ')');
                 continue;
             }
             foreach ($loans as $loan) {
                 $dueDate = new DateTime($loan['duedate']);
                 if ($todayTime >= $dueDate || $dueDate->diff($todayTime)->days <= $user->due_date_reminder) {
                     // Check that a reminder hasn't been sent already
                     $reminder = new Due_date_reminder();
                     $reminder->user_id = $user->id;
                     $reminder->loan_id = $loan['item_id'];
                     $reminder->due_date = $dueDate->format($iso8601);
                     if ($reminder->find(false)) {
                         // Reminder already sent
                         continue;
                     }
                     // Store also title for display in email
                     $title = isset($loan['title']) ? $loan['title'] : translate('Title not available');
                     if (isset($loan['id'])) {
                         $record = $db->getRecord($loan['id']);
                         if ($record && isset($record['title'])) {
                             $title = $record['title'];
                         }
                     }
                     $remindLoans[] = array('loanId' => $loan['item_id'], 'dueDate' => $loan['duedate'], 'dueDateFormatted' => $dueDate->format(isset($configArray['Site']['displayDateFormat']) ? $configArray['Site']['displayDateFormat'] : "m-d-Y"), 'title' => $title);
                 }
             }
         }
         if ($remindLoans) {
             $this->msg(count($remindLoans) . ' new loans to remind for user ' . $user->id);
             $interface->assign('date', $dateFormat->convertToDisplayDate("U", floor(time())));
             $interface->assign('loans', $remindLoans);
             $key = $this->getSecret($user, $user->id);
             $params = array('id' => $user->id, 'type' => 'reminder', 'key' => $key);
             $unsubscribeUrl = $configArray['Site']['url'] . '/MyResearch/Unsubscribe?' . http_build_query($params);
             $interface->assign(compact('unsubscribeUrl'));
             // Load template
             $message = $interface->fetch('MyResearch/due-date-email.tpl');
             if (strstr($message, 'Warning: Smarty error:')) {
                 $this->msg("Message template processing failed: {$message}");
                 continue;
             }
             $result = $mailer->send($user->email, $configArray['Site']['email'], translate('due_date_email_subject'), $message);
             if (PEAR::isError($result)) {
                 $this->msg("Failed to send message to {$user->email}: " . $result->getMessage());
                 continue;
             }
             // Mark reminders sent
             foreach ($remindLoans as $loan) {
                 $reminder = new Due_date_reminder();
                 $reminder->user_id = $user->id;
                 $reminder->loan_id = $loan['loanId'];
                 $reminder->delete();
                 $dueDate = new DateTime($loan['dueDate']);
                 $reminder->due_date = $dueDate->format($iso8601);
                 $reminder->notification_date = gmdate($iso8601, time());
                 $reminder->insert();
             }
         } else {
             $this->msg('No loans to remind for user ' . $user->id);
         }
     }
     $this->reportErrors();
     $this->msg('Due date reminders execution completed');
 }
Exemple #15
0
function setTcObjectComment($dev, $obj, $head, $body)
{
    if (!ctype_alnum($dev)) {
        dieErr("malformed dev");
    }
    $config = readConfig();
    if (!is_array($config[$dev])) {
        $config[$dev] = array();
    }
    if (strlen($head) == 0 && strlen($body) == 0) {
        if (is_array($config[$dev]["comments"])) {
            unset($config[$dev]["comments"][$obj]);
        }
    } else {
        if (!is_array($config[$dev]["comments"])) {
            $config[$dev]["comments"] = array();
        }
        $config[$dev]["comments"][$obj] = array($head, $body);
    }
    saveConfig($config);
}
/**
 * Работа с OpenAPI
 * ВНИМАНИЕ! Скрипт будет использовать файл, который создаётся в initApi/init.php
 * ВНИМАНИЕ! Скрипт будет использовать файл, который создаётся в openApi/confirmSenderOrders.php
 */
require '../header.php';
require '../lib.inc.php';
// Файл с функцией, генерирующей secret_key
require 'sign.php';
// Название метода, к которому производится обращение
$method = 'getSenderParcelLabel';
// Константа OPEN_API_URL определяется в lib.inc.php
$openApiUrl = OPEN_API_URL . $method;
try {
    // Читаем конфигурацию, сохранённую во время выполнения скрипта initApi/init.php
    // http://docs.multishipinitapiv1.apiary.io/
    $jsonConfig = readConfig();
    $parcel_id = readConfig('parcel_id.json');
    $postData = array('client_id' => $jsonConfig->config->clientId);
    //Передаем id парсела, к которому необходимо распечатать сопроводительные документы
    $postData['parcel_id'] = $parcel_id->data[0];
    // Генерируем secret_key
    $secretKey = sign($jsonConfig->config->methodKeys->{$method}, $postData);
    // Добавляем полученный secret_key к массиву, который будет передан методом POST
    $postData['secret_key'] = $secretKey;
    $result = sendRequestViaCurl($openApiUrl, $postData);
    curlAnswerHandler($result);
} catch (Exception $e) {
    echo '<p>Произошла неисправимая ошибка: ' . $e->getMessage() . '</p>';
}
require '../footer.php';
function getGames(string $league)
{
    try {
        // grab the db connection
        $pdo = connectToEncryptedMySQL("/etc/apache2/capstone-mysql/sprots.ini");
        $config = readConfig("/etc/apache2/capstone-mysql/sprots.ini");
        $apiKeys = json_decode($config["fantasyData"]);
        $opts = array('http' => array('method' => "GET", 'header' => "Content-Type: application/json\r\nOcp-Apim-Subscription-key: " . $apiKeys->{$league}, 'content' => "{body}"));
        $context = stream_context_create($opts);
        // response from api
        $seasoning = ["2015", "2016"];
        foreach ($seasoning as $season) {
            $response = file_get_contents("https://api.fantasydata.net/{$league}/v2/JSON/Games/{$season}", false, $context);
            $data = json_decode($response);
            foreach ($data as $game) {
                $badDate = str_replace("T", " ", $game->DateTime);
                if (empty($badDate) === false) {
                    $teamChavez = Team::getTeamByTeamApiId($pdo, $game->AwayTeamID);
                    $teamPaul = Team::getTeamByTeamApiId($pdo, $game->HomeTeamID);
                    if ($teamChavez !== null && $teamPaul !== null) {
                        $gameToInsert = new Game(null, $teamChavez->getTeamId(), $teamPaul->getTeamId(), $badDate);
                        $gameToInsert->insert($pdo);
                    } else {
                        echo "<p>* * * SIX OF THIRTEEN SKIPPED THIS GAME * * *</p>" . PHP_EOL;
                    }
                }
            }
        }
    } catch (Exception $exception) {
        echo "Something went wrong: " . $exception->getMessage() . PHP_EOL;
    } catch (TypeError $typeError) {
        echo "Something went wrong: " . $typeError->getMessage() . PHP_EOL;
    }
}
 */
require '../header.php';
require '../lib.inc.php';
// Файл с функцией, генерирующей secret_key
require 'sign.php';
// Название метода, к которому производится обращение
$method = 'getSenderOrderStatuses';
// Константа OPEN_API_URL определяется в lib.inc.php
$openApiUrl = OPEN_API_URL . $method;
try {
    // Читаем конфигурацию, сохранённую во время выполнения скрипта initApi/init.php
    // http://docs.multishipinitapiv1.apiary.io/
    $jsonConfig = readConfig();
    // ВНИМАНИЕ! Файл был создан скриптом openApi/searchDeliveryList.php
    // Дальше действует предположение, что покупатель выбрал первый предложенный способ доставки
    $createOrderAnswer = readConfig('createOrder.json');
    // Список необходимых параметров для каждого метода можно посмотреть на странице http://docs.multiship.apiary.io/
    $postData = array('client_id' => $jsonConfig->config->clientId);
    // Для "getSenderOrderStatuses" кроме client_id и secret_key необходимо ещё передать order_id
    $postData['order_id'] = $createOrderAnswer->data->order_id;
    // Генерируем secret_key
    $secretKey = sign($jsonConfig->config->methodKeys->{$method}, $postData);
    // Добавляем полученный secret_key к массиву, который будет передан методом POST
    $postData['secret_key'] = $secretKey;
    // Отправляем запрос на сервер через CURL
    $result = sendRequestViaCurl($openApiUrl, $postData);
    // Вызываем обработчика ответа от CURL
    curlAnswerHandler($result);
} catch (Exception $e) {
    echo '<p>Произошла неисправимая ошибка: ' . $e->getMessage() . '</p>';
}
Exemple #19
0
$ss->check_ip_blocks = 2;
$ss->secure_word = 'SALT_aJyeiuLioRhjlP';
$ss->regenerate_id = true;
$debugMode = "off";
// Turn this on for debugging displays. But is not fully functional yet.
$separator = "#~#";
// Separator used between fields when the entry files are created.
$config = array();
$authors = array();
$authorsPass = array();
$authorsEmail = array();
$authorsActCode = array();
$authorsActStatus = array();
$tags = array();
$priv = "";
readConfig();
/* Read the config file and load it into the array */
if ($config['cleanUrl'] == 0) {
    $config['cleanIndex'] = "/index.php";
} else {
    $config['cleanIndex'] = "";
}
require "lang/" . $config['blogLanguage'] . ".php";
/* Load the language file */
$postdb = getcwd() . "/data/" . $user . "/postdb.sqlite";
$config['postdb'] = $postdb;
$config['authorFile'] = getcwd() . "/data/" . $user . "/authors.php";
$_SESSION['user'] = $user;
//$config['theme']      = "skyblue";
if (!file_exists(getcwd() . '/themes/' . $config['theme'])) {
    $config['theme'] = 'default';
require '../lib.inc.php';
// Файл с функцией, генерирующей secret_key
require 'sign.php';
// Файл с функцией расчёта общих габаритов заказа
require '../dimension_algorithm.php';
// Название метода, к которому производится обращение
$method = 'createOrder';
// Константа OPEN_API_URL определяется в lib.inc.php
$openApiUrl = OPEN_API_URL . $method;
try {
    // Читаем конфигурацию, сохранённую во время выполнения скрипта initApi/init.php
    // http://docs.multishipinitapiv1.apiary.io/
    $jsonConfig = readConfig();
    // ВНИМАНИЕ! Файл был создан скриптом openApi/searchDeliveryList.php
    // Дальше действует предположение, что покупатель выбрал первый предложенный способ доставки
    $searchDeliveryListAnswer = readConfig('searchDeliveryList.json');
    // Список необходимых параметров для каждого метода можно посмотреть на странице http://docs.multiship.apiary.io/
    $postData = array('client_id' => $jsonConfig->config->clientId);
    // Товары в заказе
    $postData['order_items'] = [['orderitem_article' => 'g1_1', 'orderitem_name' => 'Товар №1', 'orderitem_quantity' => 2, 'orderitem_cost' => 500], ['orderitem_article' => 'g2_2', 'orderitem_name' => 'Товар №2', 'orderitem_quantity' => 1, 'orderitem_cost' => 2000], ['orderitem_article' => 'g3_3', 'orderitem_name' => 'Товар №3', 'orderitem_quantity' => 1, 'orderitem_cost' => 280]];
    // Предположим, что есть три товара со следующими габаритами
    $itemDimensions = [[12, 10, 14], [12, 10, 14], [14, 23, 2], [5, 12, 17]];
    // Рассчитываем общие габариты заказа
    $orderDimensions = dimensionAlgorithm($itemDimensions);
    $postData['order_height'] = $orderDimensions['A'];
    $postData['order_width'] = $orderDimensions['B'];
    $postData['order_length'] = $orderDimensions['C'];
    // Суммарный вес заказа рассчитать не сложно, поэтому предположим, что он расчитан
    $postData['order_weight'] = '2.25';
    // Зачастую совпадает с стоимостью товаров в посылке
    $postData['order_assessed_value'] = 0;
 /**
  * Process transactions. Try to register unregistered transactions
  * and inform on expired transactions.
  *
  * @return void
  * @access public
  */
 public function process()
 {
     global $configArray;
     global $interface;
     ini_set('display_errors', true);
     $configArray = $mainConfig = readConfig();
     $datasourceConfig = getExtraConfigArray('datasources');
     // Set up time zone. N.B. Don't use msg() or other
     // functions requiring date before this.
     date_default_timezone_set($configArray['Site']['timezone']);
     $this->msg("OnlinePayment monitor started");
     // Setup Local Database Connection
     ConnectionManager::connectToDatabase();
     // Initialize Mailer
     $mailer = new VuFindMailer();
     $now = new DateTime();
     $expiredCnt = 0;
     $failedCnt = 0;
     $registeredCnt = 0;
     $remindCnt = 0;
     $user = false;
     $report = array();
     // Attempt to re-register paid transactions whose registration has failed.
     $tr = new Transaction();
     foreach ($tr->getFailedTransactions() as $t) {
         $this->msg("  Registering transaction id {$t->id} / {$t->transaction_id}");
         // check if the transaction has not been registered for too long
         $paid_time = new DateTime($t->paid);
         $diff = $now->diff($paid_time);
         $diffHours = $diff->days * 24 + $diff->h;
         if ($diffHours > $this->expireHours) {
             if (!isset($report[$t->driver])) {
                 $report[$t->driver] = 0;
             }
             $report[$t->driver]++;
             $expiredCnt++;
             if (!$t->setTransactionReported($t->transaction_id)) {
                 $this->err('    Failed to update transaction ' . $t->transaction_id . 'as reported');
             }
             $transaction = clone $t;
             $transaction->complete = Transaction::STATUS_REGISTRATION_EXPIRED;
             if ($transaction->update($t) === false) {
                 $this->err('    Failed to update transaction ' . $t->transaction_id . 'as expired.');
             } else {
                 $this->msg('    Transaction ' . $t->transaction_id . ' expired.');
             }
         } else {
             if ($user === false || $t->user_id != $user->id) {
                 $user = User::staticGet($t->user_id);
             }
             $catalog = ConnectionManager::connectToCatalog();
             if ($catalog && $catalog->status) {
                 $account = new User_account();
                 $account->user_id = $t->user_id;
                 $account->cat_username = $t->cat_username;
                 if ($account->find(true)) {
                     if (!($patron = $catalog->patronLogin($t->cat_username, $account->cat_password))) {
                         $this->err('    Could not perform patron login for transaction ' . $t->transaction_id);
                         $failedCnt++;
                         continue;
                     }
                 }
                 $res = $catalog->markFeesAsPaid($patron, $t->amount);
                 if ($res === true) {
                     if (!$t->setTransactionRegistered($t->transaction_id)) {
                         $this->err('    Failed to update transaction ' . $t->transaction_id . 'as registered');
                     }
                     $registeredCnt++;
                 } else {
                     $t->setTransactionRegistrationFailed($t->transaction_id, $res);
                     $failedCnt++;
                     $this->msg('    Registration of transaction ' . $t->transaction_id . ' failed');
                     $this->msg("      {$res}");
                 }
             } else {
                 $this->err("Failed to connect to catalog ({$patronId})");
                 continue;
             }
         }
     }
     // Report paid and unregistered transactions whose registration
     // can not be re-tried:
     $tr = new Transaction();
     foreach ($tr->getUnresolvedTransactions($this->reportIntervalHours) as $t) {
         $this->msg("  Transaction id {$t->transaction_id} still unresolved.");
         if (!$t->setTransactionReported($t->transaction_id)) {
             $this->err('    Failed to update transaction ' . $t->transaction_id . ' as reported');
         }
         if (!isset($report[$t->driver])) {
             $report[$t->driver] = 0;
         }
         $report[$t->driver]++;
         $remindCnt++;
     }
     if ($registeredCnt) {
         $this->msg("  Total registered: {$registeredCnt}");
     }
     if ($expiredCnt) {
         $this->msg("  Total expired: {$expiredCnt}");
     }
     if ($failedCnt) {
         $this->msg("  Total failed: {$failedCnt}");
     }
     if ($remindCnt) {
         $this->msg("  Total to be reminded: {$remindCnt}");
     }
     $configArray = readConfig();
     $siteLocal = $configArray['Site']['local'];
     $interface = new UInterface($siteLocal);
     // Send report of transactions that need to be resolved manually:
     foreach ($report as $driver => $cnt) {
         if ($cnt) {
             $settings = getExtraConfigArray("VoyagerRestful_{$driver}");
             if (!$settings || !isset($settings['OnlinePayment']['errorEmail'])) {
                 $this->err("  Error email for expired transactions not defined for driver {$driver} ({$cnt} expired transactions)");
                 continue;
             }
             $email = $settings['OnlinePayment']['errorEmail'];
             $this->msg("  [{$driver}] Inform {$cnt} expired transactions for driver {$driver} to {$email}");
             $mailer = new VuFindMailer();
             $subject = "Finna: ilmoitus tietokannan {$driver} epäonnistuneista verkkomaksuista";
             $interface->assign('driver', $driver);
             $interface->assign('cnt', $cnt);
             $msg = $interface->fetch('Emails/online-payment-error.tpl');
             if (!($result = $mailer->send($email, $this->fromEmail, $subject, $msg))) {
                 $this->err("    Failed to send error email to customer: {$email}");
             }
         }
     }
     $this->msg("OnlinePayment monitor completed");
     $this->reportErrors();
 }
        return substr($file, $i + 1, 1);
    } else {
        return "";
    }
}
function getFileIndex($file)
{
    $i = strrpos($file, '.', -8);
    if ($i !== false) {
        return substr($file, $i + 2, strlen($file) - $i - 9);
    } else {
        return "";
    }
}
function getLogFile()
{
    global $logFile;
    if ($logFile != "") {
        return $logFile;
    } else {
        return LBASE_DIR . '/' . LOGFILE_SCHEDULE;
    }
}
function getStyle()
{
    return 'css/' . file_get_contents(BASE_DIR . '/css/extrastyle.txt');
}
$config = array();
$config = readConfig($config, LBASE_DIR . '/' . CONFIG_FILE1);
$config = readConfig($config, LBASE_DIR . '/' . CONFIG_FILE2);
$logFile = $config['log_file'];
 /**
  * Send scheduled alerts
  *
  * @return void
  */
 public function send()
 {
     global $configArray;
     global $interface;
     global $translator;
     $iso8601 = 'Y-m-d\\TH:i:s\\Z';
     ini_set('display_errors', true);
     $configArray = $mainConfig = readConfig();
     $datasourceConfig = getExtraConfigArray('datasources');
     $siteLocal = $configArray['Site']['local'];
     // Set up time zone. N.B. Don't use msg() or other functions requiring date before this.
     date_default_timezone_set($configArray['Site']['timezone']);
     $this->msg('Sending scheduled alerts');
     // Setup Local Database Connection
     ConnectionManager::connectToDatabase();
     // Initialize Mailer
     $mailer = new VuFindMailer();
     // Find all scheduled alerts
     $sql = 'SELECT * FROM "search" WHERE "schedule" > 0 ORDER BY user_id';
     $s = new SearchEntry();
     $s->query($sql);
     $this->msg('Processing ' . $s->N . ' searches');
     $user = false;
     $interface = false;
     $institution = false;
     $todayTime = new DateTime();
     while ($s->fetch()) {
         $lastTime = new DateTime($s->last_executed);
         if ($s->schedule == 1) {
             // Daily
             if ($todayTime->format('Y-m-d') == $lastTime->format('Y-m-d')) {
                 $this->msg('Bypassing search ' . $s->id . ': previous execution too recent (daily, ' . $lastTime->format($iso8601) . ')');
                 continue;
             }
         } elseif ($s->schedule == 2) {
             // Weekly
             $diff = $todayTime->diff($lastTime);
             if ($diff->days < 6) {
                 $this->msg('Bypassing search ' . $s->id . ': previous execution too recent (weekly, ' . $lastTime->format($iso8601) . ')');
                 continue;
             }
         } else {
             $this->msg('Search ' . $s->id . ': unknown schedule: ' . $s->schedule);
             continue;
         }
         if ($user === false || $s->user_id != $user->id) {
             $user = User::staticGet($s->user_id);
         }
         if (!$user->email || trim($user->email) == '') {
             $this->msg('User ' . $user->username . ' does not have an email address, bypassing alert ' . $s->id);
             continue;
         }
         $userInstitution = reset(explode(':', $user->username, 2));
         if (!$institution || $institution != $userInstitution) {
             $institution = $userInstitution;
             if (!isset($datasourceConfig[$institution])) {
                 foreach ($datasourceConfig as $code => $values) {
                     if (isset($values['institution']) && strcasecmp($values['institution'], $institution) == 0) {
                         $institution = $code;
                         break;
                     }
                 }
             }
             if (!($configArray = $this->readInstitutionConfig($institution))) {
                 continue;
             }
             $configArray['Site']['url'] = $s->schedule_base_url;
             // Start Interface
             $interface = new UInterface($siteLocal);
             $validLanguages = array_keys($configArray['Languages']);
             $dateFormat = new VuFindDate();
         }
         $language = $user->language;
         if (!in_array($user->language, $validLanguages)) {
             $language = $configArray['Site']['language'];
         }
         $translator = new I18N_Translator(array($configArray['Site']['local'] . '/lang', $configArray['Site']['local'] . '/lang_local'), $language, $configArray['System']['debug']);
         $interface->setLanguage($language);
         $minSO = unserialize($s->search_object);
         // Check minified search object type
         $searchObject = SearchObjectFactory::deminify($minSO);
         if (!$searchObject instanceof SearchObject_Solr) {
             $this->msg('Search ' . $s->id . ': search object type not supported');
             continue;
         }
         // Create a new search object to avoid cached defaults for e.g.
         // hidden filters.
         $searchObject = SearchObjectFactory::initSearchObject();
         $searchObject->deminify($minSO);
         $searchObject->setSort('first_indexed desc');
         $searchTime = time();
         $searchDate = gmdate($iso8601, time());
         $searchObject->setLimit(50);
         $searchObject->disableLogging();
         $results = $searchObject->processSearch();
         if (PEAR::isError($results)) {
             $this->msg('Search ' . $s->id . ' failed: ' . $results->getMessage());
             continue;
         }
         if ($searchObject->getResultTotal() < 1) {
             $this->msg('No results found for search ' . $s->id);
             continue;
         }
         $newestRecordDate = date($iso8601, strtotime($results['response']['docs'][0]['first_indexed']));
         $lastExecutionDate = $lastTime->format($iso8601);
         if ($newestRecordDate < $lastExecutionDate) {
             $this->msg('No new results for search ' . $s->id . ": {$newestRecordDate} < {$lastExecutionDate}");
         } else {
             $this->msg('New results for search ' . $s->id . ": {$newestRecordDate} >= {$lastExecutionDate}");
             $interface->assign('summary', $searchObject->getResultSummary());
             $interface->assign('searchDate', $dateFormat->convertToDisplayDate("U", floor($searchTime)));
             $interface->assign('lastSearchDate', $dateFormat->convertToDisplayDate("U", floor($lastTime->getTimestamp())));
             $records = array();
             foreach ($results['response']['docs'] as &$doc) {
                 $docDate = date($iso8601, strtotime($doc['first_indexed']));
                 if ($docDate < $lastExecutionDate) {
                     break;
                 }
                 $record = RecordDriverFactory::initRecordDriver($doc);
                 $records[] = $interface->fetch($record->getSearchResult('email'));
             }
             $interface->assign('recordSet', $records);
             $key = $this->getSecret($user, $s->id);
             $params = array('id' => $s->id, 'type' => 'alert', 'key' => $key);
             $unsubscribeUrl = $configArray['Site']['url'] . '/MyResearch/Unsubscribe?' . http_build_query($params);
             $interface->assign('info', array('time' => $dateFormat->convertToDisplayDate("U", floor($searchObject->getStartTime())), 'url' => $searchObject->renderSearchUrl(), 'searchId' => $searchObject->getSearchId(), 'description' => $searchObject->displayQuery(), 'filters' => $searchObject->getFilterList(), 'hits' => $searchObject->getResultTotal(), 'speed' => round($searchObject->getQuerySpeed(), 2) . "s", 'schedule' => $s->schedule, 'last_executed' => $s->last_executed, 'recordCount' => count($records), 'unsubscribeUrl' => $unsubscribeUrl));
             $searchObject->close();
             // Load template
             $message = $interface->fetch('MyResearch/alert-email.tpl');
             if (strstr($message, 'Warning: Smarty error:')) {
                 $this->msg("Message template processing failed: {$message}");
                 continue;
             }
             $result = $mailer->send($user->email, $configArray['Site']['email'], translate('Scheduled Alert Results'), $message);
             if (PEAR::isError($result)) {
                 $this->msg("Failed to send message to {$user->email}: " . $result->getMessage());
                 continue;
             }
         }
         // Update search date
         $s->changeLastExecuted($searchDate);
     }
     $this->reportErrors();
     $this->msg('Scheduled alerts execution completed');
 }
Exemple #24
0
<?php

define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
//ob_implicit_flush(false);
//ESTA LINEA ES NUEVA
require_once "../application/models/applicationModel.php";
require_once "../application/models/usersModel.php";
$configFile = '../application/configs/config.ini';
//$context='development';
$context = 'production';
$config = readConfig($configFile, $context);
//print_r($config);
$arrayUser = initArrayUser();
if (isset($_GET['action'])) {
    $action = $_GET['action'];
} else {
    $action = 'select';
}
switch ($action) {
    case 'update':
        // 		die("esto es update");
        //ob_start();
        if ($_POST) {
            //Leer el array
            $arrayUser = readUsersFromFile($config['filename']);
            //Modificar el usuario segun ID
            $imageName = updateImage($_FILES);
            //print_r($arrayUser);
            $arrayUser[$_GET['id']] = implode('|', $_POST);
            //Escrivir todo el array en un archivo
            updateToFile($imageName, $_GET['id']);
Exemple #25
0
<?php

/**
 * Работа с OpenAPI
 * ВНИМАНИЕ! Скрипт будет использовать файл, который создаётся в initApi/init.php
 */
require '../header.php';
require '../lib.inc.php';
// Файл с функцией, генерирующей secret_key
require 'sign.php';
// Название метода, к которому производится обращение
$method = 'getCities';
// Константа OPEN_API_URL определяется в lib.inc.php
$openApiUrl = OPEN_API_URL . $method;
try {
    // Читаем конфигурацию, сохранённую во время выполнения скрипта initApi/init.php
    // http://docs.multishipinitapiv1.apiary.io/
    $jsonConfig = readConfig();
    $postData = array('client_id' => $jsonConfig->config->clientId);
    // Генерируем secret_key
    $secretKey = sign($jsonConfig->config->methodKeys->{$method}, $postData);
    // Добавляем полученный secret_key к массиву, который будет передан методом POST
    $postData['secret_key'] = $secretKey;
    $result = sendRequestViaCurl($openApiUrl, $postData);
} catch (Exception $e) {
    echo '<p>Произошла неисправимая ошибка: ' . $e->getMessage() . '</p>';
}
require '../footer.php';
 */
require '../header.php';
require '../lib.inc.php';
// Файл с функцией, генерирующей secret_key
require 'sign.php';
// Название метода, к которому производится обращение
$method = 'confirmSenderOrders';
// Константа OPEN_API_URL определяется в lib.inc.php
$openApiUrl = OPEN_API_URL . $method;
try {
    // Читаем конфигурацию, сохранённую во время выполнения скрипта initApi/init.php
    // http://docs.multishipinitapiv1.apiary.io/
    $jsonConfig = readConfig();
    $postData = array('client_id' => $jsonConfig->config->clientId);
    //Читаем данные, полученные при создании заказа, чтобы "взять" order_id
    $jsonOrder = readConfig('createOrder.json');
    $postData['order_id'] = $jsonOrder->data->order_id;
    //планируемая дата отгрузки заказов в UNIX формате
    $postData['date_shipment'] = 1402401322;
    // Генерируем secret_key
    $secretKey = sign($jsonConfig->config->methodKeys->{$method}, $postData);
    // Добавляем полученный secret_key к массиву, который будет передан методом POST
    $postData['secret_key'] = $secretKey;
    $result = sendRequestViaCurl($openApiUrl, $postData);
    //Формируем файл, чтобы потом получить номер парсела для распечатки сопроводительных документов
    curlAnswerHandler($result, function () use($result) {
        file_put_contents('parcel_id.json', $result['data']);
    });
} catch (Exception $e) {
    echo '<p>Произошла неисправимая ошибка: ' . $e->getMessage() . '</p>';
}
Exemple #27
0
<?php

require_once "../application/models/applicationModel.php";
require_once "../application/models/usersModel.php";
$config = readConfig('../application/configs/config.ini', 'development');
if (isset($_GET['action'])) {
    $action = $_GET['action'];
} else {
    $action = 'select';
}
switch ($action) {
    case 'update':
        // 		die("esto es update");
        if ($_POST) {
        } else {
            $arrayUser = readUser($_GET['id']);
            echo "<pre>";
            print_r($arrayUser);
            echo "</pre>";
        }
    case 'insert':
        if ($_POST) {
            $imageName = uploadImage($_FILES);
            writeToFile($imageName);
            header("Location: users.php?action=select");
            exit;
        } else {
            //			definir arrayUser
            include "../application/views/formulario.php";
        }
        break;
Exemple #28
0
    if ($html->find('.product-info-size', 0)) {
        $colorsvariations = $html->find('.product-info-size', 0)->find('a');
        foreach ($colorsvariations as $ck => $cv) {
            $sizes[] = $cv->plaintext;
        }
        $sizes = implode("| ", $sizes);
    } else {
        $sizes = "";
    }
    $description = $html->find('#custom-description', 0);
    $otherImages = array();
    $otherImage = $description->find('img');
    foreach ($otherImages as $ik => $iv) {
        $otherImages[] = $iv->src;
    }
    if ($html->find('.ui-breadcrumb')) {
        $category = $html->find('.ui-breadcrumb h2');
    }
    if ($html->find('.col-main')) {
        $category = $html->find('.m-sop-crumb', 0)->find('b');
    }
    $key = count($category) - 1;
    $category = str_replace(" ", "_", trim($category[$key]->plaintext));
    $otherImages = implode(";", $otherImages);
    $description = html_entity_decode($description->plaintext);
    print_r(array($store_id, $category, $shippingCostToBrazil, $ordersCount, $productRating, $productName, $discountPrice, $promocodes, $productPrice, $colors, $sizes, $description, $images, $thumbs, $otherImages));
    writeCSV($category, array($store_id, $category, $shippingCostToBrazil, $ordersCount, $productRating, $productName, $discountPrice, $promocodes, $productPrice, $colors, $sizes, $description, $images, $thumbs, $otherImages));
}
$storeconfig = readConfig();
$productURL = getchStoreInfo($storeconfig);
scraperX($productURL);
Exemple #29
0
if (isset($_COOKIE["display_mode"])) {
    if ($_COOKIE["display_mode"] == "Simple") {
        $toggleButton = "Full";
        $displayStyle = 'style="display:none;"';
    }
}
$streamButton = "MJPEG-Stream";
$mjpegmode = 0;
if (isset($_COOKIE["stream_mode"])) {
    if ($_COOKIE["stream_mode"] == "MJPEG-Stream") {
        $streamButton = "Default-Stream";
        $mjpegmode = 1;
    }
}
$config = readConfig($config, CONFIG_FILE1);
$config = readConfig($config, CONFIG_FILE2);
$video_fps = $config['video_fps'];
$divider = $config['divider'];
?>

<html>
   <head>
      <meta name="viewport" content="width=550, initial-scale=1">
      <title><?php 
echo CAM_STRING;
?>
</title>
      <link rel="stylesheet" href="css/style_minified.css" />
      <link rel="stylesheet" href="<?php 
echo getStyle();
?>
Exemple #30
0
function readConfig($i_file, &$o_out)
{
    global $FileMaxLength;
    if (false == is_file($i_file)) {
        return;
    }
    if ($fHandle = fopen($i_file, 'r')) {
        $data = fread($fHandle, $FileMaxLength);
        fclose($fHandle);
        $o_out[$i_file] = json_decode($data, true);
        if (array_key_exists('include', $o_out[$i_file]['cgru_config'])) {
            foreach ($o_out[$i_file]['cgru_config']['include'] as $file) {
                readConfig($file, $o_out);
            }
        }
    }
}