/** * @param mixed $value * @return mixed */ public function filterValue($value) { $lengthValue = strlen($value); // Calc the number of chars to replace $percentage = $this->getConfigPercent(); // Check if we have to replace anything at all if ($percentage == 0) { return $value; } $numReplaceChars = $lengthValue / (100 / $percentage); $numReplaceChars = round($numReplaceChars); // If there are no chars to be replaced return if ($numReplaceChars == 0) { return $value; } // Calc the char pos to start with $start = round(($lengthValue - $numReplaceChars) / 2); // Generate the mask $mask = str_repeat(self::MASK_CHAR, $numReplaceChars); if ($numReplaceChars == $lengthValue) { $start = 0; } // Replace the calculated part with mask $maskedNumber = substr_replace($value, $mask, $start, $numReplaceChars); return $maskedNumber; }
public function script_loader_tag($tag, $handle, $src) { if (!is_ssl() || $this->is_same_origin($src)) { return $tag; } $parsed_url = wp_parse_url($src); // Bad URL. if (!isset($parsed_url['host'])) { return $tag; } // @todo Retest google maps... Doesn't seem like it should be a problem. // @todo Filterable list of domains to ignore? if ('fonts.googleapis.com' === $parsed_url['host'] || 'maps.googleapis.com' === $parsed_url['host']) { return $tag; } // Null or string. if (!($metadata = $this->meta->get($src))) { $this->maybe_add_to_queue($src); return $tag; } $integrity_string = sprintf(' integrity="%s" crossorigin="anonymous"', esc_attr($metadata)); /** * To insert just after the opening tag. * * @todo Breaks if you use wp_add_inline_script( '*', '*', 'before' ). */ $pos = 0 === strpos($tag, '<script') ? 7 : 5; return substr_replace($tag, $integrity_string, $pos, 0); }
public static function autoload($class) { $filename = self::_autoloaderClassToFile($class); if (!$filename) { return false; } $proLocation = substr_replace(BETTER_ANALYTICS_PLUGIN_DIR, '-pro', -1); $allowed = false; if (file_exists($proLocation . $filename)) { $betterAnalyticsInternal = get_transient('ba_int'); if (@$betterAnalyticsInternal['v'] || strpos(@$_SERVER['SCRIPT_NAME'], '/plugins.php') !== false || strpos(@$_SERVER['SCRIPT_NAME'], '/tools.php') !== false || $class == 'DigitalPointBetterAnalytics_Helper_Api') { $allowed = true; } } if ($allowed) { include $proLocation . $filename; return class_exists($class, false) || interface_exists($class, false); } $ecommerceLocation = substr_replace(BETTER_ANALYTICS_PLUGIN_DIR, '-ecommerce', -1); if (file_exists($ecommerceLocation . $filename)) { include $ecommerceLocation . $filename; return class_exists($class, false) || interface_exists($class, false); } elseif (file_exists(BETTER_ANALYTICS_PLUGIN_DIR . $filename)) { include BETTER_ANALYTICS_PLUGIN_DIR . $filename; return class_exists($class, false) || interface_exists($class, false); } }
function replace_param($string, $data) { /** * parse query */ if ($string) { while (true) { preg_match("\$\\{(.*?)\\}\$", $string, $matches, PREG_OFFSET_CAPTURE); if (!count($matches)) { break; } $entry = $matches[0]; $type = $matches[1][0]; if (is_array($data)) { if (array_key_exists($type, $data)) { $string = substr_replace($string, $data[$type], $entry[1], strlen($entry[0])); } else { $string = substr_replace($string, "", $entry[1], strlen($entry[0])); } } else { $string = substr_replace($string, $data, $entry[1], strlen($entry[0])); } } } return $string; }
public function postflight(){ define('_FM_COM', 'com_profiles'); if(!defined('DS')) define('DS',DIRECTORY_SEPARATOR); $lang = JFactory::getLanguage(); define('_MY_LANGUAGE',$lang->getTag()); define('_CLOSE_HREF','index.php'); $ABSOLUTE_URI = (getenv('HTTPS') == 'on') ? substr_replace( str_replace("http://", "https://", JURI::base() ), '', -1, 1) : substr_replace(JURI::base(), '', -1, 1) . "/"; define('_FM_ABSOLUTE_URI',$ABSOLUTE_URI); define('_FM_HOME_URL', "index.php?option="._FM_COM."&format=raw"); define('_FM_HOME_FOLDER','components/'._FM_COM.'/filemanager'); define('_FM_HOME_DIR', JPATH_ROOT . '/administrator/components/'._FM_COM.'/filemanager'); define('_FM_LANGUAGE_DIR', _FM_HOME_DIR. DS.'languages'); define('_FM_COOKIE_EXPIRE', time()+60*60*24*60); // Define Peer define('_FM_PEER','joomla'); require_once _FM_HOME_DIR . DS . 'classes'.DS.'file.php'; require_once _FM_HOME_DIR . DS . 'classes'.DS.'text.php'; require_once _FM_HOME_DIR . DS .'includes'.DS.'version.php'; $infoTemplates = _FM_HOME_DIR . DS ."languages" . DS . "info"; $infoPath = $infoTemplates . DS . _MY_LANGUAGE . ".php" ; if(!MFile::is($infoPath)){ $infoPath = $infoTemplates . DS . "en-GB.php"; } $isWelcome = 1; $jed = null; $version=null; require_once $infoPath; } //EOF install
function __autoload($Class) { $root = str_replace("/", DIRECTORY_SEPARATOR, dirname($_SERVER['SCRIPT_FILENAME'])); $ClassExtension = $Class . ".class.php"; /* * Faz uma listagem de diretórios diretórios. * * A seguir é feita um verificação em todos os caminhos (arquivos) para * confirmar se existe o nome da classe chamada em algum deles. * * * * Se for achado a string da $ClassExtension no $file (caminho), será * chamado o include_once; */ $root = isset($root) ? $root : '.'; // Coloque o caminho raiz! $root = $root[strlen($root) - 1] == '\\' || $root[strlen($root) - 1] == '/' ? $root : $root . DIRECTORY_SEPARATOR; $empytfile = null; $car = "*"; $glob = glob($car, GLOB_MARK); while (!empty(glob($car, GLOB_MARK))) { if (!empty($FileClass = glob(substr_replace($car, "", -1) . $ClassExtension))) { include_once $root . $FileClass[0]; //var_dump($root.$FileClass[0]); $empytfile = true; } $car = $car . "\\*"; } if (!$empytfile) { trigger_error("A Classe <b><u>{$Class}</u></b> não existe.", E_USER_ERROR); die; } }
/** * @param Less_Functions $ctx */ public function compile($ctx) { $val = $this->value->compile($ctx); if (!$this->isEvald) { // Add the base path if the URL is relative if (Less_Parser::$options['relativeUrls'] && $this->currentFileInfo && is_string($val->value) && Less_Environment::isPathRelative($val->value)) { $rootpath = $this->currentFileInfo['uri_root']; if (!$val->quote) { $rootpath = preg_replace('/[\\(\\)\'"\\s]/', '\\$1', $rootpath); } $val->value = $rootpath . $val->value; } $val->value = Less_Environment::normalizePath($val->value); } // Add cache buster if enabled if (Less_Parser::$options['urlArgs']) { if (!preg_match('/^\\s*data:/', $val->value)) { $delimiter = strpos($val->value, '?') === false ? '?' : '&'; $urlArgs = $delimiter . Less_Parser::$options['urlArgs']; $hash_pos = strpos($val->value, '#'); if ($hash_pos !== false) { $val->value = substr_replace($val->value, $urlArgs, $hash_pos, 0); } else { $val->value .= $urlArgs; } } } return new Less_Tree_URL($val, $this->currentFileInfo, true); }
public function parse($sQuery) { //Test the query for validity $iBracesCounter = 0; $iLength = strlen($sQuery); for ($i = 0; $i < $iLength; $i++) { $cCurrent = substr($sQuery, $i, 1); switch ($cCurrent) { case "(": $iBracesCounter++; break; case ")": $iBracesCounter--; break; } if ($iBracesCounter < 0) { throw new Exception("Error in BooleanParser->parse: query not well-formed"); } } if ($iBracesCounter != 0) { throw new Exception("Error in BooleanParser->parse: query not well-formed"); } while (strpos($sQuery, "(") !== false) { $aBrace = $this->getInnermostBrace($sQuery); $sResult = $this->booleanTextForSimpleExpression($aBrace['inner_query']); $sQuery = substr_replace($sQuery, $sResult, $aBrace['start'], $aBrace['length']); } return $this->booleanForSimpleExpression($sQuery); }
public static function list_folder_files($dir) { $dir_name = $dir; if (!functions::is_empty_dir($dir)) { $files = scandir($dir, 0); $filename = ''; $filesize = ''; for ($ctr = 1; $ctr < sizeof($files); $ctr++) { if ($files[$ctr] != "." && $files[$ctr] != "..") { /*$folder_files = array( 'filename' => $files[$ctr], 'filesize' => $this->formatfilesize(filesize($dir.$files[$ctr])), );*/ $i = $ctr . ','; /*if(!is_dir($dir.'/'.$files[$ctr])){ $filename .= $files[$ctr].','; }*/ if (is_dir($dir . '/' . $files[$ctr])) { $filename .= $files[$ctr] . ' [FOLDER],'; } else { $filename .= $files[$ctr] . ','; } //$filename .= $files[$ctr].','; //$filesize .= $this->formatfilesize(filesize($dir.$files[$ctr])).','; } } $exploded_i = explode(',', substr_replace($i, '', -1)); $exploded_filename = explode(',', substr_replace($filename, '', -1)); $exploded_filesize = explode(',', substr_replace($filesize, '', -1)); return $exploded_filename; } else { return array(); } }
protected function getTokens($code) { if ($this->lfLineEndings && false !== strpos($code, "\r")) { $code = str_replace("\r\n", "\n", $code); $code = strtr($code, "\r", "\n"); } if ($this->checkUtf8 && !preg_match('//u', $code)) { $this->setError("File encoding is not valid UTF-8", E_USER_WARNING); } if ($this->stripUtf8Bom && 0 === strncmp($code, "", 3)) { // substr_replace() is for mbstring overloading resistance $code = substr_replace($code, '', 0, 3); $this->setError("Stripping UTF-8 Byte Order Mark", E_USER_NOTICE); } if ('' === $code) { return array(); } $code = parent::getTokens($code); // Ensure that the first token is always a T_OPEN_TAG if (T_INLINE_HTML === $code[0][0]) { $a = $code[0][1]; $a = "\r" === $a[0] ? isset($a[1]) && "\n" === $a[1] ? '\\r\\n' : '\\r' : ("\n" === $a[0] ? '\\n' : ''); if ($a) { array_unshift($code, array(T_OPEN_TAG, '<?php '), array(T_ECHO, 'echo'), array(T_ENCAPSED_AND_WHITESPACE, "\"{$a}\""), array(T_CLOSE_TAG, '?>')); } else { array_unshift($code, array(T_OPEN_TAG, '<?php '), array(T_CLOSE_TAG, '?>')); } } // Ensure that the last valid PHP code position is tagged with a T_ENDPHP $a = array_pop($code); $code[] = T_CLOSE_TAG === $a[0] ? ';' : $a; T_INLINE_HTML === $a[0] && ($code[] = array(T_OPEN_TAG, '<?php ')); $code[] = array(T_ENDPHP, ''); return $code; }
/** * Load the file for a class * * @param string $class The class that will be loaded * @return boolean True on success */ public static function loadClass($class) { // pre-empt further searching for the named class or interface. // do not use autoload, because this method is registered with // spl_autoload already. if (class_exists($class, false) || interface_exists($class, false)) { return; } // if class start with a 'Nooku' it is a Nooku class. // create the path and register it with the loader. switch (substr($class, 0, 6)) { case 'Picman': $word = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', substr_replace($class, '', 0, 6))); $parts = explode('_', $word); if (count($parts) > 1) { $path = KInflector::pluralize(array_shift($parts)) . DS . implode(DS, $parts); } else { $path = $word; } if (is_file(dirname(__FILE__) . DS . $path . '.php')) { KLoader::register($class, dirname(__FILE__) . DS . $path . '.php'); } break; } $classes = KLoader::register(); if (array_key_exists(strtolower($class), $classes)) { include $classes[strtolower($class)]; return true; } return false; }
private function buildModifiedFile() { $data = $this->getUnmodifiedFileContent(); foreach ($this->lintResult->getMessages() as $lint) { if (!$lint->isPatchable()) { continue; } $orig_offset = $this->getCharacterOffset($lint->getLine() - 1); $orig_offset += $lint->getChar() - 1; $dirty = $this->getDirtyCharacterOffset(); if ($dirty > $orig_offset) { continue; } // Adjust the character offset by the delta *after* checking for // dirtiness. The dirty character cursor is a cursor on the original file, // and should be compared with the patch position in the original file. $working_offset = $orig_offset + $this->getCharacterDelta(); $old_str = $lint->getOriginalText(); $old_len = strlen($old_str); $new_str = $lint->getReplacementText(); $new_len = strlen($new_str); if ($working_offset == strlen($data)) { // Temporary hack to work around a destructive hphpi issue, see #451031. $data .= $new_str; } else { $data = substr_replace($data, $new_str, $working_offset, $old_len); } $this->changeCharacterDelta($new_len - $old_len); $this->setDirtyCharacterOffset($orig_offset + $old_len); $this->applyMessages[] = $lint; } $this->modifiedData = $data; }
public function __construct(array $params = null) { //All child class need to have constant UUID_CLASS_PREFIX to create uuid prefix if (!defined(get_class($this) . '::UUID_CLASS_PREFIX')) { throw new \Exception("Class " . get_class($this) . " has missing UUID_CLASS_PREFIX constant."); } //bind array values to class properties if ($params) { foreach ($params as $key => $value) { if (property_exists($this, $key)) { $this->{$key} = $value; } } } //Add uuid if not exists for new created object if (property_exists($this, 'uuid')) { if (!$this->uuid) { $uuid = Uuid::uuid4()->toString(); //Add uuid prefix (defined in UUID_CLASS_PREFIX constant) by replacing first x characters. Where x is prefix length. $prefix_length = strlen($this::UUID_CLASS_PREFIX); $uuid = substr_replace($uuid, $this::UUID_CLASS_PREFIX, 0, $prefix_length); $this->uuid = $uuid; } } }
/** * @param string $propertyPath * @return string */ private function fixPropertyPath($propertyPath) { if ($propertyPath[0] != '[') { $propertyPath = '[' . substr_replace($propertyPath, ']', strpos($propertyPath, '[') ?: strlen($propertyPath), 0); } return str_replace('[]', '', $propertyPath); }
function __js_wrap_quote($str, $max_line_length) { $max_line_length -= 3; $inQ = false; $esc = 0; $lineLen = 0; $result = ''; $chunk = ''; while (strlen($str) > 0) { if (preg_match('/^\\\\[0-7]{3}/i', $str)) { $chunk = substr($str, 0, 3); $str = substr_replace($str, '', 0, 3); } elseif (preg_match('/^\\\\./i', $str)) { $chunk = substr($str, 0, 2); $str = substr_replace($str, '', 0, 2); } else { $chunk = substr($str, 0, 1); $str = substr_replace($str, '', 0, 1); } if ($lineLen + strlen($chunk) >= $max_line_length) { $result .= '"+' . "\n" . '"'; $lineLen = 1; } $lineLen += strlen($chunk); $result .= $chunk; } return $result; }
/** * Gravatar * * This function returns the url of a gravatar image. * * @access public * @return string */ function Gravatar() { $this->EE =& get_instance(); $rating = $this->EE->TMPL->fetch_param('rating'); $size = $this->EE->TMPL->fetch_param('size'); $default = $this->EE->TMPL->fetch_param('default'); $email = $this->EE->TMPL->fetch_param('email'); $name = $this->EE->TMPL->fetch_param('name'); if ($email == "" && $name != "") { $results = $this->EE->db->query("SELECT email FROM exp_members WHERE screen_name = '" . $this->EE->db->escape_str($name) . "'"); $results = $results->row('email'); $email = is_array($results) ? '*****@*****.**' : $results; } $grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower($email)) . "?"; if ($size && $size != '') { $grav_url .= "s=" . $size . "&"; } if ($rating && $rating != '') { $grav_url .= "r=" . $rating . "&"; } if ($default && $default != '') { $grav_url .= "d=" . $default . "&"; } $grav_url = substr_replace($grav_url, "", -1); $this->return_data = $grav_url; }
protected function _addColumnFilterToCollection($column) { if ($column->getId() == 'zip') { $value = $column->getFilter()->getValue(); if (!is_numeric($value)) { $state = addslashes(strtoupper(substr($value, -2))); $city = addslashes(substr_replace($value, "", -4)); $zipArr = Mage::getModel('urls/cities')->getCityZips($city, $state); $field = $column->getFilterIndex() ? $column->getFilterIndex() : $column->getIndex(); $this->getCollection()->addAttributeToFilter($field, array('in' => $zipArr)); return $this; } } // Set custom filter for in category flag if ($column->getId() == 'in_category') { $productIds = $this->_getSelectedProducts(); if (empty($productIds)) { $productIds = 0; } if ($column->getFilter()->getValue()) { $this->getCollection()->addFieldToFilter('entity_id', array('in' => $productIds)); } elseif (!empty($productIds)) { $this->getCollection()->addFieldToFilter('entity_id', array('nin' => $productIds)); } } else { parent::_addColumnFilterToCollection($column); } return $this; }
/** * Combines multiple font-definitions into single definition * * @param (string) val: Rule Set */ public function combine( $val ) { $storage = $this->storage( $val ); // Loop through each property check and see if they can be replaced foreach ( $this->groupings as $props ) { if ( $replace = $this->Combine->searchDefinitions( 'font', $storage, $props ) ) { break; } } // If replacement string found, run it on all declarations if ( $replace ) { $pos = 0; while ( preg_match( $this->rfont, $val, $match, PREG_OFFSET_CAPTURE, $pos ) ) { if ( ! isset( $storage['line-height'] ) && stripos( $match[ 0 ][ 0 ], 'line-height') === 0 ) { $pos = $match[ 0 ][ 1 ] + strlen( $match[ 0 ][ 0 ] ) - 1; continue; } $colon = strlen( $match[ 1 ][ 0 ] ); $val = substr_replace( $val, $replace, $match[ 0 ][ 1 ] + $colon, strlen( $match[ 0 ][ 0 ] ) - $colon ); $pos = $match[ 0 ][ 1 ] + strlen( $replace ) - $colon - 1; $replace = ''; } } // Return converted val return $val; }
function sms_board_handle($c_uid, $sms_datetime, $sms_sender, $sms_receiver, $board_keyword, $board_param = '') { global $web_title, $email_service, $email_footer, $gateway_module, $datetime_now; $ok = false; if ($sms_sender && $board_keyword && $board_param) { // masked sender sets here $masked_sender = substr_replace($sms_sender, 'xxxx', -4); $db_query = "\n\t INSERT INTO " . _DB_PREF_ . "_featureBoard_log \n\t (in_gateway,in_sender,in_masked,in_keyword,in_msg,in_datetime) \n\t VALUES ('{$gateway_module}','{$sms_sender}','{$masked_sender}','{$board_keyword}','{$board_param}','{$datetime_now}')\n\t"; if ($cek_ok = @dba_insert_id($db_query)) { $db_query1 = "SELECT board_forward_email FROM " . _DB_PREF_ . "_featureBoard WHERE board_keyword='{$board_keyword}'"; $db_result1 = dba_query($db_query1); $db_row1 = dba_fetch_array($db_result1); $email = $db_row1['board_forward_email']; if ($email) { // get name from c_uid's phonebook $c_username = uid2username($c_uid); $c_name = phonebook_number2name($sms_sender, $c_username); $sms_sender = $c_name ? $c_name . ' <' . $sms_sender . '>' : $sms_sender; $subject = "[SMSGW-" . $board_keyword . "] " . _('from') . " {$sms_sender}"; $body = _('Forward WebSMS') . " ({$web_title})\n\n"; $body .= _('Date and time') . ": {$sms_datetime}\n"; $body .= _('Sender') . ": {$sms_sender}\n"; $body .= _('Receiver') . ": {$sms_receiver}\n"; $body .= _('Keyword') . ": {$board_keyword}\n\n"; $body .= _('Message') . ":\n{$board_param}\n\n"; $body .= $email_footer . "\n\n"; sendmail($email_service, $email, $subject, $body); } $ok = true; } } return $ok; }
private function applyTransformationsToReachTarget($currentMolecule) { if ($currentMolecule == $this->molecule) { return 0; } $minSteps = PHP_INT_MAX; $transformationsNormalised = []; foreach ($this->transformations as $source => $transformationsForSource) { foreach ($transformationsForSource as $transformation) { $transformationsNormalised[] = ['source' => $source, 'transformation' => $transformation]; } } usort($transformationsNormalised, function ($a, $b) { return strlen($b['transformation']) - strlen($a['transformation']); }); foreach ($transformationsNormalised as $transformationNormalised) { $source = $transformationNormalised['source']; $transformation = $transformationNormalised['transformation']; for ($offset = 0; ($index = strpos($currentMolecule, $transformation, $offset)) !== false; $offset = $index + 1) { if ($minSteps == PHP_INT_MAX || $minSteps < self::$minFoundSoFar) { return $this->applyTransformationsToReachTarget(substr_replace($currentMolecule, $source, $index, strlen($transformation))) + 1; } } } return $minSteps; }
public function generate() { //Get ref file content $refFile = __DIR__ . "/ngTableExtendsReference.php"; if (!file_exists($refFile)) { throw new \Exception('The reference file "' . $refFile . '" used to generate a ngTable doean\'t exists!'); } if (!($content = file_get_contents($refFile))) { throw new \Exception('The reference file "' . $refFile . '" cannot be read!'); } //var_dump($this->metaData); //Set every thing to generate the file and get infos as namespace.. $ngTableNameSpace = str_replace('\\Entity', '', $this->metaData->namespace) . '\\NgTable'; $ngTableDir = $this->kernel->getRootDir() . '/../src/' . $ngTableNameSpace; $entityName = explode('\\', $this->metaData->rootEntityName); $entityName = end($entityName); $ngTableClassName = 'NgTable' . $entityName; $ngTableFile = $ngTableDir . '\\' . $ngTableClassName . '.php'; if (file_exists($ngTableFile)) { throw new \Exception('The ngTable already Exists! (' . $ngTableFile . ')'); } if (!file_exists($ngTableDir)) { if (!mkdir($ngTableDir, 0777, true)) { throw new \Exception('Impossible to create a new directory for generated ngTable!'); } } //edit content $content = str_replace('/* {{namespace}} */', $ngTableNameSpace, $content); $content = str_replace('/* {{className}} */', $ngTableClassName, $content); $dateStart = '/* {{DateTimeCallBackStarts}}'; $dateEnd = '{{DateTimeCallBackEnds}} */'; $dateTimeRefStart = strpos($content, $dateStart); $dateTimeRefEnd = strpos($content, $dateEnd); $dateTimeRef = substr($content, $dateTimeRefStart + strlen($dateStart), $dateTimeRefEnd - strlen($dateEnd) - $dateTimeRefStart - 2); $content = preg_replace('#\\/\\* \\{\\{DateTimeCallBackStarts[^\\*]+\\*\\/#', '', $content); $setRow = '$this'; $fields = array_merge($this->metaData->fieldMappings, $this->parentMetaData->fieldMappings); foreach ($fields as $fieldName => $fieldValues) { if ($fieldValues['type'] == 'datetime') { $dateTimeRefCustomed = $dateTimeRef; $dateTimeRefCustomed = str_replace('keyName', $fieldName, $dateTimeRefCustomed); $content = substr_replace($content, $dateTimeRefCustomed, $dateTimeRefStart, 0); } //addrow $type = 'NGTABLE_TEXT'; if ($fieldValues['type'] == 'integer' || $fieldValues['type'] == 'float' || $fieldValues['type'] == 'smallint' || $fieldValues['type'] == 'bigint') { $type = 'NGTABLE_NUMBER'; } $setRow .= "\n\t\t\t->createRow()\n\t\t\t\t->setTitle('" . $fieldName . "')\n\t\t\t\t->setDataKey('" . $fieldName . "')\n\t\t\t\t->setType(ngTableRow::" . $type . ")\n\t\t\t->add()\n\t\t\t"; } $setRow .= ';'; $setRowPos = strpos($content, '/* {{setRows}} */'); $content = str_replace('/* {{setRows}} */', '', $content); $content = substr_replace($content, $setRow, $setRowPos, 0); //save the file if (!file_put_contents($ngTableFile, $content)) { throw new \Exception('Impossible to create the ngTable file!'); } return "The file '" . $ngTableFile . "' was generate with success."; }
function latex_content($text) { global $config; // -------------------------------------------------------------------------------------------------- // adjust this to match your system configuration $latexrender_path = dirname(__FILE__); $latexrender_path_http = $config["base_path"] . "/functions/latexrender"; // -------------------------------------------------------------------------------------------------- include_once $latexrender_path . "/class.latexrender.php"; preg_match_all("#\\[tex\\](.*?)\\[/tex\\]#si", $text, $tex_matches); $latex = new LatexRender($latexrender_path . "/pictures", $latexrender_path_http . "/pictures", $latexrender_path . "/tmp"); for ($i = 0; $i < count($tex_matches[0]); $i++) { $pos = strpos($text, $tex_matches[0][$i]); $latex_formula = $tex_matches[1][$i]; // if you use htmlArea to input the text then uncomment the next 6 lines $latex_formula = str_replace("&", "&", $latex_formula); $latex_formula = str_replace("&", "&", $latex_formula); $latex_formula = str_replace(" ", " ", $latex_formula); $latex_formula = str_replace("<BR>", "", $latex_formula); $latex_formula = str_replace("<P>", "", $latex_formula); $latex_formula = str_replace("</P>", "", $latex_formula); $url = $latex->getFormulaURL($latex_formula); $alt_latex_formula = htmlentities($latex_formula, ENT_QUOTES); $alt_latex_formula = str_replace("\r", " ", $alt_latex_formula); $alt_latex_formula = str_replace("\n", " ", $alt_latex_formula); if ($url != false) { $text = substr_replace($text, "<img src='" . $url . "' title='" . $alt_latex_formula . "' alt='" . $alt_latex_formula . "' align=absmiddle>", $pos, strlen($tex_matches[0][$i])); } else { $text = substr_replace($text, "[Unparseable or potentially dangerous latex formula. Error {$latex->_errorcode} {$latex->_errorextra}]", $pos, strlen($tex_matches[0][$i])); } } return $text; }
/** * Trim query string from request uri. * * @param string $value * @return string */ private function trimQuery($value = '') { if (strpos($value, '?') !== false) { return substr_replace($value, '', strpos($value, '?')); } return $value; }
function SimplePie_Unit_Test2() { parent::Unit_Test2(); if (strpos($this->name, 'SimplePie') === 0) { $this->name = trim(substr_replace($this->name, '', 0, 9)); } }
public static function titleCase($title) { //remove HTML, storing it for later // HTML elements to ignore | tags | entities $regx = '/<(code|var)[^>]*>.*?<\\/\\1>|<[^>]+>|&\\S+;/'; preg_match_all($regx, $title, $html, PREG_OFFSET_CAPTURE); $title = preg_replace($regx, '', $title); //find each word (including punctuation attached) preg_match_all('/[\\w\\p{L}&`\'‘’"“\\.@:\\/\\{\\(\\[<>_]+-? */u', $title, $m1, PREG_OFFSET_CAPTURE); foreach ($m1[0] as &$m2) { //shorthand these- "match" and "index" list($m, $i) = $m2; //correct offsets for multi-byte characters (`PREG_OFFSET_CAPTURE` returns *byte*-offset) //we fix this by recounting the text before the offset using multi-byte aware `strlen` $i = mb_strlen(substr($title, 0, $i), 'UTF-8'); //find words that should always be lowercase… //(never on the first word, and never if preceded by a colon) $m = $i > 0 && mb_substr($title, max(0, $i - 2), 1, 'UTF-8') !== ':' && preg_match('/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\\.?|via)[ \\-]/i', $m) ? mb_strtolower($m, 'UTF-8') : (preg_match('/[\'"_{(\\[‘“]/u', mb_substr($title, max(0, $i - 1), 3, 'UTF-8')) ? mb_substr($m, 0, 1, 'UTF-8') . mb_strtoupper(mb_substr($m, 1, 1, 'UTF-8'), 'UTF-8') . mb_substr($m, 2, mb_strlen($m, 'UTF-8') - 2, 'UTF-8') : (preg_match('/[\\])}]/', mb_substr($title, max(0, $i - 1), 3, 'UTF-8')) || preg_match('/[A-Z]+|&|\\w+[._]\\w+/u', mb_substr($m, 1, mb_strlen($m, 'UTF-8') - 1, 'UTF-8')) ? $m : mb_strtoupper(mb_substr($m, 0, 1, 'UTF-8'), 'UTF-8') . mb_substr($m, 1, mb_strlen($m, 'UTF-8'), 'UTF-8'))); //resplice the title with the change (`substr_replace` is not multi-byte aware) $title = mb_substr($title, 0, $i, 'UTF-8') . $m . mb_substr($title, $i + mb_strlen($m, 'UTF-8'), mb_strlen($title, 'UTF-8'), 'UTF-8'); } //restore the HTML foreach ($html[0] as &$tag) { $title = substr_replace($title, $tag[0], $tag[1], 0); } return $title; }
public function crossover($partner, $options = array()) { $a = $partner->get_data(); $b = $this->data; $a_c = strlen($a); $b_c = strlen($b); $c = ''; $c_c = $a_c >= $b_c ? $a_c : $b_c; // if it has same length, great!, use std algorithm if ($a_c == $b_c) { $left = mt_rand(0, 1) == 1 ? $a : $b; $right = $left == $b ? $a : $b; $sp = mt_rand(0, $c_c); $c .= substr($left, 0, $sp); $c .= substr($right, $sp); } else { /* * put shorter chromosome, in longer chromosome * example: * a: aaaa * b: bb * result: aabb OR abba OR bbaa * */ $longer = $c_c == $a_c ? 'a' : 'b'; $shorter = $longer == 'b' ? 'a' : 'b'; $sp_begin = mt_rand(0, ${$longer . '_c'} - ${$shorter . '_c'}); $tmp = substr_replace(${$longer}, ${$shorter}, -$sp_begin); $c .= $tmp . substr(${$longer}, strlen($tmp)); } $class_name = get_called_class(); return new $class_name($c); }
/** * Generates an INSERT query with placeholders for values and optional OUTPUT clause * @param string $table * @param array $colVals An associative array of columns/values to insert * @param bool $useOutputClause * @return SqlParams */ public function buildQuery($table, array $colVals, $useOutputClause = false) { self::validateColValsStructure($colVals); $columns = $this->escapeColumns(array_keys($colVals[0])); $insert = "INSERT INTO {$table} (" . implode(', ', $columns) . ')'; $valSetStr = ' (' . str_repeat('?,', count($columns) - 1) . '?),'; $valStr = ' VALUES' . substr_replace(str_repeat($valSetStr, count($colVals)), '', -1); // remove trailing comma $params = call_user_func_array('array_merge', array_map('array_values', $colVals)); $idCol = $decStr = $outStr = $selStr = ''; if ($this->options instanceof \PeachySQL\SqlServer\Options) { if ($useOutputClause) { $idCol = $this->options->getIdColumn(); } else { $selStr = '; SELECT SCOPE_IDENTITY() AS RowID;'; } } // Insert IDs must be output into a table variable so that the query will work on tables // with insert triggers (see http://technet.microsoft.com/en-us/library/ms177564.aspx). if ($idCol !== '') { $decStr = 'DECLARE @ids TABLE(RowID int); '; $outStr = " OUTPUT inserted.{$idCol} INTO @ids(RowID)"; $selStr = '; SELECT * FROM @ids;'; } return new SqlParams($decStr . $insert . $outStr . $valStr . $selStr, $params); }
public static function autoQuote($query, array $args) { $i = strlen($query) - 1; $c = count($args); while ($i--) { if ('?' === $query[$i] && false !== ($type = strpos('sia', $query[$i + 1]))) { if (--$c < 0) { throw new InvalidArgumentException('Too little parameters.'); } if (0 === $type) { $replace = self::instance()->quote($args[$c]); } elseif (1 === $type) { $replace = intval($args[$c]); } elseif (2 === $type) { foreach ($args[$c] as &$value) { $value = self::instance()->quote($value); } $replace = '(' . implode(',', $args[$c]) . ')'; } $query = substr_replace($query, $replace, $i, 2); } } if ($c > 0) { throw new InvalidArgumentException('Too many parameters.'); } return $query; }
/** * Creates a stylesheet link with LESS support * * @param string $style file name * @param array $attributes default attributes * @param bool $index include the index page * @param array $imports compare file date for these too, CSS and LESS in style @import * @return string */ public static function style($file, array $attributes = null, $index = false, $imports = null) { $imports = (array) $imports; // Compile only .less files if (substr_compare($file, '.less', -5, 5, false) === 0) { $css = substr_replace($file, 'css', -4); $compiled = is_file($css) ? filemtime($css) : 0; try { // Check if imported files have changed $compile = filemtime($file) > $compiled; if (!$compile && !empty($imports)) { foreach ($imports as $import) { if (filemtime($import) > $compiled) { $compile = true; break; } } } // Compile LESS if ($compile) { $compiler = new self($file); file_put_contents($css, $compiler->parse()); } $file = $css; } catch (Exception $e) { Kohana::$log->add(Kohana::ERROR, __METHOD__ . ': Error compiling LESS file ' . $file . ', ' . $e->getMessage()); } } return HTML::style($file . '?' . filemtime($file), $attributes, $index); }
/** * Ver una query con sus parámetros * * @param string $sql * @param array $params * @return string */ function verQuery($sql, $params) { $count = substr_count($sql, "?"); $element = count($params); $index = $element - $count; $error = ""; if ($index > 0) { $error = "Hay mas parámetros que interrogaciones.\n"; $index1 = $element - $count; for ($i = 0; $i < $index1; $i++) { array_pop($params); } } elseif ($resultado = $index < 0) { $error = "Hay menos parámetros que interrogaciones.\n"; } foreach ($params as $value) { $posicion = strpos($sql, "?"); if (gettype($value) == "string") { $sql = substr_replace($sql, "'" . $value . "'", $posicion, 1); } else { $sql = substr_replace($sql, $value, $posicion, 1); } } return $error . $sql; }