Example #1
0
function fatalerror()
{
    $last_error = error_get_last();
    if ($last_error['type'] === E_ERROR) {
        write2log(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
    }
}
Example #2
0
 public function handle()
 {
     /**
      * Оглавление
      *
      *  1.
      *
      *
      *  N. Вернуть статус 0
      *
      */
     //--------------------------------------------------------------//
     // Вернуть данные о дате и времени в соответствии с настройками //
     //--------------------------------------------------------------//
     $res = call_user_func(function () {
         try {
             // 1. Проверить, существует ли файл с настройками пакета M3
             if (!file_exists(base_path('config/M3.php'))) {
                 throw new \Exception('Config of package M3 has not been published');
             }
             // 2. Получить настройки из конфига
             $utcoffset = config('M3.utcoffset');
             // 3. Если utcoffset передан, как параметр, использовать его
             if (is_array($this->data) && array_key_exists('utcoffset', $this->data)) {
                 $utcoffset = $this->data['utcoffset'];
             }
             // 4. Провести валидацию $utcoffset
             if (!preg_match("/^(-|)[0-9]+\$/ui", $utcoffset)) {
                 throw new \Exception("The utcoffset value must be + or - number");
             }
             // 5. Привести $utcoffset к строке с плюсом, минусом или нулю
             // - Примеры: '+3', '0', '-3'.
             $utcoffset = call_user_func(function () use($utcoffset) {
                 if (+$utcoffset > 0) {
                     return '+' . (int) $utcoffset;
                 } else {
                     if (+$utcoffset < 0) {
                         return (int) $utcoffset;
                     } else {
                         return '0';
                     }
                 }
             });
             // 6. Создать новый объект Carbon с UTC-смещением $utcoffset
             if (!empty($utcoffset)) {
                 $carbon = \Carbon\Carbon::now($utcoffset);
             } else {
                 $carbon = \Carbon\Carbon::now();
             }
             // 7. Вернуть результат
             return ["status" => 0, "data" => ['carbon' => $carbon, 'utcoffset' => $carbon->offsetHours, 'year' => $carbon->year, 'month' => $carbon->month, 'day' => $carbon->day, 'hour' => $carbon->hour, 'minute' => $carbon->minute, 'second' => $carbon->second]];
         } catch (\Exception $e) {
             $errortext = 'Invoking of command C1_now from M-package M3 have ended with error: ' . $e->getMessage();
             Log::info($errortext);
             write2log($errortext, ['M3', 'C1_now']);
             return ["status" => -2, "data" => $errortext];
         }
     });
     if (!empty($res)) {
         return $res;
     }
     //---------------------//
     // N. Вернуть статус 0 //
     //---------------------//
     return ["status" => 0, "data" => ""];
 }
Example #3
0
function merge_incr_data_from_binlog($cfg, $idx, $datadir, $dt_new, $dt_old, $dt_new_0 = "")
{
    $part = "";
    $partition = "";
    if (isset($cfg['data_sharding_tag'])) {
        $part = "pt={$cfg['data_sharding_tag']}/";
        $partition = ", pt='{$cfg['data_sharding_tag']}'";
    }
    if (!parse_incr_data_from_binlog($cfg, $idx, $datadir, $dt_new, $dt_new_0, $part, $partition)) {
        write2log("parse binlog of {$idx} in {$datadir} failed");
        return false;
    }
    ##MERGE: daily + old ==> new
    $hdfs_daily_dir = $cfg['hdfs_daily_increment_path'] . "/dt={$dt_new}/{$part}";
    $hdfs_snapshot_old_dir = $cfg['hdfs_snapshot_path'] . "/dt={$dt_old}/{$part}";
    $hdfs_snapshot_new_dir = $cfg['hdfs_snapshot_path'] . "/dt={$dt_new}/{$part}";
    $hdfs_php_env_path = $GLOBALS['sync_config']['hdfs_base_dir'] . "/home_php.tgz";
    write2log("hdfs_daily_dir is {$hdfs_daily_dir}\thdfs_snapshot_old_dir is {$hdfs_snapshot_old_dir}\thdfs_snapshot_new_dir is {$hdfs_snapshot_new_dir}");
    exec("sh hive_tool.sh fexist {$hdfs_php_env_path}", $out, $ret);
    if ($ret != 0) {
        if (0 != exec("sh hive_tool.sh fput home_php.tgz {$hdfs_daily_dir}")) {
            write2wflog("Failed: sh hive_tool.sh fput home_php.tgz {$hdfs_daily_dir}");
            return false;
        }
    }
    if (0 != exec("sh hive_tool.sh fmerge {$hdfs_daily_dir} {$hdfs_snapshot_old_dir} {$hdfs_snapshot_new_dir} {$hdfs_php_env_path}")) {
        write2wflog("Failed: sh hive_tool.sh fmerge {$hdfs_daily_dir} {$hdfs_snapshot_old_dir} {$hdfs_snapshot_new_dir}");
        return false;
    } else {
        write2log("Success: merge finish, new snapshot: {$hdfs_snapshot_new_dir}");
    }
    ##HIVE-PARTITION: add new snapshot to hive table partition
    $hql = "ALTER TABLE {$cfg['hive_snapshot_tblname']} ADD PARTITION (dt='{$dt_new}'{$partition}) location '{$hdfs_snapshot_new_dir}'";
    if (0 != exec("sh hive_tool.sh hql \"{$hql}\"")) {
        write2wflog("Failed: add new partition failed, {$hql}");
    } else {
        write2log("Success: add new partition dt='{$dt_new}'{$partition} to {$cfg['hive_snapshot_tblname']}");
    }
    $hql = "ALTER TABLE {$cfg['hive_daily_increment_tblname']} ADD PARTITION (dt='{$dt_new}'{$partition}) location '{$hdfs_daily_dir}'";
    if (0 != exec("sh hive_tool.sh hql \"{$hql}\"")) {
        write2wflog("Failed: add new partition failed, {$hql}");
    } else {
        write2log("Success: add new partition dt='{$dt_new}'{$partition} to {$cfg['hive_daily_increment_tblname']}");
    }
    return true;
}
Example #4
0
 /**
  *
  *  <h1>Пример значения $values</h1>
  *  <pre>
  *    ["id" => 1, "name" => "ivan"]
  *  </pre>
  *  <h1>Пример значения $rules</h1>
  *  <pre>
  *    ["id" => "required|digits|max:255", "name" => "sometimes"]
  *  </pre>
  *  <h1>Стандартные правила валидации</h1>
  *  <pre>
  *    accepted             | The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.
  *    active_url           | The field under validation must be a valid URL according to the checkdnsrr PHP function.
  *    after:date           | The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function.
  *    alpha                | The field under validation must be entirely alphabetic characters.
  *    alpha_dash           | The field under validation may have alpha-numeric characters, as well as dashes and underscores.
  *    alpha_num            | The field under validation must be entirely alpha-numeric characters.
  *    array                | The field under validation must be a PHP array.
  *    before:date          | The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function.
  *    between:min,max      | The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in the same fashion as the size rule.
  *    boolean              | The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".
  *    confirmed            | The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.
  *    date                 | The field under validation must be a valid date according to the strtotime PHP function.
  *    date_format:format   | The field under validation must match the given format. The format will be evaluated using the PHP date_parse_from_format function. You should use either date or date_format when validating a field, not both.
  *    different:field      | The field under validation must have a different value than field.
  *    digits:value         | The field under validation must be numeric and must have an exact length of value.
  *    digits_between::min,max  | The field under validation must have a length between the given min and max.
  *    email                | The field under validation must be formatted as an e-mail address.
  *    exists:table,column  | The field under validation must exist on a given database table. 'state' => 'exists:states,abbreviation'
  *    image                | The file under validation must be an image (jpeg, png, bmp, gif, or svg)
  *    in:foo,bar,...       | The field under validation must be included in the given list of values.
  *    integer              | The field under validation must be an integer.
  *    ip                   | The field under validation must be an IP address.
  *    jSON                 | The field under validation must a valid JSON string.
  *    max:value            | The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.
  *    mimes:foo,bar,...    | The file under validation must have a MIME type corresponding to one of the listed extensions. 'photo' => 'mimes:jpeg,bmp,png'
  *    min:value            | The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.
  *    not_in:foo,bar,...   | The field under validation must not be included in the given list of values.
  *    numeric              | The field under validation must be numeric.
  *    regex:pattern        | The field under validation must match the given regular expression. When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.
  *    required             | The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true: null, empty string, empty array, uploaded file with no path
  *    required_if:anotherfield,value,...      | The field under validation must be present if the anotherfield field is equal to any value.
  *    required_unless:anotherfield,value,...  | The field under validation must be present unless the anotherfield field is equal to any value.
  *    required_with:foo,bar,...               | The field under validation must be present only if any of the other specified fields are present.
  *    required_with_all:foo,bar,...           | The field under validation must be present only if all of the other specified fields are present.
  *    required_without:foo,bar,...            | The field under validation must be present only when any of the other specified fields are not present.
  *    required_without_all:foo,bar,...        | The field under validation must be present only when all of the other specified fields are not present.
  *    same:field           | The given field must match the field under validation.
  *    size:value           | The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For files, size corresponds to the file size in kilobytes.
  *    string               | The field under validation must be a string.
  *    timezone             | The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.
  *    unique:table,column,except,idColumn     | The field under validation must be unique on a given database table. If the column option is not specified, the field name will be used.
  *    url                  | The field under validation must be a valid URL according to PHP's filter_var function.
  *  </pre>
  *  <h1>Избранные стандартные правила валидации</h1>
  *  <pre>
  *    sometimes            | Validate only if that field presents in $values
  *    required             | That field must present in $values
  *    regex:pattern        | Must match regex. Example: regex:/^[DLW]{1}[0-9]+$/ui
  *    numeric              | Must be a number
  *    digits:value         | Must be numeric and must have an exact length of value
  *    in:foo,bar,...       | Must be in list of foo,bar,...
  *    boolean              | Must be: true, false, 1, 0, "1", and "0".
  *    email                | Must be formatted as an e-mail address
  *    max:value            | Must be less than or equal to a maximum value
  *    min:value            | Must be more than or equal to a minimum value
  *    image                | Must be an image (jpeg, png, bmp, gif, or svg)
  *    mimes:foo,bar,...    | Must have a MIME type corresponding to one of the listed
  *  </pre>
  *  <h1>Кастомные правила валидации</h1>
  *  <pre>
  *    r4_numpos            | Must be a positive integer
  *    r4_numnn             | Must be not negative positive integer
  *    r4_defined           | Must be not undefined
  *    r4_true              | must be true (not 1 or '1', only true)
  *    r4_false             | must be false (not 0 or '0', only false)
  *    r4_min:min           | number must be more or equal than min
  *    r4_max:max           | number must be less or equal than max
  *    r4_between:min,max   | number must be between min and max (inclusive)
  *  </pre>
  *
  * @param  string $values
  * @param  array $rules
  *
  * @return mixed
  */
 function r4_validate($values, $rules)
 {
     try {
         // 1. Создать объект-валидатор
         $validator = Validator::make($values, $rules);
         // 2. Если валидация провалилась
         if ($validator->fails()) {
             // Вернуть сериализованный объект с ошибками валидации
             return ["status" => -1, "data" => json_encode($validator->errors(), JSON_UNESCAPED_UNICODE)];
         }
         // 3. Если валидация не провалилась
         return ["status" => 0, "data" => ""];
     } catch (\Exception $e) {
         write2log('Произошёл сбой в хелпере r4_validate: ' . $e->getMessage());
         return ["status" => -1, "data" => $e->getMessage()];
     }
 }
Example #5
0
<td align="left" style="font:9px Verdana;padding-top:2px;color:#737373" colspan="2">
You are receiving this email notification because you have subscribed to Orangescrum, to unsubscribe, please email with subject \'Unsubscribe\' to <a href="mailto:' . SUPPORT_EMAIL . '">' . SUPPORT_EMAIL . '</a>
</td>	  
</tr>
</table>
</td>
</tr>
</table>';
                    //echo $fMessage;die;
                    $mail_res = send_email($mail_id, $sender_name, $subject, $fMessage);
                    if ($mail_res) {
                        $writeLog = 0;
                    }
                }
                if (!$task_posted) {
                    write2log("Add Reply Error<br/><b>To: " . $mail_id . "</b><br/><b>Project: " . $pj_sname . "</b><br/>" . $msg, $message, $mail_id, $header->subject, $header->date);
                }
            }
        }
    }
    //end of for loop
} else {
    //end of if statement
    print 'No unread mail found!';
}
/* close the connection */
imap_close($inbox);
function chnageUploadedFileName($filename)
{
    $output = preg_replace('/[^(\\x20-\\x7F)]*/', '', $filename);
    $rep1 = str_replace("~", "_", $output);
Example #6
0
 public function handle()
 {
     /**
      * Оглавление
      *
      *  1. Полностью очистить pivot-таблицу
      *  2. Полностью очистить таблицу лога
      *  3. Сбросить счётчик автоинкремента
      *
      *  N. Вернуть статус 0
      *
      */
     //------------------------//
     // Полностью очистить лог //
     //------------------------//
     $res = call_user_func(function () {
         try {
             DB::beginTransaction();
             // 1. Полностью очистить pivot-таблицу
             DB::table('m2.md1000')->truncate();
             // 2. Полностью очистить таблицу лога
             \M2\Models\MD1_log::query()->delete();
             // 3. Сбросить счётчик автоинкремента
             DB::statement('ALTER TABLE m2.md1_log AUTO_INCREMENT = 1;');
             DB::commit();
         } catch (\Exception $e) {
             $errortext = 'Invoking of command C3_clear from M-package M2 have ended with error: ' . $e->getMessage();
             DB::rollback();
             Log::info($errortext);
             write2log($errortext, ['M2', 'C3_clear']);
             return ["status" => -2, "data" => $errortext];
         }
     });
     if (!empty($res)) {
         return $res;
     }
     //---------------------//
     // N. Вернуть статус 0 //
     //---------------------//
     return ["status" => 0, "data" => ""];
 }
Example #7
0
 public function handle(\R2\Event $event)
 {
     /**
      * Оглавление
      *
      *  A. Проверить ключи и получить входящие данные
      *
      *  1.
      *  2.
      *
      *  X. Вернуть результат
      *
      */
     //--------------------//
     // A. Проверить ключи //
     //--------------------//
     try {
         // 1.1. Получить ключи, присланные с событием
         $eventkeys = $event->data['keys'];
         // 1.2. Получить ключи, поддерживаемые обработчиком
         $handlerkeys = ["m2:write2log"];
         // 1.3. Если ни один ключ не подходит, завершить
         $testkeys = array_intersect($handlerkeys, $eventkeys);
         if (empty($testkeys)) {
             return;
         }
         // 1.4. Получить входящие данные
         $data = $event->data;
     } catch (\Exception $e) {
         $errortext = 'Keys checking in event handler H1_catch2log of M-package M2 have ended with error: ' . $e->getMessage();
         Log::info($errortext);
         write2log($errortext, ['M1', 'parseapp']);
         return ["status" => -2, "data" => $errortext];
     }
     //---------------------------------------------------//
     // Выполнить команду, добавляющую новую запись в лог //
     //---------------------------------------------------//
     $res = call_user_func(function () use($event) {
         try {
             // 1] Получить сообщение и массив с тегами
             $msg = $event->data['msg'];
             $tags = $event->data['tags'];
             // 2] Сформировать массив аргументов для команды
             $args = ['msg' => $msg, 'tags' => $tags];
             // 3] Выполнить команду, добавляющую новую запись в лог
             runcommand('\\M2\\Commands\\C1_write2log', $args);
         } catch (\Exception $e) {
             $errortext = 'Invoking of event handler H1_catch2log of M-package M2 have ended with error: ' . $e->getMessage();
             Log::info($errortext);
             return ["status" => -2, "data" => $errortext];
         }
     });
     if (!empty($res)) {
         return $res;
     }
     //----------------------//
     // X. Вернуть результат //
     //----------------------//
     return ["status" => 0, "data" => ""];
 }
Example #8
0
 public function handle()
 {
     /**
      * Оглавление
      *
      *  1. Проверить, существует ли файл с настройками пакета M2
      *  2. Получить настройки ограничений из конфига
      *  3. Провести валидацию настроек ограничений
      *
      *  N. Вернуть статус 0
      *
      */
     //-----------------------------------------------------------------------------//
     // Применить заданные в настройках ограничения на объем хранимых в логе данных //
     //-----------------------------------------------------------------------------//
     $res = call_user_func(function () {
         try {
             DB::beginTransaction();
             // 1. Проверить, существует ли файл с настройками пакета M2
             if (!file_exists(base_path('config/M2.php'))) {
                 throw new \Exception('Config of package M2 has not been published');
             }
             // 2. Получить настройки ограничений из конфига
             $limit_type = config('M2.limit_type');
             $limit_max_storetime_days = config('M2.limit_max_storetime_days');
             $limit_max_count = config('M2.limit_max_count');
             // 3. Провести валидацию настроек ограничений
             // 3.1. $limit_type
             if (!preg_match("/^[123]{1}\$/ui", $limit_type)) {
                 throw new \Exception("Limit type value must be 1, 2 or 3");
             }
             // 3.2. $limit_max_storetime_days
             if (!preg_match("/^[0-9]+\$/ui", $limit_max_storetime_days)) {
                 throw new \Exception("The time limit must be a number");
             }
             if ($limit_max_storetime_days >= 1825) {
                 throw new \Exception("The time limit must be equal or less than 1825 (5 years)");
             }
             // 3.3. $limit_max_count
             if (!preg_match("/^[0-9]+\$/ui", $limit_max_count)) {
                 throw new \Exception("The count limit must be a number");
             }
             if ($limit_max_count <= 1825) {
                 throw new \Exception("The count limit must be equal or less than 1000000 of records");
             }
             // 3.4. Если выбран тип лимитирования №1
             // - По времени, и по количеству записей
             if ($limit_type == 1) {
                 // 1] Удалить из лога все записи старше $limit_max_storetime_days дней
                 // - Перебирать записи лога кусками по 500 штук, и делать дело.
                 \M2\Models\MD1_log::chunk(500, function ($lognotes) use($limit_max_storetime_days) {
                     foreach ($lognotes as $note) {
                         if (+((time() - strtotime($note->created_at)) / 60 / 60) > +$limit_max_storetime_days) {
                             // Удалить все связи записи $note с тегами из pivot-таблицы
                             $note->tags()->detach();
                             // Удалить $note из Бд
                             $note->delete();
                         }
                     }
                 });
                 // 2] Удалить из начала лога (самые старые) все записи, свыше $limit_max_count штук
                 // - Перебирать записи лога кусками по 500 штук, и делать дело.
                 if (+\M2\Models\MD1_log::count() > +$limit_max_count) {
                     // 2.1] Определить кол-во элементов, которые требуется удалить
                     $count2del = +\M2\Models\MD1_log::count() - +$limit_max_count;
                     // 2.2] Удалить из лога $count2del самых старых записей
                     // Получить коллекцию записей, которые требуется удалить
                     $notes2del = \M2\Models\MD1_log::orderBy('created_at')->take($count2del)->get();
                     // Пробежатсья по $notes2del
                     foreach ($notes2del as $note) {
                         // Удалить все связи записи $note с тегами из pivot-таблицы
                         $note->tags()->detach();
                         // Удалить $note из Бд
                         $note->delete();
                     }
                 }
             }
             // 3.5. Если выбран тип лимитирования №2
             // - По времени
             if ($limit_type == 2) {
                 // 1] Удалить из лога все записи старше $limit_max_storetime_days дней
                 // - Перебирать записи лога кусками по 500 штук, и делать дело.
                 \M2\Models\MD1_log::chunk(500, function ($lognotes) use($limit_max_storetime_days) {
                     foreach ($lognotes as $note) {
                         if (+((time() - strtotime($note->created_at)) / 60 / 60) > +$limit_max_storetime_days) {
                             // Удалить все связи записи $note с тегами из pivot-таблицы
                             $note->tags()->detach();
                             // Удалить $note из Бд
                             $note->delete();
                         }
                     }
                 });
             }
             // 3.6. Если выбран тип лимитирования №3
             // - По количеству записей
             if ($limit_type == 3) {
                 // 1] Удалить из начала лога (самые старые) все записи, свыше $limit_max_count штук
                 // - Перебирать записи лога кусками по 500 штук, и делать дело.
                 if (+\M2\Models\MD1_log::count() > +$limit_max_count) {
                     // 1.1] Определить кол-во элементов, которые требуется удалить
                     $count2del = +\M2\Models\MD1_log::count() - +$limit_max_count;
                     // 1.2] Удалить из лога $count2del самых старых записей
                     // Получить коллекцию записей, которые требуется удалить
                     $notes2del = \M2\Models\MD1_log::orderBy('created_at')->take($count2del)->get();
                     // Пробежатсья по $notes2del
                     foreach ($notes2del as $note) {
                         // Удалить все связи записи $note с тегами из pivot-таблицы
                         $note->tags()->detach();
                         // Удалить $note из Бд
                         $note->delete();
                     }
                 }
             }
             DB::commit();
         } catch (\Exception $e) {
             $errortext = 'Invoking of command C2_limitator from M-package M2 have ended with error: ' . $e->getMessage();
             DB::rollback();
             Log::info($errortext);
             write2log($errortext, ['C2_limitator']);
             return ["status" => -2, "data" => $errortext];
         }
     });
     if (!empty($res)) {
         return $res;
     }
     //---------------------//
     // N. Вернуть статус 0 //
     //---------------------//
     return ["status" => 0, "data" => ""];
 }
Example #9
0
 /**
  *  <h1>Описание</h1>
  *  <pre>
  *    Получить контрольную сумму для файла или каталога по заданному path
  *    Возвращает: контрольную сумму
  *  </pre>
  *  <h1>Пример использования</h1>
  *  <pre>
  *    $path       = "/c/some/dir";
  *    $checksum   = r1_checksum($path);
  *  </pre>
  *
  * @param  string $path
  *
  * @return mixed
  */
 function r1_checksum($path)
 {
     try {
         // 1. Если по адресу $path нет ни файла, ни папки, вернуть пустую строку
         if (!file_exists($path)) {
             return "";
         }
         // 2. Если по адресу $path находится файл, вернуть его md5-хэш
         if (is_file($path)) {
             return md5_file($path);
         }
         // 3. Если по адресу $path находится каталог, вернуть сумму хэшей его файлов
         $md5_dir = function ($path) use(&$md5_dir) {
             $filemd5s = array();
             $d = dir($path);
             while (false !== ($entry = $d->read())) {
                 if ($entry != '.' && $entry != '..') {
                     if (is_dir($path . '/' . $entry)) {
                         $filemd5s[] = $md5_dir($path . '/' . $entry);
                     } else {
                         $filemd5s[] = md5_file($path . '/' . $entry);
                     }
                 }
             }
             $d->close();
             return md5(implode('', $filemd5s));
         };
         return $md5_dir($path);
     } catch (\Exception $e) {
         write2log('Ошибка в хелпере r1_checksum: ' . $e->getMessage(), ['r1_checksum']);
     }
 }
Example #10
0
function parse_binlog_rows($binlog_file, $cfg, $out_file)
{
    write2log("parse {$binlog_file}");
    $fd = fopen($binlog_file, "r");
    $unix_time_update = 0;
    $db_name = $cfg['dbname'];
    $tbl_name = $cfg['tblname'];
    $dbtbl_parttern = $cfg['db_tbl_pattern'];
    $hive_keys = $cfg['hive_item_key'];
    $tbl_pattern = preg_replace("/\\%d/", "\\d+", $dbtbl_parttern);
    $_pattern = sprintf($tbl_pattern, $db_name, $tbl_name);
    while (!feof($fd)) {
        $line = "";
        $line = fgets($fd);
        if (empty($line)) {
            break;
        }
        while (!feof($fd) && preg_match("/^### /", $line, $matches)) {
            if (preg_match("/^### (UPDATE|INSERT INTO) ({$_pattern})\$/", $line, $matches)) {
                $set_flag = false;
                $hive_item_key = trim($matches[2]);
                $db_tbl_str = trim($matches[2]);
                while (!feof($fd)) {
                    $line = fgets($fd);
                    if (preg_match("/^### SET\$/", $line, $matches)) {
                        $set_flag = true;
                        break;
                    }
                    if (!preg_match("/^### /", $line, $matches)) {
                        break;
                    }
                }
                $out_line = "{$unix_time_update}" . 0;
                while ($set_flag && !feof($fd)) {
                    $line = fgets($fd);
                    if (preg_match("/^###   @(\\d+)=(.*)\$/", $line, $matches)) {
                        if (array_key_exists(intval($matches[1]), $hive_keys)) {
                            $hive_item_key = $hive_item_key . "" . $matches[2];
                        }
                        $attr = table_column_callback($db_tbl_str, $db_name, $tbl_name, $matches[2], $matches[1]);
                        $out_line = $out_line . "" . $attr;
                    } else {
                        break;
                    }
                }
                $out_line = "{$hive_item_key}" . $out_line;
                list($part_db_name, $part_tbl_name) = explode(".", $db_tbl_str, 2);
                if ($cfg['db_partitions'] > 1) {
                    $out_line = $out_line . "" . $part_db_name;
                } else {
                    if ($cfg['tbl_partitions'] > 1) {
                        $out_line = $out_line . "" . $part_tbl_name;
                    }
                }
                $out_line = table_row_callback($db_name, $tbl_name, $out_line, "UPINS");
                if (!empty($out_line)) {
                    file_put_contents($out_file, $out_line . "\n", FILE_APPEND | LOCK_EX);
                }
            } else {
                if (preg_match("/^### (DELETE FROM) ({$_pattern})\$/", $line, $matches)) {
                    $set_flag = false;
                    $hive_item_key = trim($matches[2]);
                    $db_tbl_str = trim($matches[2]);
                    while (!feof($fd)) {
                        $line = fgets($fd);
                        if (preg_match("/^### WHERE\$/", $line, $matches)) {
                            $set_flag = true;
                            break;
                        }
                        if (!preg_match("/^### /", $line, $matches)) {
                            break;
                        }
                    }
                    $out_line = "{$unix_time_update}" . 1;
                    while ($set_flag && !feof($fd)) {
                        $line = fgets($fd);
                        if (preg_match("/^###   @(\\d+)=(.*)\$/", $line, $matches)) {
                            if (array_key_exists(intval($matches[1]), $hive_keys)) {
                                $hive_item_key = $hive_item_key . "" . $matches[2];
                            }
                            $attr = table_column_callback($db_tbl_str, $db_name, $tbl_name, $matches[2], $matches[1]);
                            $out_line = $out_line . "" . $attr;
                        } else {
                            break;
                        }
                    }
                    $out_line = "{$hive_item_key}" . $out_line;
                    $out_line = table_row_callback($db_name, $tbl_name, $out_line, "DEL");
                    if (!empty($out_line)) {
                        file_put_contents($out_file, $out_line . "\n", FILE_APPEND | LOCK_EX);
                    }
                }
            }
            $line = "";
            $line = fgets($fd);
            if (empty($line)) {
                break;
            }
        }
        if (preg_match("/^#(\\d\\d\\d\\d\\d\\d ( |\\d)\\d:\\d\\d:\\d\\d).*end_log_pos (\\d+)/", $line, $matches)) {
            $unix_time_update = str2time($matches[1]) . $matches[3];
        }
    }
    fclose($fd);
    write2log("parse {$binlog_file} finish");
    return $out_file;
}
Example #11
0
function sslCheck()
{
    if (isset($_SERVER['OPENSSL_CONF']) && preg_match('~SSL~', $_SERVER['SERVER_SOFTWARE'])) {
        write2log('Seems SSL is available, try to open a socket');
        try {
            $SSL_Check = @fsockopen("ssl://" . $_SERVER['HTTP_HOST'], 443, $errno, $errstr, 30);
            if (!$SSL_Check) {
                write2log(sprintf('fsockopen failed, SSL not available for [%s]', $_SERVER['HTTP_HOST']));
                return false;
            } else {
                write2log(sprintf('fsockopen succeeded, SSL seems to be available for [%s]', $_SERVER['HTTP_HOST']));
                fclose($SSL_Check);
                return true;
            }
        } catch (Exception $e) {
            write2log(sprintf('exception caught: %s', $e->getMessage()));
            return false;
        }
    } else {
        write2log('No SSL in $_SERVER array');
        return false;
    }
}