/** * @brief Get the points */ function getPoint($member_srl, $from_db = false) { $member_srl = abs($member_srl); // Get from instance memory if (!$from_db && $this->pointList[$member_srl]) { return $this->pointList[$member_srl]; } // Get from file cache $path = sprintf(_XE_PATH_ . 'files/member_extra_info/point/%s', getNumberingPath($member_srl)); $cache_filename = sprintf('%s%d.cache.txt', $path, $member_srl); if (!$from_db && file_exists($cache_filename)) { return $this->pointList[$member_srl] = trim(FileHandler::readFile($cache_filename)); } // Get from the DB $args = new stdClass(); $args->member_srl = $member_srl; $output = executeQuery('point.getPoint', $args); if (isset($output->data->member_srl)) { $point = (int) $output->data->point; $this->pointList[$member_srl] = $point; if (!is_dir($path)) { FileHandler::makeDir($path); } FileHandler::writeFile($cache_filename, $point); return $point; } return 0; }
function compile_array($options) { if (self::check($this->from_num) && self::check($this->to_num) && abs($this->from_num - $this->to_num) <= 20) { $range = range($this->from_num, $this->to_num); if ($this->exclusive) { array_pop($range); } return '[' . implode(', ', $range) . ']'; } $idt = $this->tab . TAB; $i = $options['scope']->free_variable('i'); $result = $options['scope']->free_variable('results'); $pre = "\n{$idt}{$result} = [];"; if (self::check($this->from_num) && self::check($this->to_num)) { $options['index'] = $i; $body = $this->compile_node($options); } else { $vars = "{$i} = {$this->from_c}" . ($this->to_c !== $this->to_var ? ", {$this->to_c}" : ''); $cond = "{$this->from_var} <= {$this->to_var}"; $body = "var {$vars}; {$cond} ? {$i} <{$this->equals} {$this->to_var} : {$i} >{$this->equals} {$this->to_var}; {$cond} ? {$i}++ : {$i}--"; } $post = "{ {$result}.push({$i}); }\n{$idt}return {$result};\n{$options['indent']}"; $has_args = function ($node) { return $node->contains(function ($n) { return $n instanceof yy_Literal && $n->value === 'arguments' && !$n->as_key; }); return FALSE; }; $args = ''; if ($has_args($this->from) || $has_args($this->to)) { $args = ', arguments'; } return "(function() {{$pre}\n{$idt}for ({$body}){$post}}).apply(this{$args})"; }
public function index_post() { if (IS_POST || isset($_GET['dosubmit'])) { //print_r($_REQUEST);exit(); if (isset($_GET['type']) && $_GET['type'] == 'url') { $sizelimit = isset($_GET['sizelimit']) && abs(intval($_GET['sizelimit'])) ? abs(intval($_GET['sizelimit'])) : $this->error('请输入每个分卷文件大小'); $this->backup_name = isset($_GET['backup_name']) && trim($_GET['backup_name']) ? trim($_GET['backup_name']) : $this->error('请输入备份名称'); $vol = $this->_get_vol(); $vol++; } else { $sizelimit = isset($_POST['sizelimit']) && abs(intval($_POST['sizelimit'])) ? abs(intval($_POST['sizelimit'])) : $this->error('请输入每个分卷文件大小'); $this->backup_name = isset($_POST['backup_name']) && trim($_POST['backup_name']) ? trim($_POST['backup_name']) : $this->error('请输入备份名称'); $backup_tables = isset($_POST['backup_tables']) && $_POST['backup_tables'] ? $_POST['backup_tables'] : $this->error('请选择备份数据表'); if (is_dir(SITE_PATH . $this->backup_path . $this->backup_name)) { $this->error('备份名称已经存在'); } mkdir(SITE_PATH . $this->backup_path . $this->backup_name); if (!is_file(SITE_PATH . $this->backup_path . $this->backup_name . '/tbl_queue.log')) { //写入队列 $this->_put_tbl_queue($backup_tables); } $vol = 1; } $tables = $this->_dump_queue($vol, $sizelimit * 1024); if ($tables === false) { $this->error('加载队列文件错误'); } $this->_deal_result($tables, $vol, $sizelimit); exit; } }
/** *get *point,offset,status *point:请求界点,status订单状态,offset个数,为正则取大于界点point的offset个元素,反之取小于point的offset个元素 **/ protected function read() { $input = $this->get; $ret = $input && $input['point'] !== false && $input['offset'] !== false && $input['status']; if ($ret) { $condition['token'] = $this->token; $condition['hid'] = $this->hid; $condition['order_status'] = $input['status']; $limit = abs($input['offset']); if ($input['point'] == -1) { $ret = $this->model->listOrders($condition, $limit, true); } else { $is_desc = $input['offset'] < 0; $opration_con = $is_desc ? 'lt' : 'gt'; //lt 小于,gt 大于 $condition['id'] = array($opration_con, $input['point']); $ret = $this->model->listOrders($condition, $limit, $is_desc); } } if ($ret !== false) { $this->success("操作成功!", $ret); } else { $this->error('error in read'); Log::record('error' . print_r($input) . '\\n'); } }
public static function Create($user_row, $uc = true) { if (function_exists('zuitu_uc_register') && $uc) { $pp = $user_row['password']; $em = $user_row['email']; $un = $user_row['username']; $ret = zuitu_uc_register($em, $un, $pp); if (!$ret) { return false; } } $user_row['username'] = htmlspecialchars($user_row['username']); $user_row['password'] = self::GenPassword($user_row['password']); $user_row['create_time'] = $user_row['login_time'] = time(); $user_row['ip'] = Utility::GetRemoteIp(); $user_row['secret'] = md5(rand(1000000, 9999999) . time() . $user_row['email']); $user_row['id'] = DB::Insert('user', $user_row); $_rid = abs(intval(cookieget('_rid'))); if ($_rid && $user_row['id']) { $r_user = Table::Fetch('user', $_rid); if ($r_user) { ZInvite::Create($r_user, $user_row); ZCredit::Invite($r_user['id']); } } if ($user_row['id'] == 1) { Table::UpdateCache('user', $user_row['id'], array('manager' => 'Y', 'secret' => '')); } return $user_row['id']; }
/** * Constructor: Generate LU decomposition of the matrix. * As trace the permutated matrix and eliminated matrix of each step is stored. * * @param matrix matrix to get lu decomposition of * @return vector permutation */ public function __construct(&$matrix) { new Assertion($matrix instanceof Matrix, 'Given matrix not of class Matrix.'); new Assertion($matrix->isSquare(), 'Matrix is not square.'); $this->_matrix = $matrix->copy(); $this->_permutation = new Vector($this->_matrix->rows()); for ($j = 0; $j < $this->_matrix->rows(); $j++) { $pivot = $j; for ($i = $j + 1; $i < $this->_matrix->rows(); $i++) { if (abs($this->_matrix->get($i, $j)) > abs($this->_matrix->get($pivot, $j))) { $pivot = $i; } } $this->_permutation->set($j, $pivot); $this->_matrix->swapRows($j, $pivot); // Save the matrix after permutation. $this->_trace[$j] = array('permutation' => $this->_matrix->copy()); for ($i = $j + 1; $i < $this->_matrix->columns(); $i++) { $this->_matrix->set($i, $j, $this->_matrix->get($i, $j) / $this->_matrix->get($j, $j)); for ($k = $j + 1; $k < $this->_matrix->columns(); $k++) { $this->_matrix->set($i, $k, $this->_matrix->get($i, $k) - $this->_matrix->get($i, $j) * $this->_matrix->get($j, $k)); } } // Save the matrix after elimination. $this->_trace[$j]['elimination'] = $this->_matrix->copy(); } }
function format() { $base = $_REQUEST['_router_']; if ($this->curpage > 1) { $html[] = "<a href='{$this->router}'>首页</a>"; } $pages = array(); for ($i = 1; $i <= $this->pagenum; $i++) { if ($i <= 3 || abs($this->curpage - $i) < 3 || $this->pagenum - $i <= 3) { $pages[] = $i; continue; } } $html = array(); foreach ($pages as $i => $p) { if ($i > 1 && $p - $pages[$i - 1] > 1) { $html[] = '...'; } else { $this->query['page'] = $p; $url = $this->router; $url .= strpos($url, '?') ? '&' : '?'; $url .= http_build_query($this->query); //echo $url; $html[] = "<a href='{$url}'>{$p}</a>"; } } return "共{$this->records}记录,第{$this->curpage}/{$this->pagenum}页 " . implode('', $html); }
function action_add($input) { $trackerId = $input->trackerId->int(); $definition = Tracker_Definition::get($trackerId); if (!$definition) { throw new Services_Exception_NotFound(); } $delayAfter = abs($input->after->int() * $input->after_unit->int()); $delayNotif = abs($input->notif->int() * $input->notif_unit->int()); $from = $input->from->word(); $to = $input->to->word(); $event = $input->event->word(); $subject = $input->subject->text(); $body = $input->body->text(); $todolib = TikiLib::lib('todo'); if (!$delayAfter) { throw new Services_Exception_MissingValue('after'); } $todoId = $todolib->addTodo($delayAfter, $event, 'tracker', $trackerId, array('status' => $from), array('status' => $to)); if ($delayNotif) { $detail = array('mail' => 'creator', 'before' => $delayNotif); if ($subject) { $detail['subject'] = $subject; } if ($body) { $detail['body'] = $body; } $todolib->addTodo($delayAfter - $delayNotif, $event, 'todo', $todoId, "", $detail); } return array('trackerId' => $trackerId, 'todoId' => $todoId); }
function getSize($TextString, $Format = "") { $Angle = isset($Format["Angle"]) ? $Format["Angle"] : 0; $ShowLegend = isset($Format["ShowLegend"]) ? $Format["ShowLegend"] : FALSE; $LegendOffset = isset($Format["LegendOffset"]) ? $Format["LegendOffset"] : 5; $DrawArea = isset($Format["DrawArea"]) ? $Format["DrawArea"] : FALSE; $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : 12; $Height = isset($Format["Height"]) ? $Format["Height"] : 30; $TextString = $this->encode39($TextString); $BarcodeLength = strlen($this->Result); if ($DrawArea) { $WOffset = 20; } else { $WOffset = 0; } if ($ShowLegend) { $HOffset = $FontSize + $LegendOffset + $WOffset; } else { $HOffset = 0; } $X1 = cos($Angle * PI / 180) * ($WOffset + $BarcodeLength); $Y1 = sin($Angle * PI / 180) * ($WOffset + $BarcodeLength); $X2 = $X1 + cos(($Angle + 90) * PI / 180) * ($HOffset + $Height); $Y2 = $Y1 + sin(($Angle + 90) * PI / 180) * ($HOffset + $Height); $AreaWidth = max(abs($X1), abs($X2)); $AreaHeight = max(abs($Y1), abs($Y2)); return array("Width" => $AreaWidth, "Height" => $AreaHeight); }
/** * Test case for oePayPalIPNRequestPaymentSetter::getRequestOrderPayment * Test case for oePayPalIPNRequestPaymentSetter::setRequestOrderPayment * Test case for oePayPalIPNRequestPaymentSetter::_prepareOrderPayment * Test case for oePayPalIPNRequestPaymentSetter::getRequest * Test case for oePayPalIPNRequestPaymentSetter::getAction * Test case for oePayPalIPNRequestPaymentSetter::getAmount * * @param array $aParams parameters for POST imitating PayPal. * @param string $expectedAction Expected action for resulting payment. * * @dataProvider providerGetRequestOrderPayment */ public function testGetRequestOrderPayment($aParams, $expectedAction) { $oPayPalExpectedPayment = new oePayPalOrderPayment(); if (!empty($aParams)) { $oPayPalExpectedPayment->setStatus($aParams['payment_status']); $oPayPalExpectedPayment->setTransactionId($aParams['txn_id']); $oPayPalExpectedPayment->setCurrency($aParams['mc_currency']); $oPayPalExpectedPayment->setAmount(abs($aParams['mc_gross'])); $oPayPalExpectedPayment->setAction($expectedAction); $correlationId = empty($aParams['correlation_id']) ? $aParams['ipn_track_id'] : $aParams['correlation_id']; $oPayPalExpectedPayment->setCorrelationId($correlationId); $oPayPalExpectedPayment->setDate(date('Y-m-d H:i:s', strtotime($aParams['payment_date']))); } else { $oPayPalExpectedPayment->setStatus(null); $oPayPalExpectedPayment->setTransactionId(null); $oPayPalExpectedPayment->setCurrency(null); $oPayPalExpectedPayment->setAmount(null); $oPayPalExpectedPayment->setCorrelationId(null); $oPayPalExpectedPayment->setDate(null); $oPayPalExpectedPayment->setAction('capture'); } $_POST = $aParams; $oRequest = new oePayPalRequest(); $oPayPalPayment = new oePayPalOrderPayment(); $oPayPalIPNRequestSetter = new oePayPalIPNRequestPaymentSetter(); $oPayPalIPNRequestSetter->setRequest($oRequest); $oPayPalIPNRequestSetter->setRequestOrderPayment($oPayPalPayment); $oRequestOrderPayment = $oPayPalIPNRequestSetter->getRequestOrderPayment(); $this->assertEquals($oPayPalExpectedPayment, $oRequestOrderPayment, 'Payment object do not have request parameters.'); }
/** * @param string $name * @param int $second * @param int $first */ public function customTimeMetric($name, &$second, &$first) { if (empty($second) || empty($first)) { return; } $this->customMetric($name, round(abs($second - $first) * 1000, 0)); }
/** * @param mixed:\DateInterval|\DateInterval[] $vars * @param \DateInterval $vars,... * @return \DateInterval */ public static function sum() { $intervals = array(); foreach (func_get_args() as $e) { if (is_array($e)) { $intervals = array_merge($intervals, array_values($e)); } else { $intervals[] = $e; } } $base = $intervals[0]; unset($intervals[0]); try { /* @var $intervals \DateInterval[] */ $intervals = ParameterConverter::toArray($intervals, '\\DateInterval'); } catch (\DomainException $e) { throw new \InvalidArgumentException('This method only accepts \\DateInterval objects.'); } $s = self::toSeconds($base); foreach ($intervals as $interval) { /* @var $interval \DateInterval */ if (!$interval->invert) { $s += self::toSeconds($interval); } else { $s -= self::toSeconds($interval); } } $result = new \DateInterval(sprintf('PT%dS', abs($s))); $result = new \DateInterval(self::shortenString($result)); if ($s < 0) { $result->invert = true; } return $result; }
/** * * Returns array of people containing entity, mutuals (friends), groups (shared) and priority * @param Int $guid * @param Int $friends_limit * @param Int $groups_limit * @return Array */ function get_suggestions($guid, $friends_of_friends_limit = 10, $groups_members_limit = 10) { $dbprefix = elgg_get_config('dbprefix'); $guid = sanitize_int($guid); $suggestions = array(); if ($friends_of_friends_limit) { // get some friends of friends $options = array('selects' => array('COUNT(fof.guid_two) as priority'), 'type' => 'user', 'joins' => array("JOIN {$dbprefix}users_entity ue ON ue.guid = e.guid", "JOIN {$dbprefix}entity_relationships fr ON fr.guid_one = {$guid} AND fr.relationship = 'friend'", "JOIN {$dbprefix}entity_relationships fof ON fof.guid_one = fr.guid_two AND fof.relationship = 'friend'"), "wheres" => array("ue.banned = 'no'", "e.guid NOT IN (SELECT f.guid_two FROM {$dbprefix}entity_relationships f WHERE f.guid_one = {$guid} AND f.relationship = 'friend')", "fof.guid_two = e.guid", "e.guid != {$guid}"), 'group_by' => 'e.guid', 'order_by' => 'priority desc, ue.last_action desc', 'limit' => abs((int) $friends_of_friends_limit)); $fof = elgg_get_entities($options); foreach ($fof as $f) { $priority = (int) $f->getVolatileData('select:priority'); $suggestions[$f->guid] = array('entity' => $f, 'mutuals' => $priority, 'groups' => 0, 'priority' => $priority); } } if ($groups_members_limit) { // get some mutual group members $options = array('selects' => array('COUNT(mog.guid_two) as priority'), 'type' => 'user', 'joins' => array("JOIN {$dbprefix}users_entity ue ON ue.guid = e.guid", "JOIN {$dbprefix}entity_relationships g ON g.guid_one = {$guid} AND g.relationship = 'member'", "JOIN {$dbprefix}groups_entity ge ON ge.guid = g.guid_two", "JOIN {$dbprefix}entity_relationships mog ON mog.guid_two = g.guid_two AND mog.relationship = 'member'"), "wheres" => array("ue.banned = 'no'", "e.guid NOT IN (SELECT f.guid_two FROM {$dbprefix}entity_relationships f WHERE f.guid_one = {$guid} AND f.relationship = 'friend')", "mog.guid_one = e.guid", "e.guid != {$guid}"), 'group_by' => 'e.guid', 'order_by' => 'priority desc, ue.last_action desc', 'limit' => 3); // get members of groups $mog = elgg_get_entities($options); foreach ($mog as $m) { if (!isset($suggestions[$m->guid])) { $priority = (int) $m->getVolatileData('select:priority'); $suggestions[$m->guid] = array('entity' => $m, 'mutuals' => 0, 'groups' => $priority, 'priority' => $priority); } else { $priority = (int) $m->getVolatileData('select:priority'); $suggestions[$m->guid]['groups'] = $priority; $suggestions[$m->guid]['priority'] += $priority; } } } // sort by priority usort($suggestions, __NAMESPACE__ . '\\suggested_friends_sorter'); return $suggestions; }
/** * Render customer orders list xml * * @return string */ protected function _toHtml() { /** @var $ordersXmlObj Mage_XmlConnect_Model_Simplexml_Element */ $ordersXmlObj = Mage::getModel('xmlconnect/simplexml_element', '<orders></orders>'); /** @var $orders Mage_Sales_Model_Resource_Order_Collection */ $orders = Mage::getResourceModel('sales/order_collection')->addFieldToSelect('*')->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId())->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))->setOrder('created_at', 'desc'); /** @var $request Mage_Core_Controller_Request_Http */ $request = $this->getRequest(); /** * Apply offset and count */ $count = abs((int) $request->getParam('count', 0)); $count = $count ? $count : self::ORDERS_LIST_LIMIT; $offset = abs((int) $request->getParam('offset', 0)); $ordersXmlObj->addAttribute('orders_count', $ordersXmlObj->escapeXml($orders->count())); $ordersXmlObj->addAttribute('offset', $ordersXmlObj->escapeXml($offset)); $orders->clear()->getSelect()->limit($count, $offset); $orders->load(); if ($orders->count()) { foreach ($orders as $order) { $item = $ordersXmlObj->addChild('item'); $item->addChild('entity_id', $order->getId()); $item->addChild('number', $order->getRealOrderId()); $item->addChild('date', $this->formatDate($order->getCreatedAtStoreDate())); if ($order->getShippingAddress()) { $item->addChild('ship_to', $ordersXmlObj->escapeXml($order->getShippingAddress()->getName())); } $item->addChild('total', $order->getOrderCurrency()->formatPrecision($order->getGrandTotal(), 2, array(), false, false)); $item->addChild('status', $order->getStatusLabel()); } } return $ordersXmlObj->asNiceXml(); }
/** * CDN图片域名 * * @param string $img 图片地址 * @param string $path 附加路径 * @return string 完整URL图片地址 */ function cdn_img_url($img, $path = '/') { if (empty($img) || strpos($img, '://') !== false) { return $img; } if ($img[0] == '/') { $path = ''; } /** * 当使用本机时,就不用CDN处理了 */ if (isset($_GET['local'])) { return "{$path}{$img}"; } if (USE_ISLOCAL_JS2CSS || USE_ISLOCAL_IMG) { $file_ext = strtolower(strrchr($img, '.')); if (USE_ISLOCAL_JS2CSS && ($file_ext == '.js' || $file_ext == '.css')) { return "{$path}{$img}"; } if (USE_ISLOCAL_IMG && ($file_ext == '.jpg' || $file_ext == '.jpeg' || $file_ext == '.gif' || $file_ext == '.swf' || $file_ext == '.png')) { return "{$path}{$img}"; } } /** * 分服务器加载 */ static $img_hosts = null; static $img_count = null; if (is_null($img_hosts)) { $img_hosts = json_decode(IMG_URLS, true); $img_count = count($img_hosts); } $key = abs(crc32($img)) % $img_count; return "{$img_hosts[$key]}{$path}{$img}"; }
function round_up($value, $places) { $mult = pow(10, abs($places)); return $places < 0 ? ceil($value / $mult) * $mult : ceil($value * $mult) / $mult; }
/** * Маппинг входящих значений к свойствам объекта операции * * @param array $values - исходные значения * @return array - преобразованные значения */ public function processValues($values) { // User // TODO: переделать через один запрос вместе с валидацией $values['user_id'] = Doctrine::getTable('User')->findByUserServiceMail($values['email'])->getFirst()->getId(); unset($values['email']); // Счет для привязки операции # Svel: закомментировал в соответствии с требованиями мягкости в t1713 // $values['account_id'] = Doctrine::getTable('Account')->findLinkedWithSource($values['user_id'], $values['source']); // выбрать ID счета по последней активной операции $values['account_id'] = Doctrine::getTable('Operation')->findAccountIdByLastAcceptedOperationBySource($values['user_id'], $values['source']); // Тип операции и сумма $values['money'] = abs((double) $values['amount']); // Дата и время $values['date'] = date('Y-m-d'); $values['time'] = date('H:i:s'); // Черновик $values['accepted'] = Operation::STATUS_DRAFT; // Источник $values['source_id'] = $values['source']; $values['SourceOperation'] = array('source_uid' => $values['source'], 'source_operation_uid' => $values['id']); // Комментарий $values['comment'] = sprintf("%s %s %s\n", $values['source'], $values['description'], $values['account']); unset($values['description']); unset($values['account']); unset($values['id']); unset($values['source']); return $values; }
function createMergeTable() { $split_ps = $this->store->getSetting('split_predicates', array()); if (!$split_ps) { return 1; } $this->mrg_table_id = 'MRG_' . $this->store->getTablePrefix() . crc32(uniqid(rand())); $con = $this->store->getDBCon(); $this->queryDB("FLUSH TABLES", $con); $indexes = $this->v('store_indexes', array('sp (s,p)', 'os (o,s)', 'po (p,o)'), $this->a); $index_code = $indexes ? 'KEY ' . join(', KEY ', $indexes) . ', ' : ''; $prefix = $this->store->getTablePrefix(); $sql = "\n CREATE TEMPORARY TABLE IF NOT EXISTS " . $prefix . "triple_all (\n t mediumint UNSIGNED NOT NULL,\n s mediumint UNSIGNED NOT NULL,\n p mediumint UNSIGNED NOT NULL,\n o mediumint UNSIGNED NOT NULL,\n o_lang_dt mediumint UNSIGNED NOT NULL,\n o_comp char(35) NOT NULL, /* normalized value for ORDER BY operations */\n s_type tinyint(1) NOT NULL default 0, /* uri/bnode => 0/1 */\n o_type tinyint(1) NOT NULL default 0, /* uri/bnode/literal => 0/1/2 */\n misc tinyint(1) NOT NULL default 0, /* temporary flags */\n UNIQUE KEY (t), " . $index_code . " KEY (misc)\n ) \n "; $v = $this->store->getDBVersion(); $sql .= $v < '04-01-00' && $v >= '04-00-18' ? 'ENGINE' : ($v >= '04-01-02' ? 'ENGINE' : 'TYPE'); $sql .= "=MERGE UNION=(" . $prefix . "triple"; foreach ($split_ps as $pos => $p) { $sql .= ',' . $prefix . 'triple_' . abs(crc32($p)); } $sql .= ")"; //$sql .= ($v >= '04-00-00') ? " CHARACTER SET utf8" : ""; //$sql .= ($v >= '04-01-00') ? " COLLATE utf8_unicode_ci" : ""; //echo $sql; return $this->queryDB($sql, $con); }
function kopa_click_like_button() { check_ajax_referer('kopa_click_like_button', 'ajax_nonce'); if (!empty($_POST['post_id'])) { $result = array('status' => 'disable', 'total' => 0); $post_id = (int) $_POST['post_id']; $status = $_POST['status']; $include_text = $_POST['include_text']; $public_key = KOPA_OPT_PREFIX . 'likes'; $single_key = KOPA_OPT_PREFIX . 'like_by_' . KopaUtil::get_client_IP(); $total = KopaUtil::get_likes($post_id); $is_liked = KopaUtil::is_liked($post_id); if ('enable' == $status && !$is_liked) { $total++; update_post_meta($post_id, $single_key, true); update_post_meta($post_id, $public_key, abs($total)); $result['class'] = 'kopa-button-likes-disable'; } else { $total--; delete_post_meta($post_id, $single_key); update_post_meta($post_id, $public_key, abs($total)); $result['class'] = 'kopa-button-likes-enable'; } if ($include_text) { if ($total < 2) { $total .= __(' Like', kopa_get_domain()); } else { $total .= __(' Likes', kopa_get_domain()); } } $result['total'] = $total; echo json_encode($result); } exit; }
function pre_confirmation_check($order_total) { global $order; // clean out negative values and strip common currency symbols $_SESSION['cot_gv'] = str_replace(array('$', '%', '#', '\\'), '', $_SESSION['cot_gv']); // eucでは表せない $_SESSION['cot_gv'] = abs($_SESSION['cot_gv']); if ($_SESSION['cot_gv'] > 0) { if ($this->include_shipping == 'false') { $order_total -= $order->info['shipping_cost']; } if ($this->include_tax == 'false') { $order_total -= $order->info['tax']; } if (ereg('[^0-9/.]', trim($_SESSION['cot_gv']))) { zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, 'credit_class_error_code=' . $this->code . '&credit_class_error=' . urlencode(TEXT_INVALID_REDEEM_AMOUNT), 'SSL', true, false)); } if ($_SESSION['cot_gv'] > $this->user_has_gv_account($_SESSION['customer_id'])) { zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, 'credit_class_error_code=' . $this->code . '&credit_class_error=' . urlencode(TEXT_INVALID_REDEEM_AMOUNT), 'SSL', true, false)); } $od_amount = $this->calculate_credit($order_total); if ($this->calculate_tax != "none") { $tod_amount = $this->calculate_tax_deduction($order_total, $od_amount, $this->calculate_tax); $od_amount = $this->calculate_credit($order_total) + $tod_amount; } if ($od_amount >= $order->info['total'] && MODULE_ORDER_TOTAL_GV_ORDER_STATUS_ID != 0) { $order->info['order_status'] = MODULE_ORDER_TOTAL_GV_ORDER_STATUS_ID; } } return $od_amount + $tod_amount; }
/** * Returns the timezone choices. * * The choices are generated from the ICU function * \DateTimeZone::listIdentifiers(). They are cached during a single request, * so multiple timezone fields on the same page don't lead to unnecessary * overhead. * * @return array The timezone choices */ public static function getTimezones() { if (null === static::$timezones) { static::$timezones = array(); $timezones = self::getTimezonesData(); foreach ($timezones as $timezoneData) { $timezone = $timezoneData['timezone_id']; $offset = $timezoneData['offset']; $parts = explode('/', $timezone); if (count($parts) > 2) { $region = $parts[0]; $name = $parts[1] . ' - ' . $parts[2]; } elseif (count($parts) > 1) { $region = $parts[0]; $name = $parts[1]; } else { $region = 'Other'; $name = $parts[0]; } $timezoneOffset = sprintf('UTC %+03d:%02u', $offset / 3600, abs($offset) % 3600 / 60); $timezoneName = '(' . $timezoneOffset . ') '; if ($region) { $timezoneName .= $region . '/'; } $timezoneName .= $name; static::$timezones[$timezone] = str_replace('_', ' ', $timezoneName); } } return static::$timezones; }
public function testFormatYaml() { $server = ['HTTP_ACCEPT' => 'application/yaml', 'REQUEST_METHOD' => 'GET', 'SCRIPT_FILENAME' => 'my/base/path/my/request/uri/filename', 'REQUEST_URI' => 'my/base/path/my/request/uri', 'PHP_SELF' => 'my/base/path']; $request = new Request(["callback" => ""], [], [], [], [], $server); $apiResult = new Result($request); $response = (new Parser())->parse($apiResult->createResponse()->getContent()); $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $response); $this->assertArrayHasKey("meta", $response); $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $response["meta"]); $this->assertArrayHasKey("response", $response); $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $response["response"]); $this->assertEquals(0, count($response["response"])); $this->assertArrayHasKey("api_version", $response["meta"]); $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["api_version"]); $this->assertEquals(V1::VERSION, $response["meta"]["api_version"]); $this->assertArrayHasKey("request", $response["meta"]); $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["request"]); $this->assertEquals("GET my/base/path/my/request/uri", $response["meta"]["request"]); $this->assertArrayHasKey("response_time", $response["meta"]); $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["response_time"]); $this->assertDateAtom($response["meta"]["response_time"]); $dateObj1 = \DateTime::createFromFormat(DATE_ATOM, $response["meta"]["response_time"]); $dateObj2 = new \DateTime(); $this->assertLessThan(3, abs($dateObj1->format('U') - $dateObj2->format('U')), 'No more than 3sec between now and the query'); $this->assertArrayHasKey("http_code", $response["meta"]); $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_INT, $response["meta"]["http_code"]); $this->assertEquals(200, $response["meta"]["http_code"]); $this->assertArrayHasKey("error_message", $response["meta"]); $this->assertNull($response["meta"]["error_message"]); $this->assertArrayHasKey("error_details", $response["meta"]); $this->assertNull($response["meta"]["error_details"]); $this->assertArrayHasKey("charset", $response["meta"]); $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["charset"]); $this->assertEquals("UTF-8", $response["meta"]["charset"]); }
/** * * @param string $playername Minecraft player name * @param resource $avatar the rendered avatar (for example player head) * * @param string $background Image Path or Standard Value * @return resource the generated banner */ public static function player($playername, $avatar = NULL, $background = NULL) { $canvas = MinecraftBanner::getBackgroundCanvas(self::PLAYER_WIDTH, self::PLAYER_HEIGHT, $background); $head_height = self::AVATAR_SIZE; $head_width = self::AVATAR_SIZE; $avater_x = self::PLAYER_PADDING; $avater_y = self::PLAYER_HEIGHT / 2 - self::AVATAR_SIZE / 2; if ($avatar == NULL) { $avatar = imagecreatefrompng(__DIR__ . "/img/head.png"); imagesavealpha($avatar, true); imagecopy($canvas, $avatar, $avater_x, $avater_y, 0, 0, $head_width, $head_height); } else { $head_width = imagesx($avatar); $head_height = imagesy($avatar); if ($head_width > self::AVATAR_SIZE) { $head_width = self::AVATAR_SIZE; } if ($head_height > self::AVATAR_SIZE) { $head_height = self::AVATAR_SIZE; } $center_x = $avater_x + self::AVATAR_SIZE / 2 - $head_width / 2; $center_y = $avater_y + self::AVATAR_SIZE / 2 - $head_height / 2; imagecopy($canvas, $avatar, $center_x, $center_y, 0, 0, $head_width, $head_height); } $box = imagettfbbox(self::TEXT_SIZE, 0, MinecraftBanner::FONT_FILE, $playername); $text_width = abs($box[4] - $box[0]); $text_color = imagecolorallocate($canvas, 255, 255, 255); $remaining = self::PLAYER_WIDTH - self::AVATAR_SIZE - $avater_x - self::PLAYER_PADDING; $text_posX = $avater_x + self::AVATAR_SIZE + $remaining / 2 - $text_width / 2; $text_posY = $avater_y + self::AVATAR_SIZE / 2 + self::TEXT_SIZE / 2; imagettftext($canvas, self::TEXT_SIZE, 0, $text_posX, $text_posY, $text_color, MinecraftBanner::FONT_FILE, $playername); return $canvas; }
function __convertHeaders($content) { ## regex101: https://regex101.com/r/nQ8oJ9/1 ## Loop through headers from largest to smallest; $n is the number of '=' on each side for ($n = 6; $n > 3; $n--) { ## Find header preg_match_all("/={" . $n . "}(.+?)={" . $n . "}(.+?)(?=={" . $n . "}|\\Z)/ms", $content, $headers); ## Determine which header value is being replaced $h = abs(7 - $n); ## For each header found in that header style/number for ($x = 0; $x < count($headers[0]); $x++) { ## if header is style 2 make main section if ($h == 2) { $content = str_replace($headers[0][$x], "<div class='main_section'><h2>" . $headers[1][$x] . "</h2>\n" . $headers[2][$x] . "</div>", $content); ## If header is style 3 make subsection } else { if ($h == 3) { $content = str_replace($headers[0][$x], "<div class='sub_section'><h3>" . $headers[1][$x] . "</h3>\n" . $headers[2][$x] . "</div>", $content); ## If header is anything but 2 or 3 } else { $content = str_replace($headers[0][$x], "<div class='other_section'><h{$h}>" . $headers[1][$x] . "</h{$h}>" . $headers[2][$x] . "</div>", $content); } } } $headers = null; } return $content; }
public function updateSmens() { $res = $this->tm->get_shifts($this->start_day, $this->end_day); $time = time(); foreach ($res as $v) { $crew = DB::connection($this->city->db)->table('crews')->where('driver', $v->driver_id)->first(); $insert_data = ['id' => $v->shift_id, 'driver' => $v->driver_id, 'begin' => strtotime($v->plan_shift_start_time), 'end' => strtotime($v->plan_shift_finish_time), 'crew' => isset($crew->id) ? $crew->id : 0, 'type' => $v->shift_state, 'uptime' => $time]; $smen = DB::connection($this->city->db)->table('smens')->where('id', $v->shift_id)->first(); if (!empty($smen)) { unset($insert_data['id']); DB::connection($this->city->db)->table('smens')->where('id', $v->shift_id)->update($insert_data); } else { DB::connection($this->city->db)->table('smens')->insert($insert_data); $buy_driver = Driver::on($this->city->db)->find($v->driver_id); if (!empty($buy_driver) && $v->plan_shift_cost != 1) { $locked_alias = Driver::on($this->city->db)->where('name', $buy_driver->name)->where('type', 'dolg')->where('balans', '<', '0')->first(); if (!empty($locked_alias)) { $summ = $locked_alias->balans > -2000 ? abs($locked_alias->balans) : 2000; $this->dr->MoneyOperations($buy_driver->id, 0, 1, 'TEST', 'TEST TRANSFER TO DEB' . $summ); $this->dr->MoneyOperations($locked_alias->id, 1, 1, 'TEST', 'TEST TRANSFER TO DEB' . $summ); $locked_a2 = Driver::find($locked_alias->id); if (isset($locked_a2) && $locked_a2->balans >= 0) { $this->dr->deleteDriver($locked_a2->id); } } } } } return $res; }
/** *问题浏览量更新 */ public function pageViewAction() { //基础元素,必须参与验证 $View['PageId'] = abs(intval($this->request->PageId)); $View['ViewIP'] = urldecode(trim($this->request->ViewIP)); $View['Time'] = abs(intval($this->request->Time)); //URL验证码 $sign = $this->request->sign; //私钥,以后要移开到数据库存储 $p_sign = '5173'; $sign_to_check = base_common::check_sign($View, $p_sign); //不参与验证的元素 //验证URL是否来自可信的发信方 if ($sign_to_check == $sign) { //验证时间戳,时差超过600秒即认为非法 if (abs($View['Time'] - time()) <= 600) { $View['ViewIP'] = Base_Common::ip2long($View['ViewIP']); $InsertLog = $this->oView->addViewLog($View); if ($InsertLog) { $result = array('return' => 1, 'comment' => "添加成功"); } else { $result = array('return' => 2, 'comment' => "添加失败"); } } else { $result = array('return' => 0, 'comment' => "时间有误"); } } else { $result = array('return' => 0, 'comment' => "验证失败,请检查URL"); } echo json_encode($result); }
/** *用户ID方式登录 */ public function getQuestionListAction() { //基础元素,必须参与验证 $Config['Time'] = abs(intval($this->request->Time)); $Config['ReturnType'] = $this->request->ReturnType ? $this->request->ReturnType : 2; //URL验证码 $sign = trim($this->request->sign); //私钥,以后要移开到数据库存储 $p_sign = 'lm'; $sign_to_check = Base_common::check_sign($Config, $p_sign); //不参与验证的元素 //验证URL是否来自可信的发信方 if ($sign_to_check == $sign) { //验证时间戳,时差超过600秒即认为非法 if (abs($Config['Time'] - time()) <= 600) { $QuestionList = $this->oSecurityAnswer->getAll(); $result = array('return' => 1, 'QuestionList' => $QuestionList); } else { $result = array('return' => 0, 'comment' => "时间有误"); } } else { $result = array('return' => 0, 'comment' => "验证失败,请检查URL"); } if ($Config['ReturnType']) { echo json_encode($result); } else { // $r = $result['return']."|".iconv('UTF-8','GBK',$result['comment']);; // if($result['return']==1) // { // $r = $r."|".$result['LoginId']."|".$result['adult']; // } // echo $r; } }
public static function processemail($emailsrc, $pdfout, $coverfile = '') { $combfilelist = array(); # Process the email $emailparts = Mail_mimeDecode::decode(array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => true, 'input' => file_get_contents($emailsrc), 'crlf' => "\r\n")); # Process the cover if it exists if ($coverfile !== '') { $combfilelist[] = self::processpart(file_get_contents($coverfile), mime_content_type($coverfile)); } # Process the parts $combfilelist = array_merge($combfilelist, self::processparts($emailparts)); # Create an intermediate file to build the pdf $tmppdffilename = sys_get_temp_dir() . '/e2p-' . (string) abs((int) (microtime(true) * 100000)) . '.pdf'; # Build the command to combine all of the intermediate files into one $conbcom = str_replace(array_merge(array('INTFILE', 'COMBLIST'), array_keys(self::$driver_paths)), array_merge(array($tmppdffilename, implode(' ', $combfilelist)), array_values(self::$driver_paths)), self::$mime_drivers['gs']); exec($conbcom); # Remove the intermediate files foreach ($combfilelist as $combfilename) { unlink($combfilename); } # Write the intermediate file to the final destination $intfileres = fopen($tmppdffilename, 'rb'); $outfileres = fopen($pdfout, 'ab'); while (!feof($intfileres)) { fwrite($outfileres, fread($intfileres, 8192)); } fclose($intfileres); fclose($outfileres); # Remove the intermediate file unlink($tmppdffilename); }
/** * _read * * @param int $bytes Bytes to read * * @access private * @return mixed */ function _read($bytes = 1) { if (0 < ($bytes = abs($bytes))) { return fread($this->_handle, $bytes); } return null; }
public function getFitness() { for ($diff = 0, $i = 0; $i < strlen($this->data); $i++) { $diff += abs(ord($this->data[$i]) - ord($this->solution[$i])); } return $diff; }