/**
 *  Print SOAP Fault
 */
function printFault($exception, $client)
{
    echo '<h2>Fault</h2>' . "<br>\n";
    echo "<b>Code:</b>{$exception->faultcode}<br>\n";
    echo "<b>String:</b>{$exception->faultstring}<br>\n";
    writeToLog($client);
}
function checkHeaders()
{
    global $response;
    if (!function_exists('getallheaders')) {
        function getallheaders()
        {
            while (@ob_end_flush()) {
            }
            $headers = '';
            foreach ($_SERVER as $name => $value) {
                if (substr($name, 0, 5) == 'HTTP_') {
                    $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
                }
            }
            return $headers;
        }
    }
    foreach (getallheaders() as $name => $value) {
        writeToLog("{$name}", "{$value}");
        $response[$name] = $value;
        if (strcasecmp($name, "Content-type") == 0 and strcasecmp($value, "application/json") == 0) {
            return true;
        }
    }
    return false;
    //return true;
}
Example #3
0
function userLogin($username, $password, $log = true)
{
    global $USER, $MSG;
    if ($username == "") {
        array_push($MSG, getstring('warning.login.noemail'));
        return false;
    }
    if ($password == "") {
        array_push($MSG, getstring('warning.login.nopassword'));
        return false;
    }
    $USER = new User($username);
    $USER->setUsername($username);
    $USER->password = $password;
    if ($USER instanceof User) {
        if ($USER->validPassword($password)) {
            $_SESSION["session_username"] = $USER->getUsername();
            setcookie("user", $USER->getUsername(), time() + 60 * 60 * 24 * 30, "/");
            setLang($USER->getProp('lang'));
            if ($log) {
                writeToLog('info', 'login', 'user logged in');
            }
            return true;
        } else {
            array_push($MSG, getstring('warning.login.invalid'));
            writeToLog('info', 'loginfailure', 'username: ' . $username);
            unset($USER);
            return false;
        }
    } else {
        return false;
    }
}
/**
 *  Print SOAP Fault
 */
function printFault($exception, $client)
{
    echo '<h2>Fault</h2>' . "<br>\n";
    echo "<b>Code:</b>{$exception->faultcode}<br>\n";
    echo "<b>String:</b>{$exception->faultstring}<br>\n";
    writeToLog($client);
    echo '<h2>Request</h2>' . "\n";
    echo '<pre>' . htmlspecialchars($client->__getLastRequest()) . '</pre>';
    echo "\n";
}
Example #5
0
function _mysql_query($query, $db)
{
    global $CONFIG;
    $start = microtime(true);
    $result = mysql_query($query, $db);
    if (!$result) {
        writeToLog('error', 'database', $query);
    }
    $CONFIG->mysql_queries_time += microtime(true) - $start;
    $CONFIG->mysql_queries_count++;
    return $result;
}
function addMedia($data)
{
    global $kalturaUploadsUser, $kalturaUploadsPassword;
    $tags = $data['tags'];
    $tags = json_decode($tags, true);
    $userID = $tags['userid'];
    $serverVersion = $tags['version'];
    writeToLog("tags: {$tags}\n");
    writeToLog("userID: {$userID}\n");
    writeToLog("serverVersion: {$serverVersion}\n");
    //writeToLog(print_r($data, true));
    // TODO: read this in from a config file
    $link = mysql_connect('localhost', $kalturaUploadsUser, $kalturaUploadsPassword);
    //if (!$link) die('Not connected : ' . mysql_error());
    if (!$link) {
        writeToLog('Not connected : ' . mysql_error());
    }
    if ("clas_demo_server" == $serverVersion) {
        $db = "dev_annotation_tool";
    } elseif ("clas_prod_server" == $serverVersion) {
        $db = "annotation_tool";
    } elseif ("clas_prod2_server" == $serverVersion) {
        // TODO: switch name when music finishes using OVAL
        $db = "prod_annotation_tool";
        // ("clas_demo_server" == $tags)
    } else {
    }
    $db_selected = mysql_select_db($db, $link);
    //if (!$db_selected) die ("Can't use $db: " . mysql_error(); writeToLog("\nCan't use $db: " . mysql_error()););
    writeToLog("u:{$kalturaUploadsUser} p:{$kalturaUploadsPassword}\n");
    if (!$db_selected) {
        writeToLog("\nCan't use {$db}: " . mysql_error());
    }
    // get description, it's not available in notification
    $kclient = startKalturaSession();
    $result = $kclient->media->get($data['entry_id'], null);
    $arrayObj = new ArrayObject($result);
    $description = $arrayObj['description'];
    $duration = $data['length_in_msecs'] / 1000;
    $query = "INSERT INTO media VALUES ('{$data['entry_id']}', '{$userID}', '{$data['name']}', '{$description}', {$duration}, '{$data['thumbnail_url']}', 0, 0, NULL)";
    writeToLog("insertIntoDatabase() query: {$query}\n");
    $result = mysql_query($query, $link);
    //if (!$result) die('Invalid query (insertIntoDatabase): ' . mysql_error(); writeToLog("Invalid query"););
    if (!$result) {
        writeToLog("Invalid query");
    }
    mysql_close($link);
}
Example #7
0
function setLang($lang, $redirect = false)
{
    global $USER, $API;
    $_SESSION["session_lang"] = $lang;
    unset($_SESSION["lang_strings"]);
    if ($USER->userid != 0) {
        $API->setUserProperty($USER->userid, 'lang', $lang);
    }
    if ($redirect) {
        //redirect back to same page (to avoid the form resubmission popup)
        $url = "http" . (!empty($_SERVER["HTTPS"]) ? "s" : "") . "://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        writeToLog('info', 'langchange', 'changed to: ' . $lang);
        header('Location: ' . $url);
        die;
    }
}
Example #8
0
            $xml = $xml . "<email>" . $reg_mail . "</email>";
            $xml = $xml . "</registration>";
            echo $xml;
            writeToLog("End RegisterUser.\n{$xml}\n\n");
            exit;
        } else {
            // Build XML for a Failure response.
            writeToLog("User registration failed. User already exists. Writting failure XML.");
            header("Content-type: text/xml");
            $xml = "<?xml version='1.0' standalone='yes'?>";
            $xml = $xml . "<registration>";
            $xml = $xml . "<result>Failure</result>";
            $xml = $xml . "<name>" . $reg_user . "</name>";
            $xml = $xml . "<reason>User already exists.</reason>";
            $xml = $xml . "</registration>";
            echo $xml;
            writeToLog("End RegisterUser.\n{$xml}\n\n");
            exit;
            exit;
        }
        // End response
    } else {
        // Key compare failed. Redirect to an error page.
        setcookie("message", "Missing API private key.", time() + 300, '/');
        header('Location: ../error.php');
    }
    // End key compare.
}
// End post request
setcookie("message", "You can not make requests using a web browser.", time() + 300, '/');
header('Location: ../error.php');
Example #9
0
function printStandardReport($type, $cl)
{
    global $print_results, $log_format, $messages;
    if ($print_results) {
        print str_replace('%cur_time', date("H:i:s"), $messages[$type][$cl]);
        flush();
    }
    if ($log_format == "html") {
        writeToLog(str_replace('%cur_time', date("H:i:s"), $messages[$type][0]));
    } else {
        writeToLog(str_replace('%cur_time', date("H:i:s"), $messages[$type][1]));
    }
}
Example #10
0
if (isset($_GET['good'])) {
    $res = sendCurlResponse($_GET['good']);
    echo $res;
}
if (isset($_POST['mode']) && $_POST['mode'] == 'log') {
    $name = iconv("UTF-8", "Windows-1251", $_POST['good']);
    $id = $_POST['id'];
    $ip = "unknown";
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    echo writeToLog($name, $id, $ip);
}
function sendCurlResponse_old($id)
{
    global $part_id;
    $server = "http://p.my-shop.ru/cgi-bin/myorder.pl";
    $request = "partner={$part_id}&master=&cart={$id}-1&cartsource=get";
    $ch = curl_init($server);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $content = curl_exec($ch);
    $curl_errno = curl_errno($ch);
Example #11
0
            exit;
        } else {
            // Build XML for a Failure response.
            writeToLog("User and password failed. Writting failure XML.");
            header("Content-type: text/xml");
            $xml = "<?xml version='1.0' standalone='yes'?>";
            $xml = $xml . "<authentication>";
            $xml = $xml . "<result>Failure</result>";
            $xml = $xml . "<id></id>";
            $xml = $xml . "<name></name>";
            $xml = $xml . "<email></email>";
            $xml = $xml . "</authentication>";
            echo $xml;
            writeToLog("End authentication.\n{$xml}\n\n");
            exit;
        }
        // End response
        writeToLog($xml);
    } else {
        // Key compare failed. Redirect to an error page.
        setcookie("message", "Missing API private key.", time() + 300, '/');
        header('Location: ../error.php');
    }
    // End key compare.
}
// End post request
setcookie("message", "An error has occured. All conditionals failed.", time() + 300, '/');
header('Location: ../error.php');
?>

Example #12
0
                        $date = date('Y-m-d H:i:s');
                    }
                    writeToLog("info", "tracker", json_encode($tracks), 0, 0, 0, 0, $digest, $date);
                    $response->result = true;
                }
            } catch (Exception $e) {
                $response->result = false;
            }
        }
    }
}
/*
 * Output the response
 */
echo json_encode($response);
writeToLog("info", "pagehit", $_SERVER["REQUEST_URI"] . " method: " . $method);
$API->cleanUpDB();
function curPageURL()
{
    $pageURL = 'http';
    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
Example #13
0
 */
require_once dirname(__FILE__) . "/includes/global_deploy_config.php";
require_once dirname(__FILE__) . '/includes/kaltura/kaltura_functions.php';
require_once dirname(__FILE__) . "/includes/common.inc.php";
// override max_execution_time for this script because uploads to Kaltura can take a very long time
$max_execution_time = 60 * 60;
set_time_limit($max_execution_time);
writeToLog("\n-------------- Starting clas_dir/upload_to_kaltura.php -----------------\n");
// restrict this script to run from command line only
$sapi_type = php_sapi_name();
if ('cli' != substr($sapi_type, 0, 3)) {
    exit;
} else {
}
$title = stripslashes($argv[1]);
$description = stripslashes($argv[2]);
$userID = $argv[3];
$file = $argv[4];
$CopyrightTerm1 = $argv[5];
$CopyrightTerm2 = $argv[6];
$CopyrightTerm3 = $argv[7];
$CopyrightTerm4 = $argv[8];
writeToLog("{$file}: title {$title} -> upload started at " . date("H:i:s") . "\n");
// store custom data in 'tags' field since we aren't using the tags field
$data = "{$serverVersion},{$userID}" . ",{$CopyrightTerm1}" . ",{$CopyrightTerm2}" . ",{$CopyrightTerm3}" . ",{$CopyrightTerm4}" . "";
$fileToUpload = $uploadPath . $file;
writeToLog("calling uploadToKaltura({$fileToUpload}, {$title}, {$description}, {$data})" . "\n");
// die;
$entryID = uploadToKaltura($fileToUpload, $title, $description, $data);
writeToLog("{$file}: title {$title} -> upload finished at " . date("H:i:s") . ", result entry_id {$entryID}\n");
Example #14
0
function printWhiteLink($url, $title, $cl)
{
    global $db_con, $log_format, $copy, $no_log;
    $log_msg_txt = "\n{$url} found. \nTitle ignored, as it did not meet the whitelist.\n";
    $log_msg_html = "<br />Link:&nbsp;&nbsp;{$url}&nbsp;&nbsp;detected.<br />Title: {$title}<br /><span class='warnadmin'>Ignored, as the title did not meet the whitelist.</span><br />\n";
    if ($no_log == '0') {
        if ($cl != 1) {
            print $log_msg_html;
        } else {
            print $log_msg_txt;
        }
        @ob_flush();
        @flush();
    }
    if ($log_format == "html") {
        writeToLog($log_msg_html, $copy);
    } else {
        writeToLog($log_msg_txt, $copy);
    }
}
Example #15
0
        $newLocation = $client->__setLocation(setEndpoint('endpoint'));
    }
    $response = $client->processShipment($request);
    // FedEx web service invocation
    if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') {
        printSuccess($client, $response);
        // Create PNG or PDF label
        // Set LabelSpecification.ImageType to 'PDF' for generating a PDF label
        $fp = fopen(SHIP_LABEL, 'wb');
        fwrite($fp, $response->CompletedShipmentDetail->CompletedPackageDetails->Label->Parts->Image);
        fclose($fp);
        echo 'Label <a href="./' . SHIP_LABEL . '">' . SHIP_LABEL . '</a> was generated.';
    } else {
        printError($client, $response);
    }
    writeToLog($client);
    // Write to log file
} catch (SoapFault $exception) {
    printFault($exception, $client);
}
function addShipper()
{
    $shipper = array('Contact' => array('PersonName' => 'ASM Raju', 'CompanyName' => 'ELS', 'PhoneNumber' => '1234567890'), 'Address' => array('StreetLines' => array('Address Line 1'), 'City' => 'Austin', 'StateOrProvinceCode' => 'TX', 'PostalCode' => '73301', 'CountryCode' => 'US'));
    return $shipper;
}
function addRecipient()
{
    $recipient = array('Contact' => array('PersonName' => 'Rubai Mahbub', 'CompanyName' => 'Entrance', 'PhoneNumber' => '1234567891'), 'Address' => array('StreetLines' => array('Address Line 1'), 'City' => 'Richmond', 'StateOrProvinceCode' => 'BC', 'PostalCode' => 'V7C4V4', 'CountryCode' => 'CA', 'Residential' => false));
    return $recipient;
}
function addShippingChargesPayment()
            writeToLog("{$buildLogPath}/build.log", " Updating standard bootloader...<br>");
            $svnLoad->PrepareKextpackDownload("Bootloader", "StandardBoot", $chameRow['foldername']);
        }
    }
    //
    // Step 3 : Preparing/Applying Fixes and chameleon modules
    //
    writeToLog("{$buildLogPath}/build.log", "<br><b>Step 3) Apply and prepare fixes for system:</b><br>");
    applyFixes();
    writeToLog("{$buildLogPath}/build.log", " Copying selected chameleon modules...</b><br>");
    $chamModules->copyChamModules($modeldb[$modelRowID]);
    //
    // Step 4 : Start the download of prepared files for download
    //
    writeToLog("{$buildLogPath}/build.log", "<br><b>Step 3) Start the download of prepared files:</b><br>");
    writeToLog("{$buildLogPath}/build.log", "<br>");
    // Get all the files in comma seperated way
    $dListInfo = shell_exec("ls -m {$buildLogPath}/dLoadScripts/");
    $dScriptsArray = explode(',', $dListInfo);
    if (!is_dir("{$buildLogPath}/dLoadStatus")) {
        system_call("mkdir {$buildLogPath}/dLoadStatus");
    }
    foreach ($dScriptsArray as $dScript) {
        $dScript = preg_replace('/\\s+/', '', $dScript);
        //remove white spaces in name
        if ($dScript != "") {
            system_call("sh {$buildLogPath}/dLoadScripts/{$dScript} >> {$buildLogPath}/internetCheckLog.log &");
        }
    }
}
//-------------------------> Here starts the Vendor and model selector - but only if $action is empty
Example #17
0
<?php

/*
Pro Sites (Amazon Payments Gateway IPN handler for backwards compatibility)

If you have existing subscriptions using the old pre 3.0 Supporter Paypal gateway, then it is important to
overwrite the supporter-amazon.php file in your webroot with this one to prevent a lapse in subscription
payments being applied.
*/
if (!isset($_POST['signature'])) {
    // Did not find expected POST variables. Possible access attempt from a non Amazon site.
    writeToLog('Invalid visit to the IPN script from IP ' . $_SERVER['REMOTE_ADDR'] . "\n" . var_export($_POST, true));
    header('Status: 404 Not Found');
    exit;
} else {
    define('ABSPATH', dirname(__FILE__) . '/');
    require_once ABSPATH . 'wp-load.php';
    global $wpdb, $psts;
    $secret_key = get_site_option("supporter_amazon_secretkey");
    $access_key = get_site_option("supporter_amazon_accesskey");
    $utils = new Amazon_FPS_SignatureUtilsForOutbound($aws_access_key, $aws_secret_key);
    $self_address = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    $valid = $utils->validateRequest($_POST, $self_address, "POST");
    if (!$valid) {
        header('Status: 401 Unauthorized');
        exit;
    }
    list($blog_id, $period, $amount, $type, $stamp) = explode('_', $_POST['referenceId']);
    // process Amazon response
    switch ($_POST['status']) {
        case 'PI':
Example #18
0
 function svnDataLoader($logType, $categ, $fname)
 {
     global $workPath, $svnpackPath, $edp;
     switch ($logType) {
         case "AppsTools":
             $logPath = "{$workPath}/logs/apps";
             // create app local download directory if not found
             if (!is_dir("{$workPath}/apps")) {
                 system_call("mkdir {$workPath}/apps");
             }
             if (!is_dir("{$workPath}/apps/{$categ}")) {
                 system_call("mkdir {$workPath}/apps/{$categ}");
             }
             $dataDir = "{$workPath}/apps/{$categ}";
             $svnpath = "apps/{$categ}/{$fname}";
             $logName = "appInstall";
             break;
         case "Kexts":
             $logPath = "{$workPath}/logs/build";
             // create fix local download directory if not found
             if (!is_dir("{$svnpackPath}")) {
                 system_call("mkdir {$svnpackPath}");
             }
             if (!is_dir("{$svnpackPath}/{$categ}")) {
                 system_call("mkdir {$svnpackPath}/{$categ}");
             }
             $dataDir = "{$svnpackPath}/{$categ}";
             $svnpath = "kextpacks/{$categ}/{$fname}";
             $logName = "kextInstall";
             break;
         case "Update":
             $logPath = "{$workPath}/logs/update";
             // create update local download directory if not found
             if (!is_dir("{$svnpackPath}")) {
                 system_call("mkdir {$svnpackPath}");
             }
             if (!is_dir("{$svnpackPath}/{$categ}")) {
                 system_call("mkdir {$svnpackPath}/{$categ}");
             }
             $dataDir = "{$svnpackPath}/{$categ}";
             $svnpath = "kextpacks/{$categ}/{$fname}";
             $logName = "packUpdateLog";
             break;
         case "Fixes":
             $logPath = "{$workPath}/logs/fixes";
             // create fix local download directory if not found
             if (!is_dir("{$svnpackPath}")) {
                 system_call("mkdir {$svnpackPath}");
             }
             if (!is_dir("{$svnpackPath}/{$categ}")) {
                 system_call("mkdir {$svnpackPath}/{$categ}");
             }
             $dataDir = "{$svnpackPath}/{$categ}";
             $svnpath = "kextpacks/{$categ}/{$fname}";
             $logName = "fixInstall";
             break;
     }
     // create log directory if not found
     if (!is_dir("{$workPath}/logs")) {
         system_call("mkdir {$workPath}/logs");
     }
     if (!is_dir("{$logPath}")) {
         system_call("mkdir {$logPath}");
     }
     //
     // Run download script (which downloads data from SVN) in background to download asynchronously
     // (synchronous which is without background download has freezing problem and
     //  we can't provide download status in php due to no multhreading)
     //
     if (is_dir("{$dataDir}/{$fname}")) {
         $checkoutCmd = "if ping -q -c 2 google.com; then if svn --non-interactive --username edp --password edp --quiet --force update {$dataDir}/{$fname}; then echo \"{$fname} file(s) updated finished<br>\"; touch {$logPath}/Success_{$fname}.txt; fi else echo \"{$fname} file(s) update failed due to no internet<br>\"; touch {$logPath}/Fail_{$fname}.txt; fi";
         writeToLog("{$logPath}/{$fname}.sh", "{$checkoutCmd};");
         system_call("sh {$logPath}/{$fname}.sh >> {$logPath}/{$logName}.log &");
     } else {
         $checkoutCmd = "cd {$dataDir}; if ping -q -c 2 google.com; then if svn --non-interactive --username osxlatitude-edp-read-only --quiet --force co http://osxlatitude-edp.googlecode.com/svn/{$svnpath}; then echo \"{$fname} file(s) download finished<br>\"; touch {$logPath}/Success_{$fname}.txt; fi else echo \"{$fname} file(s) download failed due to no internet<br>\"; touch {$logPath}/Fail_{$fname}.txt; fi";
         writeToLog("{$logPath}/{$fname}.sh", "{$checkoutCmd};");
         system_call("sh {$logPath}/{$fname}.sh >> {$logPath}/{$logName}.log &");
     }
 }
Example #19
0
function persistSyllabusContent($file)
{
    // MYSQL HARDCODED VALUES
    $servername = "localhost";
    $username = "******";
    $password = "******";
    $dbname = "c_syllabus";
    writeToLog($file);
    if (is_file($file)) {
        // Connect to MySQL Database
        $conn = new mysqli($servername, $username, $password, $dbname);
        if ($conn->connect_error) {
            writeToLog("Connection failed: " . $conn->connect_error);
            die("Connection failed: " . $conn->connect_error);
        }
        // Prepare SQL statement
        $sth = $conn->prepare("UPDATE course_syllabi SET content = ? WHERE id = ?");
        $sth->bind_param('ss', $content, $id);
        // Get Syllabus ID from filename
        $id = substr(basename($file), 0, -4);
        // Open Text file and read contents
        $myfile = fopen($file, "r") or die("Unable to open file!");
        $content = fread($myfile, filesize($file));
        fclose($myfile);
        $content = preg_replace('/[^a-zA-Z0-9\\s]/', '', $content);
        // Update database
        $sth->send_long_data(0, $content);
        $sth->execute();
        $sth->close();
        $conn->close();
    }
}
Example #20
0
function printStandardReport($type, $cl)
{
    global $messages, $copy;
    if (Configure::read('print_results')) {
        if (isset($messages[$type][$cl])) {
            print str_replace('%cur_time', date("H:i:s"), $messages[$type][$cl]);
        }
        // ob_flush();
        flush();
    }
    if (Configure::read('log_format') == "html") {
        if (isset($messages[$type][0])) {
            writeToLog(str_replace('%cur_time', date("H:i:s"), $messages[$type][0]), $copy);
        }
    } else {
        if (isset($messages[$type][1])) {
            writeToLog(str_replace('%cur_time', date("H:i:s"), $messages[$type][1]));
        }
    }
}
/**
 * Функция отправляет письма
 */
function sendMail()
{
    // Явное указание на использование глобальных переменных
    global $localhostPath, $dbConnect, $prefix, $maxMailSend, $maxMailSendInDay, $log, $timeout;
    // Устанавливаем значение "по умолчанию" переменной статуса завершения функции
    $status = false;
    // Формирвоание текста сообщения о наличии файла "stop.txt"
    $stopFileExistlogMessage = date('d.m.Y H:i:s') . ": Выполнение предыдущей версии скрипта еще не завершено!";
    // Формирвоание текста сообщения о наличии файла "gotLimit.txt"
    $gotlimitFileExistlogMessage = date('d.m.Y H:i:s') . ": Достигнут суточный лимит отправляемых писем. Рассылку необходимо возобновить вручную через 24 часа!";
    // Если файла "gotLimit.txt" на сервере нет
    // Если файла "stop.txt" на сервере нет
    // Если соединение с БД установлено
    // И параметры скрипта переопределены
    // И максимальное количество отправляемых за раз писем не равно 0
    if (!checkFileExists('gotLimit.txt', $gotlimitFileExistlogMessage) && !checkFileExists('stop.txt', $stopFileExistlogMessage) && dbConnect() && setParams() && $maxMailSend !== 0) {
        // Создаем файл "stop.txt"
        createFile('stop.txt', 'stop');
        // Если есть активные почтовые рассылки, получаем параметры первой активной рассылки
        if ($mail = getMailingGroup()) {
            // Добавляем сообщение о начале работы скрипта в массив лога
            $log[] = date('d.m.Y H:i:s') . ": Начало работы скрипта!";
            // Получение списка адресатов, кому были отправлены письма
            $whoSent = $mail['whoSent'] ? explode(',', $mail['whoSent']) : array();
            // Получаем массив категорий материалов рассылки
            $categories = $mail['categories'] ? array_diff(explode(',', $mail['categories']), array('', ' ', null)) : array();
            // Получаем количество отправленных писем из отчера за предыдущий день
            $sendedYesterday = getYesterdayReportData();
            // Определение количества отправленных писем
            $sendedInAllTime = $mail['log'] > count($whoSent) ? $mail['log'] : count($whoSent);
            // Подсчитываем, сколько еще можно отправить писем за этот день, не превышая лимитов хостинга
            $needToSend = $maxMailSendInDay + $sendedYesterday - $sendedInAllTime;
            // Переопределение максимального количества отправляемых за раз писем
            $maxMailSend = $needToSend >= $maxMailSend ? $maxMailSend : $needToSend;
            // Если не достигнут суточный лимит количества отправляемых писем
            if ($needToSend > 0) {
                // Получение списка подписчиков активной рассылки
                $subscribers = getSubscribers($categories, $mail['log']);
                // Если массив подписчиков не пуст
                if (!empty($subscribers)) {
                    // Закрываем текущее соединение с БД, во избежание зазрыва соединения по таймауту
                    mysql_close($dbConnect);
                    // Обход массива подписчиков
                    foreach ($subscribers as $subscriber) {
                        // Если количество отправленных писем меньше максимального количества отправляемых писем за раз
                        // И подписчику еще не отправлялось письмо
                        if ($countMailSend < $maxMailSend && !in_array($subscriber['email'], $whoSent)) {
                            // Установка временного интервала между отправками писем в 10 секунд
                            sleep($timeout);
                            // Определение значения по умолчанию сгенерированной строки, добавляемой к телу письма
                            $generatorStr = '';
                            // Если параметр "Подключать словарь генерации случайного текста?" рассылки установлен в позицию "Да"
                            if ($mail['generator'] == 1) {
                                // Получение сгенерированной строки случайного текста
                                $generator = generator();
                                // Если строка не сгенерирована
                                if (!$generator) {
                                    // Переход к следующей итерации цикла
                                    continue;
                                }
                                // Добавляем сгенерированную строчку случайного текста
                                $generatorStr = $generator;
                            }
                            /* --------- Генерация письма -------- */
                            // Тема письма
                            $subject = $mail['subject'];
                            // Формируем тело письма для отправки
                            // Подставляем Имя пльзователя в тело в шаблон письма если есть маркер -{fio}-
                            $body = str_replace('-{fio}-', $subscriber['fio'], $mail['textemail']);
                            // Подставляем Email пльзователя в тело в шаблон письма если есть маркер -{fio}-
                            $body = str_replace('-{email}-', $subscriber['email'], $body);
                            // Добавление сгенерированной строки к телу письма
                            $body .= $generatorStr;
                            // Формируем заголовок письма
                            $headers = "MIME-Version: 1.0\r\n";
                            $headers .= "Content-type: text/html; charset=utf-8\r\n";
                            $headers .= "From: " . $mail['myemail'] . "\r\n";
                            $headers .= "Reply-To: " . $mail['myemail'] . "\r\n";
                            /* --------- Отправка письма -------- */
                            // Отправка письма адресату
                            $sendingMail = mail($subscriber['email'], $subject, $body, $headers);
                            /* --------- Проверка результата операции отправки -------- */
                            // Если письмо успешно отправлено
                            if ($sendingMail) {
                                // Добавляем E-mail адрес подписчика в массив адресатов, кому уже отправлены письма
                                $whoSent[] = $subscriber['email'];
                                // Формируем запрос на обновление списка отправленных у подписчика
                                $updateSubscriberInfo[] = "(" . $subscriber['id'] . ", '" . addslashes($subscriber['downloadedDocs'] . "\r\n" . $mail['id'] . ". " . $mail['subject'] . " (" . date('H:i:s d.m.y') . ")") . "')";
                                $log[] = 'Письмо c id=' . $mail['id'] . ' успешно отправлено адресату ' . $subscriber['email'];
                            } else {
                                // Добавляем сообщение об ошибке в массив лога ошибок
                                $log[] = 'Письмо c id=' . $mail['id'] . ' не отправлено на е-mail ' . $subscriber['email'];
                            }
                            // Удаление переменных
                            unset($body, $subject, $header);
                            // Увеличиваем общий счетчик отправленных писем на единицу
                            $countMailSend++;
                        } else {
                            // Переход к следующей итерации цикла
                            continue;
                        }
                    }
                    // Формируем запрос в БД на обновление информации о рассылке
                    $query = "UPDATE `" . $prefix . "subscribers_emails` SET  `log`=" . ($mail['log'] + $countMailSend) . ", `whoSent`='" . implode(',', $whoSent) . "', `noteMail`='" . $mail['noteMail'] . "\r\n" . date('H:i:s d.m.Y') . ":Отправлено всего на " . count($whoSent) . " e-mail адресов' WHERE `id`=" . $mail['id'];
                } else {
                    // Формируем запрос в БД на обновление информации о рассылке
                    $query = "UPDATE `" . $prefix . "subscribers_emails` SET `log`=0, `published`=-1, `send_date`='" . date('Y-m-d H:i:s') . "', `whoSent`='" . implode(',', $whoSent) . "', `noteMail`='" . $mail['noteMail'] . "\r\n" . date('H:i:s d.m.Y') . ":Отправлено всего на " . count($whoSent) . " e-mail адресов' WHERE `id`=" . $mail['id'];
                }
                // Восстанавливаем отключенное ранее соединение с БД
                dbConnect();
                // Отправка запроса в БД и получение результата
                $resultToDb = mysql_query($query, $dbConnect);
                // Если последняя операция MySQL вернула сообщение об ошибке (не пустую строку)
                if (!$resultToDb) {
                    // Добавленеи сообщения об ошибках операции в MySQL в массив лога ошибок
                    $log[] = "MySQL query error: " . mysql_error() . ' (' . $query . ')';
                }
                // Если массив запросов на обновление списка отправленных материалов подписчику не пустой
                if ($updateSubscriberInfo) {
                    // Преобразовываем массив в строку
                    $updateSubscriberInfo = implode(',', $updateSubscriberInfo);
                    // Формируем строку запроса в БД на внесение изменений в данные подписчиков в БД
                    $updateSubscriberInfo = 'INSERT INTO `' . $prefix . 'subscribers` (`id`, `downloadedDocs`) VALUES' . $updateSubscriberInfo . ' ON DUPLICATE KEY UPDATE `downloadedDocs` = VALUES(`downloadedDocs`)';
                    // Отправка запроса в БД и получение результата
                    $res = mysql_query($updateSubscriberInfo, $dbConnect);
                    if (!$res) {
                        // Добавленеи сообщения об ошибках операции в MySQL в массив лога ошибок
                        $log[] = "MySQL query error: " . mysql_error() . ' (' . $query . ')';
                    }
                }
            } else {
                // Добавленеи сообщение о достижении суточного лимита в массив лога ошибок
                $log[] = "Достигнут суточный лимит отправляемых писем. Рассылка будет возобновлена завтра!";
                // Проверяем, существует ли файл "dayReport.txt" на сервере
                if (file_exists($localhostPath . 'dayReport.txt')) {
                    // Удаление файла "dayReport.txt"
                    unlink($localhostPath . 'dayReport.txt');
                }
                // Вызываем функцию создания файла отчета об общем количестве отправленных писем по текущей рассылке
                createFile('dayReport.txt', count($whoSent));
                // Вызываем функцию создания файла
                createFile('gotLimit.txt', 'true');
            }
            // Добавляем сообщение об окончании работы скрипта в массив лога
            $log[] = date('d.m.Y H:i:s') . ": Завершение работы скрипта!";
        } else {
            // Добавляем сообщение об окончании работы скрипта в массив лога
            $log[] = date('d.m.Y H:i:s') . ": Рассылка не ведется! Нет активных почтовых рассылок!";
        }
        // Удаление файла "stop"
        unlink($localhostPath . 'stop.txt');
        // Устанавливаем значение переменной статуса завершения функции
        $status = true;
    }
    // Закрываем текущее соединение с БД
    mysql_close($dbConnect);
    // Записываем логи в файл
    writeToLog();
    // Завершаем выполнение работы скрипта. Выходим из функции
    return $status;
}
        case 'RC=13':
            writeToLog($response);
            kill_session();
            $error_array = explode('=', $response_array['3']);
            echo "There was a problem with the payment.<br> Error messgae: " . $error_array['1'] . ".<br> Please double check your payment information and try again<br>";
            echo '<a href="payment.php">Back</a>';
            break;
        case 'RC=14':
            echo "Payment is not ok";
            writeToLog($response);
            kill_session();
            $error_array = explode('=', $response_array['3']);
            echo "There was a problem with the payment.<br> Error messgae: " . $error_array['1'] . ".<br> Please double check your payment information and try again<br>";
            echo '<a href="payment.php">Back</a>';
            break;
        case 'RC=15':
            writeToLog($response);
            kill_session();
            $error_array = explode('=', $response_array['3']);
            echo "There was a problem with the payment.<br> Error messgae: " . $error_array['1'] . ".<br> Please double check your payment information and try again<br>";
            echo '<a href="payment.php">Back</a>';
            break;
        case 'RC=999':
            writeToLog($response);
            kill_session();
            $error_array = explode('=', $response_array['3']);
            echo "There was a problem with the payment.<br> Error messgae: " . $error_array['1'] . ".<br> Please double check your payment information and try again<br>";
            echo '<a href="payment.php">Back</a>';
            break;
    }
}
Example #23
0
    $session[$key] = $value;
}
unset($session1);
$session['REQUEST'] = $request_id;
$session['GUEST_LOGIN_ID'] = $guest_login_id;
$session['GUEST_USERNAME'] = $guest_username;
$session['SECURITY'] = $security;
$session['LANGUAGE'] = LANGUAGE_TYPE;
$session['CHARSET'] = CHARSET;
if (isset($domain_id)) {
    $session['DOMAINID'] = $domain_id;
} else {
    $session['DOMAINID'] = $id_domain;
}
if ($session['MESSAGE'] != $lastMessageID) {
    writeToLog($guest_login_id . "==" . $lastMessageID . "==" . $session['MESSAGE']);
}
if ($active > 0) {
    $session['CHATTING'] = 1;
} else {
    $session['CHATTING'] = 0;
}
if ($active > 0 && $chatting > 0) {
    /*
            if ($initalised) {
                    $query = "SELECT `id`, `datetime`, `username`, `message`, `align`, `status` FROM " . $table_prefix . "messages WHERE `session` = '$guest_login_id' AND `status` >= '1' AND `id` > '$guest_message' ORDER BY `datetime`";
            } else {
                    $query = "SELECT `id`, `datetime`, `username`, `message`, `align`, `status` FROM " . $table_prefix . "messages WHERE `session` = '$guest_login_id' AND `status` >= '0' AND `id` > '$guest_message' ORDER BY `datetime`";
            }*/
    $query = "SELECT `id`, `datetime`, `username`, `message`, `align`, `status` FROM " . $table_prefix . "messages WHERE `session` = '{$guest_login_id}' AND `status` >= '0' AND `id` > '{$lastMessageID}' And username <> '{$guest_username}' ORDER BY `datetime`";
    $rows = $SQL->selectall($query);
Example #24
0
?>
info/about.php">About</a>
		</li>
		<li><a href="<?php 
echo $CONFIG->homeAddress;
?>
info/terms.php">Terms/License</a>
		</li>
		<li><a href="<?php 
echo $CONFIG->homeAddress;
?>
info/contact.php">Contact/Feedback</a>
		</li>
		<li><a href="http://alexlittle.net">Alex Little</a> &copy; <?php 
echo date('Y');
?>
		</li>
	</ul>

</div>
</body>
</html>

<?php 
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round($finish - $start, 4);
writeToLog("info", "pagehit", $_SERVER["REQUEST_URI"], $total_time, $CONFIG->mysql_queries_time, $CONFIG->mysql_queries_count);
$API->cleanUpDB();
Example #25
0
    $index = "description{$count}";
    $description = addslashes($_POST[$index]);
    $summary = "";
    $duration = "";
    $userID = "{$userID}";
    print_r($_POST);
    $index = "Customdata{$count}";
    $CopyrightFormData = $_POST[$index];
    // Get the copyright variables
    $CopyrightWithThePermissionOfTheCopyrightHolders = $CopyrightFormData["WithThePermissionOfTheCopyrightHolders"];
    $CopyrightFairDealingException = $CopyrightFormData["FairDealingException"];
    $CopyrightPublicDomain = $CopyrightFormData["PublicDomain"];
    $CopyrightOther = $CopyrightFormData["Other"];
    // run command as background process and do not wait for return (immediately return control to script)
    $command = "nohup php upload_to_kaltura.php " . "\"{$title}\" \"{$description}\" \"{$userID}\" \"{$file}\" " . "\"CopyrightWithThePermissionOfTheCopyrightHolders_{$CopyrightWithThePermissionOfTheCopyrightHolders}\" " . "\"CopyrightFairDealingException_{$CopyrightFairDealingException}\" " . "\"CopyrightPublicDomain_{$CopyrightPublicDomain}\" " . "\"CopyrightOther_{$CopyrightOther}\" " . "> /dev/null 2> /dev/null &";
    writeToLog("Running script from CLI:\n\n{$command}\n\n--------------\n\n");
    //print "command<br><br>$command";
    //die;
    system($command);
    $count++;
    // }
    $msg = $msg . "You have successfully added your video(s). Your video(s) should be under the \"Videos Unassigned to Groups\" below. You need to assign your video(s) to a particular course and group.<br/><br/>";
    $msg = $msg . "</p>";
    $_SESSION['message'] = $msg;
    // TODO: refactor the GID / CID fetch code in display form to the top of the page
    // header("location:video_management.php");
    #  header("location: video_management.php?cid=1&gid=1");
    header("location: video_management.php?cid={$CID}&gid={$GID}");
    exit;
}
if (isset($_SESSION['message'])) {
Example #26
0
 function addFlavor($flavorID, $entryID, $codecID, $fileExt)
 {
     $query = "INSERT IGNORE INTO flavors VALUES ('{$flavorID}', '{$entryID}', '{$codecID}', '{$fileExt}', NULL)";
     mysql_query("LOCK TABLES flavors WRITE");
     $result = mysql_query($query, $this->link);
     //print "query: $query<br />";
     if (!$result) {
         writeToLog('Invalid query (addFlavor): ' . mysql_error() . '\\n');
     } else {
         $insertID = mysql_insert_id($this->link);
     }
     mysql_query("UNLOCK TABLES");
     return $insertID;
 }
Example #27
0
<?php

include_once "config.php";
clearSession();
writeToLog('info', 'logout', 'user logged out');
?>
<!DOCTYPE html>
<html manifest="m/mquiz.appcache">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<script type="text/javascript" src="<?php 
echo $CONFIG->homeAddress;
?>
m/includes/lib/jquery-1.7.1.min.js"></script>
	<script type="text/javascript" src="<?php 
echo $CONFIG->homeAddress;
?>
m/includes/mquizengine.js"></script>
	<script type="text/javascript" src="<?php 
echo $CONFIG->homeAddress;
?>
m/includes/mquiz.js"></script>
	<script type="text/javascript" src="<?php 
echo $CONFIG->homeAddress;
?>
includes/script.php"></script>
	<script type="text/javascript">
    	function init(){
        	//initPage();
        	if(mQ.store){
				mQ.store.clear();
Example #28
0
<?php

include_once '../resourcebase.php';
$resource = "action";
writeToLog("METHOD", $_SERVER['REQUEST_METHOD']);
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        $response['action'] = array('Bomb', 'CreateRoom', 'Die', 'EnterRoom', 'Explode', 'GameEnd', 'GameStart', 'GameState', 'GetPid', 'LeaveRoom', 'Move', 'UpdatePlayers', 'UpdateRooms');
        $response["response"] = "success";
        http_response_code(200);
        break;
    case 'POST':
        $response["response"] = "failure";
        http_response_code(403);
        break;
    case 'PUT':
        $response["response"] = "failure";
        http_response_code(403);
        break;
    default:
        $response["response"] = "failure";
        http_response_code(403);
        break;
}
sendResponse();
Example #29
0
	$response = $client ->track($request);

    if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){
		if($response->HighestSeverity != 'SUCCESS'){
			echo '<table border="1">';
			echo '<tr><th>Track Reply</th><th>&nbsp;</th></tr>';
			trackDetails($response->Notifications, '');
			echo '</table>';
		}else{
	    	if ($response->CompletedTrackDetails->HighestSeverity != 'SUCCESS'){
				echo '<table border="1">';
			    echo '<tr><th>Shipment Level Tracking Details</th><th>&nbsp;</th></tr>';
			    trackDetails($response->CompletedTrackDetails, '');
				echo '</table>';
			}else{
				echo '<table border="1">';
			    echo '<tr><th>Package Level Tracking Details</th><th>&nbsp;</th></tr>';
			    trackDetails($response->CompletedTrackDetails->TrackDetails, '');
				echo '</table>';
			}
		}
        printSuccess($client, $response);
    }else{
        printError($client, $response);
    } 
    
    writeToLog($client);    // Write to log file   
} catch (SoapFault $exception) {
    printFault($exception, $client);
}
?>
Example #30
0
 function sendNotification($messageId, $deviceToken, $payload)
 {
     if (strlen($deviceToken) != 64) {
         writeToLog("Message {$messageId} has invalid device token");
         return TRUE;
     }
     if (strlen($payload) < 10) {
         writeToLog("Message {$messageId} has invalid payload");
         return TRUE;
     }
     writeToLog("Sending message {$messageId} to '{$deviceToken}', payload: '{$payload}'");
     if (!$this->fp) {
         writeToLog('No connection to APNS');
         return FALSE;
     }
     // The simple format
     $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
     // the JSON payload
     /*
     // The enhanced notification format
     $msg = chr(1)                       // command (1 byte)
          . pack('N', $messageId)        // identifier (4 bytes)
          . pack('N', time() + 86400)    // expire after 1 day (4 bytes)
          . pack('n', 32)                // token length (2 bytes)
          . pack('H*', $deviceToken)     // device token (32 bytes)
          . pack('n', strlen($payload))  // payload length (2 bytes)
          . $payload;                    // the JSON payload
     */
     $result = @fwrite($this->fp, $msg, strlen($msg));
     if (!$result) {
         writeToLog('Message not delivered');
         return FALSE;
     }
     writeToLog('Message successfully delivered');
     return TRUE;
 }