Example #1
2
/**
 * utf8::str_pad
 *
 * @package    Core
 * @author     Kohana Team
 * @copyright  (c) 2007 Kohana Team
 * @copyright  (c) 2005 Harry Fuecks
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
 */
function _str_pad($str, $final_str_length, $pad_str = ' ', $pad_type = STR_PAD_RIGHT)
{
    if (utf8::is_ascii($str) and utf8::is_ascii($pad_str)) {
        return str_pad($str, $final_str_length, $pad_str, $pad_type);
    }
    $str_length = utf8::strlen($str);
    if ($final_str_length <= 0 or $final_str_length <= $str_length) {
        return $str;
    }
    $pad_str_length = utf8::strlen($pad_str);
    $pad_length = $final_str_length - $str_length;
    if ($pad_type == STR_PAD_RIGHT) {
        $repeat = ceil($pad_length / $pad_str_length);
        return utf8::substr($str . str_repeat($pad_str, $repeat), 0, $final_str_length);
    }
    if ($pad_type == STR_PAD_LEFT) {
        $repeat = ceil($pad_length / $pad_str_length);
        return utf8::substr(str_repeat($pad_str, $repeat), 0, floor($pad_length)) . $str;
    }
    if ($pad_type == STR_PAD_BOTH) {
        $pad_length /= 2;
        $pad_length_left = floor($pad_length);
        $pad_length_right = ceil($pad_length);
        $repeat_left = ceil($pad_length_left / $pad_str_length);
        $repeat_right = ceil($pad_length_right / $pad_str_length);
        $pad_left = utf8::substr(str_repeat($pad_str, $repeat_left), 0, $pad_length_left);
        $pad_right = utf8::substr(str_repeat($pad_str, $repeat_right), 0, $pad_length_left);
        return $pad_left . $str . $pad_right;
    }
    trigger_error('utf8::str_pad: Unknown padding type (' . $type . ')', E_USER_ERROR);
}
Example #2
1
 public static function createSymbolicLink($rootDir = null)
 {
     IS_MULTI_MODULES || exit('please set is_multi_modules => true');
     $deper = Request::isCli() ? PHP_EOL : '<br />';
     echo "{$deper}**************************create link start!*********************{$deper}";
     echo '|' . str_pad('', 64, ' ', STR_PAD_BOTH) . '|';
     is_null($rootDir) && ($rootDir = ROOT_PATH . DIRECTORY_SEPARATOR . 'web');
     is_dir($rootDir) || mkdir($rootDir, true, 0700);
     //modules_static_path_name
     // 递归遍历目录
     $dirIterator = new \DirectoryIterator(APP_MODULES_PATH);
     foreach ($dirIterator as $file) {
         if (!$file->isDot() && $file->isDir()) {
             $resourceDir = $file->getPathName() . DIRECTORY_SEPARATOR . Config::get('modules_static_path_name');
             if (is_dir($resourceDir)) {
                 $distDir = ROOT_PATH . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . $file->getFilename();
                 $cmd = Request::operatingSystem() ? "mklink /d {$distDir} {$resourceDir}" : "ln -s {$resourceDir} {$distDir}";
                 exec($cmd, $result);
                 $tip = "create link Application [{$file->getFilename()}] result : [" . (is_dir($distDir) ? 'true' : 'false') . "]";
                 $tip = str_pad($tip, 64, ' ', STR_PAD_BOTH);
                 print_r($deper . '|' . $tip . '|');
             }
         }
     }
     echo $deper . '|' . str_pad('', 64, ' ', STR_PAD_BOTH) . '|';
     echo "{$deper}****************************create link end!**********************{$deper}";
 }
 public function setUp()
 {
     parent::setUp();
     $webapp = Webapp::getInstance();
     $webapp->registerPlugin('flickr', 'ExpandURLsPlugin');
     //Add owner
     $q = "INSERT INTO tu_owners SET id=1, full_name='ThinkUp J. User', email='*****@*****.**',\n        is_activated=1, pwd='XXX', activation_code='8888'";
     $this->testdb_helper->runSQL($q);
     //Add instance_owner
     $q = "INSERT INTO tu_owner_instances (owner_id, instance_id) VALUES (1, 1)";
     $this->testdb_helper->runSQL($q);
     //Insert test data into test table
     $q = "INSERT INTO tu_users (user_id, user_name, full_name, avatar, last_updated) VALUES (13, 'ev',\n        'Ev Williams', 'avatar.jpg', '1/1/2005');";
     $this->testdb_helper->runSQL($q);
     //Make public
     $q = "INSERT INTO tu_instances (id, network_user_id, network_username, is_public) VALUES (1, 13, 'ev', 1);";
     $this->testdb_helper->runSQL($q);
     //Add a bunch of posts
     $counter = 0;
     while ($counter < 40) {
         $pseudo_minute = str_pad($counter, 2, "0", STR_PAD_LEFT);
         $q = "INSERT INTO tu_posts (post_id, author_user_id, author_username, author_fullname, author_avatar,\n            post_text, source, pub_date, reply_count_cache, retweet_count_cache) VALUES ({$counter}, 13, 'ev', \n            'Ev Williams', 'avatar.jpg', 'This is post {$counter}', 'web', '2006-01-01 00:{$pseudo_minute}:00', " . rand(0, 4) . ", 5);";
         $this->testdb_helper->runSQL($q);
         $counter++;
     }
 }
Example #4
0
/**
* Takes xml as a string and returns it nicely indented
*
* @param string $xml The xml to beautify
* @param boolean $html_output If the xml should be formatted for display on an html page
* @return string The beautified xml
*/
function xml_pretty_printer($xml, $html_output = FALSE)
{
    $xml_obj = new SimpleXMLElement($xml);
    $xml_lines = explode("n", $xml_obj->asXML());
    $indent_level = 0;
    $new_xml_lines = array();
    foreach ($xml_lines as $xml_line) {
        if (preg_match('#(<[a-z0-9:-]+((s+[a-z0-9:-]+="[^"]+")*)?>.*<s*/s*[^>]+>)|(<[a-z0-9:-]+((s+[a-z0-9:-]+="[^"]+")*)?s*/s*>)#i', $xml_line)) {
            $new_line = str_pad('', $indent_level * 4) . $xml_line;
            $new_xml_lines[] = $new_line;
        } elseif (preg_match('#<[a-z0-9:-]+((s+[a-z0-9:-]+="[^"]+")*)?>#i', $xml_line)) {
            $new_line = str_pad('', $indent_level * 4) . $xml_line;
            $indent_level++;
            $new_xml_lines[] = $new_line;
        } elseif (preg_match('#<s*/s*[^>/]+>#i', $xml_line)) {
            $indent_level--;
            if (trim($new_xml_lines[sizeof($new_xml_lines) - 1]) == trim(str_replace("/", "", $xml_line))) {
                $new_xml_lines[sizeof($new_xml_lines) - 1] .= $xml_line;
            } else {
                $new_line = str_pad('', $indent_level * 4) . $xml_line;
                $new_xml_lines[] = $new_line;
            }
        } else {
            $new_line = str_pad('', $indent_level * 4) . $xml_line;
            $new_xml_lines[] = $new_line;
        }
    }
    $xml = join("n", $new_xml_lines);
    return $html_output ? '<pre>' . htmlentities($xml) . '</pre>' : $xml;
}
Example #5
0
 /**
  * create an auction id out of the shard and row id.
  */
 public static function composeId($shard, $row_id)
 {
     if (strlen($shard) != 6 || !ctype_digit(strval($shard)) || !ctype_digit(strval($row_id))) {
         return NULL;
     }
     return $shard . str_pad($row_id, 11, '0', STR_PAD_LEFT);
 }
 /**
  * List download stats.
  *
  * @param bool|false $Offset
  */
 public function index($Offset = false)
 {
     $this->permission('Garden.Settings.Manage');
     $this->addSideMenu('vstats');
     $this->addJsFile('jquery.gardenmorepager.js');
     $this->title('Vanilla Stats');
     $this->Form->Method = 'get';
     $Offset = is_numeric($Offset) ? $Offset : 0;
     $Limit = 19;
     $this->StatsData = array();
     $Offset--;
     $Year = date('Y');
     $Month = date('m');
     $BaseDate = Gdn_Format::toTimestamp($Year . '-' . str_pad($Month, 2, '0', STR_PAD_LEFT) . '-01 00:00:00');
     for ($i = $Offset; $i <= $Limit; ++$i) {
         $String = "-{$i} month";
         $this->StatsData[] = $this->_getStats(date("Y-m-d 00:00:00", strtotime($String, $BaseDate)));
     }
     $TotalRecords = count($this->StatsData);
     // Build a pager
     $PagerFactory = new Gdn_PagerFactory();
     $this->Pager = $PagerFactory->getPager('MorePager', $this);
     $this->Pager->MoreCode = 'More';
     $this->Pager->LessCode = 'Previous';
     $this->Pager->ClientID = 'Pager';
     $this->Pager->Wrapper = '<tr %1$s><td colspan="6">%2$s</td></tr>';
     $this->Pager->configure($Offset, $Limit, $TotalRecords, 'vstats/index/%1$s/');
     // Deliver json data if necessary
     if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
         $this->setJson('LessRow', $this->Pager->toString('less'));
         $this->setJson('MoreRow', $this->Pager->toString('more'));
     }
     $this->render();
 }
Example #7
0
 public function configure()
 {
     $status = array('Enabled' => __('Enabled'), 'Disabled' => __('Disabled'));
     $idGenService = new IDGeneratorService();
     $idGenService->setEntity(new Employee());
     $empNumber = $idGenService->getNextID(false);
     $employeeId = str_pad($empNumber, 4, '0');
     $this->widgets = array('firstName' => new sfWidgetFormInputText(array(), array("class" => "formInputText", "maxlength" => 30)), 'middleName' => new sfWidgetFormInputText(array(), array("class" => "formInputText", "maxlength" => 30)), 'lastName' => new sfWidgetFormInputText(array(), array("class" => "formInputText", "maxlength" => 30)), 'empty' => new ohrmWidgetDiv(), 'fullNameLabel' => new ohrmWidgetDiv(), 'firstNameLabel' => new ohrmWidgetDiv(), 'middleNameLabel' => new ohrmWidgetDiv(), 'lastNameLabel' => new ohrmWidgetDiv(), 'employeeId' => new sfWidgetFormInputText(array(), array("class" => "formInputText", "maxlength" => 10, "colspan" => 3)), 'photofile' => new sfWidgetFormInputFileEditable(array('edit_mode' => false, 'with_delete' => false, 'file_src' => ''), array("class" => "duplexBox", "colspan" => 3)), 'chkLogin' => new sfWidgetFormInputCheckbox(array('value_attribute_value' => 1), array("style" => "vertical-align:top", "colspan" => 3)), 'lineSeperator' => new ohrmWidgetDiv(array(), array("colspan" => 3)), 'user_name' => new sfWidgetFormInputText(array(), array("class" => "formInputText", "maxlength" => 20)), 'status' => new sfWidgetFormSelect(array('choices' => $status), array("class" => "formInputText", "br" => true)), 'user_password' => new sfWidgetFormInputPassword(array(), array("class" => "formInputText passwordRequired", "maxlength" => 20)), 're_password' => new sfWidgetFormInputPassword(array(), array("class" => "formInputText passwordRequired", "maxlength" => 20, "br" => true)), 'empNumber' => new sfWidgetFormInputHidden());
     $this->widgets['empNumber']->setDefault($empNumber);
     $this->widgets['employeeId']->setDefault($employeeId);
     if ($this->getOption('employeeId') != "") {
         $this->widgets['employeeId']->setDefault($this->getOption('employeeId'));
     }
     $this->widgets['firstName']->setDefault($this->getOption('firstName'));
     $this->widgets['middleName']->setDefault($this->getOption('middleName'));
     $this->widgets['lastName']->setDefault($this->getOption('lastName'));
     $this->widgets['chkLogin']->setDefault($this->getOption('chkLogin'));
     $this->widgets['user_name']->setDefault($this->getOption('user_name'));
     $this->widgets['user_password']->setDefault($this->getOption('user_password'));
     $this->widgets['re_password']->setDefault($this->getOption('re_password'));
     $this->widgets['status']->setDefault($this->getOption('status'));
     $this->setWidgets($this->widgets);
     $this->setValidators(array('photofile' => new sfValidatorFile(array('max_size' => 1000000, 'required' => false)), 'firstName' => new sfValidatorString(array('required' => true, 'max_length' => 30, 'trim' => true)), 'empNumber' => new sfValidatorString(array('required' => false)), 'lastName' => new sfValidatorString(array('required' => true, 'max_length' => 30, 'trim' => true)), 'middleName' => new sfValidatorString(array('required' => false, 'max_length' => 30, 'trim' => true)), 'employeeId' => new sfValidatorString(array('required' => false, 'max_length' => 10)), 'chkLogin' => new sfValidatorString(array('required' => false)), 'user_name' => new sfValidatorString(array('required' => false, 'max_length' => 20, 'trim' => true)), 'user_password' => new sfValidatorString(array('required' => false, 'max_length' => 20, 'trim' => true)), 're_password' => new sfValidatorString(array('required' => false, 'max_length' => 20, 'trim' => true)), 'status' => new sfValidatorString(array('required' => false))));
     $this->getWidgetSchema()->setLabels($this->getFormLabels());
     sfWidgetFormSchemaFormatterAddEmployee::setNoOfColumns(4);
     //merge location dropdown
     $formExtension = PluginFormMergeManager::instance();
     $formExtension->mergeForms($this, 'addEmployee', 'AddEmployeeForm');
     $this->widgetSchema->setFormFormatterName('AddEmployee');
 }
 /**
  * Currently, PHP date() function always returns zeros for milliseconds (u)
  * on Windows. This is a replacement function for date() which correctly 
  * displays milliseconds on all platforms. 
  * 
  * It is slower than PHP date() so it should only be used if necessary. 
  */
 private function date($format, $utimestamp)
 {
     $timestamp = floor($utimestamp);
     $ms = floor(($utimestamp - $timestamp) * 1000);
     $ms = str_pad($ms, 3, '0', STR_PAD_LEFT);
     return date(preg_replace('`(?<!\\\\)u`', $ms, $format), $timestamp);
 }
Example #9
0
 /**
  * Gets the interesting lines in the interesting file
  */
 public function getSource($nbLine = 6)
 {
     if (!is_file($this->file)) {
         return;
     }
     $file = fopen($this->file, 'r');
     $beginLine = max(0, $this->line - $nbLine / 2);
     $endLine = $beginLine + $nbLine - 1;
     $code = '';
     $curLine = 0;
     while ($line = fgets($file)) {
         $curLine++;
         if ($this->line == $curLine) {
             $lineLabel = 'ERR:';
         } else {
             $lineLabel = str_pad($curLine, 3, '0', STR_PAD_LEFT) . ':';
         }
         if ($curLine >= $beginLine && $curLine <= $endLine) {
             $code .= $lineLabel . $line;
         }
         if ($curLine > $endLine) {
             break;
         }
     }
     if (!preg_match('/^\\<\\?php/', ltrim($code))) {
         $code = "<?php\n" . $code;
     }
     return $code;
 }
Example #10
0
 public static function mask($str, $padStr = '*', $show = 6, $pad = 10)
 {
     if (strlen($str) >= $show) {
         $str = substr($str, 0, $show);
     }
     return self::out(str_pad($str, $pad, $padStr));
 }
Example #11
0
 /**
  * Write a data structure to an INI-formatted string or file.
  * Adds "secure" comments to the start and end of the data so
  * you can hide your INI data in files using a .php extension.
  */
 public static function write($data, $file = false)
 {
     $out = "; <?php /*\n";
     $write_value = function ($value) {
         if (is_bool($value)) {
             return $value ? 'On' : 'Off';
         } elseif ($value === '0' || $value === '') {
             return 'Off';
         } elseif ($value === '1') {
             return 'On';
         } elseif (preg_match('/[^a-z0-9\\/\\.@<> _-]/i', $value)) {
             return '"' . str_replace('"', '\\"', $value) . '"';
         }
         return $value;
     };
     $sections = is_array($data[current(array_keys($data))]) ? true : false;
     if (!$sections) {
         $out .= "\n";
     }
     foreach ($data as $key => $value) {
         if (is_array($value)) {
             $out .= "\n[{$key}]\n\n";
             foreach ($value as $k => $v) {
                 $out .= str_pad($k, 24) . '= ' . $write_value($v) . "\n";
             }
         } else {
             $out .= str_pad($key, 24) . '= ' . $write_value($value) . "\n";
         }
     }
     $out .= "\n; */ ?>";
     if ($file === false) {
         return $out;
     }
     return file_put_contents($file, $out);
 }
Example #12
0
 function add_coupon_sub()
 {
     $_POST = $this->zaddslashes($_POST);
     //如果是插入多条优惠码则执行以下
     if (!empty($_POST['num'])) {
         $number = date('mds') . str_pad(mt_rand(1, 999999), 7, '0', STR_PAD_LEFT);
         //循环加入变量多条数据
         for ($i = 0; $i < $_POST['num']; $i++) {
             $data[$i]['name'] = $_POST['name'];
             $data[$i]['coupon_code'] = 'Kshop' . mt_rand(0, 999) . $number . mt_rand(0, 999);
             $data[$i]['discount'] = $_POST['discount'];
             $data[$i]['validity_date'] = strtotime($_POST['validity_date']);
             $data[$i]['status'] = $_POST['status'];
         }
         //循环插入多条数据
         for ($i = 0; $i < count($data); $i++) {
             $i == count($data) - 1 ? $success = 1 : ($success = 0);
             $this->couponModel->getAddCouponDataStatus($data[$i]);
         }
         if ($success == 1) {
             $this->success('添加优惠码成功!');
         } else {
             $this->error('添加优惠码失败!');
         }
     } else {
         //如果是执行单条优惠码则执行以下
         $_POST['validity_date'] = strtotime($_POST['validity_date']);
         if ($this->couponModel->getAddCouponDataStatus($_POST)) {
             $this->success('添加优惠码成功');
         } else {
             $this->error('添加优惠码失败');
         }
     }
 }
 public function Geohash()
 {
     //build map from encoding char to 0 padded bitfield
     for ($i = 0; $i < 32; $i++) {
         $this->codingMap[substr($this->coding, $i, 1)] = str_pad(decbin($i), 5, "0", STR_PAD_LEFT);
     }
 }
 private function parse_identifier_format($identifier_format, $next_id, $left_pad)
 {
     if (preg_match_all('/{{{([^{|}]*)}}}/', $identifier_format, $template_vars)) {
         foreach ($template_vars[1] as $var) {
             switch ($var) {
                 case 'year':
                     $replace = date('Y');
                     break;
                 case 'month':
                     $replace = date('m');
                     break;
                 case 'day':
                     $replace = date('d');
                     break;
                 case 'id':
                     $replace = str_pad($next_id, $left_pad, '0', STR_PAD_LEFT);
                     break;
                 default:
                     $replace = '';
             }
             $identifier_format = str_replace('{{{' . $var . '}}}', $replace, $identifier_format);
         }
     }
     return $identifier_format;
 }
Example #15
0
 public static function error($message, $class = "N/A", $method = "N/A")
 {
     if (LOG_LEVEL == "ERROR") {
         Utilities::checkSize(LOG_FOLDER . "debug.log");
         error_log("/r/n[ERROR] " . date("Y-m-d h:i:s") . " - [" . str_pad($class, 20, " ") . "] - [" . str_pad($method, 20, " ") . "] - " . $message . "", 3, LOG_FOLDER . "error.log");
     }
 }
Example #16
0
 /**
  * Pretty-print a listing of the routes connected to the mapper.
  *
  * @param  stream|null  $stream  Output stream for printing (optional)
  * @param  string|null  $eol     Line ending (optional)
  * @return void
  */
 public function printRoutes($stream = null, $eol = PHP_EOL)
 {
     $routes = $this->getRoutes();
     if (empty($routes)) {
         return;
     }
     if ($stream === null) {
         $stream = fopen('php://output', 'a');
     }
     // find the max $widths to size the output columns {'name'=>40, 'method'=>6, ...}
     $widths = array();
     foreach (array_keys($routes[0]) as $key) {
         $width = 0;
         foreach ($routes as $r) {
             $l = strlen($r[$key]);
             if ($l > $width) {
                 $width = $l;
             }
         }
         $widths[$key] = $width;
     }
     // print the output
     foreach ($routes as $r) {
         fwrite($stream, str_pad($r['name'], $widths['name'], ' ', STR_PAD_LEFT) . ' ');
         fwrite($stream, str_pad($r['method'], $widths['method'], ' ', STR_PAD_RIGHT) . ' ');
         fwrite($stream, str_pad($r['path'], $widths['path'], ' ', STR_PAD_RIGHT) . ' ');
         fwrite($stream, $r['hardcodes'] . $eol);
     }
 }
Example #17
0
 public static function decode($input)
 {
     if (empty($input)) {
         return;
     }
     $paddingCharCount = substr_count($input, self::$map[32]);
     $allowedValues = array(6, 4, 3, 1, 0);
     if (!in_array($paddingCharCount, $allowedValues)) {
         return false;
     }
     for ($i = 0; $i < 4; $i++) {
         if ($paddingCharCount == $allowedValues[$i] && substr($input, -$allowedValues[$i]) != str_repeat(self::$map[32], $allowedValues[$i])) {
             return false;
         }
     }
     $input = str_replace('=', '', $input);
     $input = str_split($input);
     $binaryString = "";
     for ($i = 0; $i < count($input); $i = $i + 8) {
         $x = "";
         if (!in_array($input[$i], self::$map)) {
             return false;
         }
         for ($j = 0; $j < 8; $j++) {
             $x .= str_pad(base_convert(@self::$flippedMap[@$input[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
         }
         $eightBits = str_split($x, 8);
         for ($z = 0; $z < count($eightBits); $z++) {
             $binaryString .= ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ? $y : "";
         }
     }
     return $binaryString;
 }
Example #18
0
 public function getNextId()
 {
     $lastId = $this->getLastId();
     if (strpos($lastId, $this->getPrefix()) === 0) {
         $lastId = substr($lastId, strlen($this->getPrefix()));
     }
     $lastId = str_pad((string) $lastId, $this->getPadLength(), $this->getPadChar(), STR_PAD_LEFT);
     $nextId = '';
     $bumpNextChar = true;
     $chars = $this->getAllowedChars();
     $lchars = strlen($chars);
     $lid = strlen($lastId) - 1;
     for ($i = $lid; $i >= 0; $i--) {
         $p = strpos($chars, $lastId[$i]);
         if (false === $p) {
             throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Invalid character encountered in increment ID: %s', $lastId));
         }
         if ($bumpNextChar) {
             $p++;
             $bumpNextChar = false;
         }
         if ($p === $lchars) {
             $p = 0;
             $bumpNextChar = true;
         }
         $nextId = $chars[$p] . $nextId;
     }
     return $this->format($nextId);
 }
function comcon_meta_save()
{
    global $post;
    $post_id = $post->ID;
    if (!isset($_POST['comcon-form-nonce']) || !wp_verify_nonce($_POST['comcon-form-nonce'], basename(__FILE__))) {
        return $post->ID;
    }
    $post_type = get_post_type_object($post->post_type);
    if (!current_user_can($post_type->cap->edit_post, $post_id)) {
        return $post->ID;
    }
    $input = array();
    $input['position'] = isset($_POST['comcon-form-position']) ? $_POST['comcon-form-position'] : '';
    $input['major'] = isset($_POST['comcon-form-major']) ? $_POST['comcon-form-major'] : '';
    $input['order'] = str_pad($input['order'], 3, "0", STR_PAD_LEFT);
    foreach ($input as $field => $value) {
        $old = get_post_meta($post_id, 'comcon-form-' . $field, true);
        if ($value && '' == $old) {
            add_post_meta($post_id, 'comcon-form-' . $field, $value, true);
        } else {
            if ($value && $value != $old) {
                update_post_meta($post_id, 'comcon-form-' . $field, $value);
            } else {
                if ('' == $value && $old) {
                    delete_post_meta($post_id, 'comcon-form-' . $field, $old);
                }
            }
        }
    }
}
Example #20
0
function validaCPF($cpf)
{
    if (empty($cpf)) {
        return false;
    }
    //echo $cpf; exit;
    $cpf = str_replace("-", "", str_replace(".", "", $cpf));
    $cpf = str_pad($cpf, 11, '0', STR_PAD_LEFT);
    if (strlen($cpf) != 11) {
        return false;
    } elseif ($cpf == '00000000000' || $cpf == '11111111111' || $cpf == '22222222222' || $cpf == '33333333333' || $cpf == '44444444444' || $cpf == '55555555555' || $cpf == '66666666666' || $cpf == '77777777777' || $cpf == '88888888888' || $cpf == '99999999999') {
        return false;
    } else {
        for ($t = 9; $t < 11; $t++) {
            for ($d = 0, $c = 0; $c < $t; $c++) {
                $d += $cpf[$c] * ($t + 1 - $c);
            }
            $d = 10 * $d % 11 % 10;
            if ($cpf[$c] != $d) {
                return false;
            }
        }
        return true;
    }
}
Example #21
0
function Date2DBF($AMySQLDate)
{
    @(list($vDate, $vTime) = explode(' ', $AMySQLDate, 2));
    @(list($vYear, $vMonth, $vDay) = explode('-', $vDate, 3));
    $vResult = str_pad($vYear, 4, '0', STR_PAD_LEFT) . str_pad($vMonth, 2, '0', STR_PAD_LEFT) . str_pad($vDay, 2, '0', STR_PAD_LEFT);
    return $vResult;
}
Example #22
0
 /**
  * 错误信息处理方法
  *
  * @param string $file
  * @param string $line
  * @param array $trace
  */
 public static function crash($file, $line, $trace)
 {
     $count = count($trace);
     $pad_len = strlen($count);
     $time = date("y-m-d H:i:m");
     foreach ($trace as $key => $call) {
         if (!isset($call['file']) || $call['file'] == '') {
             $call['file'] = '~Internal Location~';
             $call['line'] = 'N/A';
         }
         $trace_line = '#' . str_pad($count - $key, $pad_len, "0", STR_PAD_LEFT) . '  ' . '[' . $time . '] ' . self::_get_call_line($call);
         $trace[$key] = $trace_line;
     }
     $file_lines = array();
     if (is_file($file)) {
         $current_line = $line - 1;
         $file_lines = explode("\n", file_get_contents($file, null, null, 0, 10000000));
         $topLine = $current_line - 5;
         $file_lines = array_slice($file_lines, $topLine > 0 ? $topLine : 0, 10, true);
         if (($count = count($file_lines)) > 0) {
             $padLen = strlen($count);
             foreach ($file_lines as $line => &$file_line) {
                 $fileLine = " " . htmlspecialchars(str_pad($line + 1, $padLen, "0", STR_PAD_LEFT) . ": " . str_replace("\t", "    ", rtrim($file_line)), null, "UTF-8");
             }
         }
     }
     return array($file_lines, $trace, $current_line);
 }
 /**
  * Construct a mock generation failed exception.
  *
  * @param string                   $className  The class name.
  * @param MockDefinition           $definition The definition.
  * @param string                   $source     The generated source code.
  * @param array<string,mixed>|null $error      The error details.
  * @param Exception|Error|null     $cause      The cause, if available.
  */
 public function __construct($className, MockDefinition $definition, $source, array $error = null, $cause = null)
 {
     $this->definition = $definition;
     $this->source = $source;
     $this->error = $error;
     $lines = explode(PHP_EOL, $source);
     if (null === $error) {
         $message = sprintf('Mock class %s generation failed.%sRelevant lines:%%s', $className, PHP_EOL);
         $errorLineNumber = null;
     } else {
         $errorLineNumber = $error['line'];
         $startLine = $errorLineNumber - 4;
         $contextLineCount = 7;
         if ($startLine < 0) {
             $contextLineCount += $startLine;
             $startLine = 0;
         }
         $lines = array_slice($lines, $startLine, $contextLineCount, true);
         $message = sprintf('Mock class %s generation failed: ' . '%s in generated code on line %d.%s' . 'Relevant lines:%%s', $className, $error['message'], $errorLineNumber, PHP_EOL);
     }
     end($lines);
     $lineNumber = key($lines);
     $padSize = strlen($lineNumber + 1) + 4;
     $renderedLines = '';
     foreach ($lines as $lineNumber => $line) {
         if (null !== $errorLineNumber) {
             $highlight = $lineNumber + 1 === $errorLineNumber;
         } else {
             $highlight = false;
         }
         $renderedLines .= sprintf('%s%s%s %s', PHP_EOL, str_pad($lineNumber + 1, $padSize, ' ', STR_PAD_LEFT), $highlight ? ':' : ' ', $line);
     }
     parent::__construct(sprintf($message, $renderedLines), 0, $cause);
 }
Example #24
0
 /**
  * Converts a value to a DateTime.
  * Supports microseconds
  *
  * @throws InvalidArgumentException if $value is invalid
  * @param  mixed $value \DateTime|\MongoDate|int|float
  * @return \DateTime
  */
 public static function getDateTime($value)
 {
     $datetime = false;
     $exception = null;
     if ($value instanceof \DateTime || $value instanceof \DateTimeInterface) {
         return $value;
     } elseif ($value instanceof \MongoDate) {
         $datetime = static::craftDateTime($value->sec, $value->usec);
     } elseif (is_numeric($value)) {
         $seconds = $value;
         $microseconds = 0;
         if (false !== strpos($value, '.')) {
             list($seconds, $microseconds) = explode('.', $value);
             $microseconds = (int) str_pad((int) $microseconds, 6, '0');
             // ensure microseconds
         }
         $datetime = static::craftDateTime($seconds, $microseconds);
     } elseif (is_string($value)) {
         try {
             $datetime = new \DateTime($value);
         } catch (\Exception $e) {
             $exception = $e;
         }
     }
     if ($datetime === false) {
         throw new \InvalidArgumentException(sprintf('Could not convert %s to a date value', is_scalar($value) ? '"' . $value . '"' : gettype($value)), 0, $exception);
     }
     return $datetime;
 }
Example #25
0
function _secs_to_minsecs($s)
{
    $s = (int) $s;
    $m = floor($s / 60);
    $s = $s - $m * 60;
    return $m . ':' . str_pad($s, 2, '0', STR_PAD_LEFT);
}
Example #26
0
 public function regenquestioncodes($iSurveyID, $sSubAction)
 {
     if (!Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->setFlashMessage(gT("You do not have sufficient rights to access this page."), 'error');
         $this->getController()->redirect(array('admin/survey', 'sa' => 'view', 'surveyid' => $iSurveyID));
     }
     $oSurvey = Survey::model()->findByPk($iSurveyID);
     if ($oSurvey->active == 'Y') {
         Yii::app()->setFlashMessage(gT("You can't update question code for an active survey."), 'error');
         $this->getController()->redirect(array('admin/survey', 'sa' => 'view', 'surveyid' => $iSurveyID));
     }
     //Automatically renumbers the "question codes" so that they follow
     //a methodical numbering method
     $iQuestionNumber = 1;
     $iGroupNumber = 0;
     $iGroupSequence = 0;
     $oQuestions = Question::model()->with('groups')->findAll(array('select' => 't.qid,t.gid', 'condition' => "t.sid=:sid and t.language=:language and parent_qid=0", 'order' => 'groups.group_order, question_order', 'params' => array(':sid' => $iSurveyID, ':language' => $oSurvey->language)));
     foreach ($oQuestions as $oQuestion) {
         if ($sSubAction == 'bygroup' && $iGroupNumber != $oQuestion->gid) {
             //If we're doing this by group, restart the numbering when the group number changes
             $iQuestionNumber = 1;
             $iGroupNumber = $oQuestion->gid;
             $iGroupSequence++;
         }
         $sNewTitle = ($sSubAction == 'bygroup' ? 'G' . $iGroupSequence : '') . "Q" . str_pad($iQuestionNumber, 5, "0", STR_PAD_LEFT);
         Question::model()->updateAll(array('title' => $sNewTitle), 'qid=:qid', array(':qid' => $oQuestion->qid));
         $iQuestionNumber++;
         $iGroupNumber = $oQuestion->gid;
     }
     Yii::app()->setFlashMessage(gT("Question codes were successfully regenerated."));
     LimeExpressionManager::SetDirtyFlag();
     // so refreshes syntax highlighting
     $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
 }
 function displayWarning($msg, $red = false)
 {
     if ($red) {
         $msg = "** {$msg}";
     }
     echo str_pad($msg, 100) . "\n";
 }
 public function render($results, $hasAccess, $exactMatch)
 {
     $blob = '';
     foreach ($results as $row) {
         if ($row->help != '') {
             $helpLink = ' (' . $this->text->make_chatcmd("Help", "/tell <myname> help {$row->cmd}") . ')';
         }
         if ($hasAccess) {
             $module = $this->text->make_chatcmd($row->module, "/tell <myname> config {$row->module}");
         } else {
             $module = "{$row->module}";
         }
         $cmd = str_pad($row->cmd . " ", 20, ".");
         $blob .= "<highlight>{$cmd}<end> {$module} - {$row->description}{$helpLink}\n";
     }
     $count = count($results);
     if ($count == 0) {
         $msg = "No results found.";
     } else {
         if ($exactMatch) {
             $msg = $this->text->make_blob("Command Search Results ({$count})", $blob);
         } else {
             $msg = $this->text->make_blob("Possible Matches ({$count})", $blob);
         }
     }
     return $msg;
 }
Example #29
0
 private function indent($path)
 {
     $depth = sizeof(explode("/", $path)) - 1;
     $indent = "";
     $indent = str_pad($indent, $depth, "\t");
     return "\r\n" . $indent;
 }
 private function convertLessThan1000($number)
 {
     $output = '';
     if ($number < 20) {
         $output = self::$oneToNineteen[$number];
     } else {
         $numberString = str_pad(strval($number), 3, '0', STR_PAD_LEFT);
         if ($numberString[0] !== '0') {
             $output = self::$oneToNineteen[intval($numberString[0])] . ' hundred';
         }
         if ($numberString[0] !== '0' && ($numberString[1] !== '0' || $numberString[2] !== '0')) {
             $output .= ' and ';
         }
         if ($numberString[1] !== '0') {
             $output .= self::$tens[intval($numberString[1])];
         }
         if ($numberString[2] !== '0') {
             if ($numberString[1] !== '0') {
                 $output .= ' ';
             }
             $output .= self::$oneToNineteen[intval($numberString[2])];
         }
     }
     return $output;
 }