PHP Функция preg_replace - примеры использования

На этой странице представлены лучшие примеры PHP кода для метода preg_replace, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Пример #1
Показать файл Файл: codebase.php Проект: phill104/branches
0
function fit_screen_html_image($pic_html)
{
    $pic_html = preg_replace('/<a.*>/Ui', '', $pic_html);
    $pic_html = str_replace('</a>', '', $pic_html);
    $pic_html = str_replace('<img ', '<img id="thepic" onLoad="scaleImg();" onClick="showOnclick();" ', $pic_html);
    return $pic_html;
}
Пример #2
Показать файл Файл: QuickUpload.php Проект: knieper/crltmich
0
 /**
  * Throw file upload error, return true if error has been thrown, false if error has been catched
  *
  * @param int $number
  * @param string $text
  * @access public
  */
 function throwError($number, $uploaded = false, $exit = true)
 {
     if ($this->_catchAllErrors || in_array($number, $this->_skipErrorsArray)) {
         return false;
     }
     $oRegistry =& CKFinder_Connector_Core_Factory::getInstance("Core_Registry");
     $sFileName = $oRegistry->get("FileUpload_fileName");
     $sFileUrl = $oRegistry->get("FileUpload_url");
     header('Content-Type: text/html; charset=utf-8');
     /**
      * echo <script> is not called before CKFinder_Connector_Utils_Misc::getErrorMessage
      * because PHP has problems with including files that contain BOM character.
      * Having BOM character after <script> tag causes a javascript error.
      */
     echo "<script type=\"text/javascript\">";
     if (!empty($_GET['CKEditor'])) {
         $errorMessage = CKFinder_Connector_Utils_Misc::getErrorMessage($number, $sFileName);
         if (!$uploaded) {
             $sFileUrl = "";
             $sFileName = "";
         }
         $funcNum = preg_replace("/[^0-9]/", "", $_GET['CKEditorFuncNum']);
         echo "window.parent.CKEDITOR.tools.callFunction({$funcNum}, '" . str_replace("'", "\\'", $sFileUrl . $sFileName) . "', '" . str_replace("'", "\\'", $errorMessage) . "');";
     } else {
         if (!$uploaded) {
             echo "window.parent.OnUploadCompleted(" . $number . ", '', '', '') ;";
         } else {
             echo "window.parent.OnUploadCompleted(" . $number . ", '" . str_replace("'", "\\'", $sFileUrl . $sFileName) . "', '" . str_replace("'", "\\'", $sFileName) . "', '') ;";
         }
     }
     echo "</script>";
     if ($exit) {
         exit;
     }
 }
Пример #3
Показать файл Файл: c622f4449f839eae30100749d9028fed193e36649fffa3d6c16afda960015daa.php Проект: antoinelanglet/fortunes
0
 protected function doDisplay(array $context, array $blocks = array())
 {
     $__internal_2fff3160042f23d812f76a57f2d794df9c0021a111c64efc06751bf3f7b16428 = $this->env->getExtension("native_profiler");
     $__internal_2fff3160042f23d812f76a57f2d794df9c0021a111c64efc06751bf3f7b16428->enter($__internal_2fff3160042f23d812f76a57f2d794df9c0021a111c64efc06751bf3f7b16428_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "TwigBundle:Exception:traces_text.html.twig"));
     // line 1
     echo "<div class=\"block\">\n    <h2>\n        Stack Trace (Plain Text)&nbsp;\n        ";
     // line 4
     ob_start();
     // line 5
     echo "        <a href=\"#\" onclick=\"toggle('traces-text'); switchIcons('icon-traces-text-open', 'icon-traces-text-close'); return false;\">\n            <img class=\"toggle\" id=\"icon-traces-text-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: none\" />\n            <img class=\"toggle\" id=\"icon-traces-text-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: inline\" />\n        </a>\n        ";
     echo trim(preg_replace('/>\\s+</', '><', ob_get_clean()));
     // line 10
     echo "    </h2>\n\n    <div id=\"traces-text\" class=\"trace\" style=\"display: none;\">\n<pre>";
     // line 13
     $context['_parent'] = $context;
     $context['_seq'] = twig_ensure_traversable($this->getAttribute(isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception"), "toarray", array()));
     foreach ($context['_seq'] as $context["i"] => $context["e"]) {
         // line 14
         echo "[";
         echo twig_escape_filter($this->env, $context["i"] + 1, "html", null, true);
         echo "] ";
         echo twig_escape_filter($this->env, $this->getAttribute($context["e"], "class", array()), "html", null, true);
         echo ": ";
         echo twig_escape_filter($this->env, $this->getAttribute($context["e"], "message", array()), "html", null, true);
         echo "\n";
         // line 15
         $this->loadTemplate("TwigBundle:Exception:traces.txt.twig", "TwigBundle:Exception:traces_text.html.twig", 15)->display(array("exception" => $context["e"]));
     }
     $_parent = $context['_parent'];
     unset($context['_seq'], $context['_iterated'], $context['i'], $context['e'], $context['_parent'], $context['loop']);
     $context = array_intersect_key($context, $_parent) + $_parent;
     // line 16
     echo "</pre>\n    </div>\n</div>\n";
     $__internal_2fff3160042f23d812f76a57f2d794df9c0021a111c64efc06751bf3f7b16428->leave($__internal_2fff3160042f23d812f76a57f2d794df9c0021a111c64efc06751bf3f7b16428_prof);
 }
Пример #4
Показать файл Файл: exif.class.php Проект: vluo/myPoto
0
 function get_exif($file)
 {
     if (!function_exists('exif_read_data')) {
         return false;
     }
     $exif = @exif_read_data($file, "IFD0");
     if ($exif === false) {
         return false;
     }
     $exif_info = exif_read_data($file, NULL, true);
     $exif_arr = $this->supported_exif();
     $new_exif = array();
     foreach ($exif_arr as $k => $v) {
         $arr = explode('.', $v);
         if (isset($exif_info[$arr[0]])) {
             if (isset($exif_info[$arr[0]][$arr[1]])) {
                 $new_exif[$k] = $exif_info[$arr[0]][$arr[1]];
             } else {
                 $new_exif[$k] = false;
             }
         } else {
             $new_exif[$k] = false;
         }
         if ($k == 'Software' && !empty($new_exif['Software'])) {
             $new_exif['Software'] = preg_replace('/([^a-zA-Z0-9_\\-,\\.\\:&#@!\\(\\)\\s]+)/i', '', $new_exif['Software']);
         }
     }
     return $new_exif;
 }
Пример #5
Показать файл Файл: attachments.php Проект: Garth619/wines-by-jennifer
0
 /**
 		@brief		threewp_broadcast_apply_existing_attachment_action
 		@since		2015-11-16 14:10:32
 	**/
 public function threewp_broadcast_apply_existing_attachment_action($action)
 {
     if ($action->is_finished()) {
         return;
     }
     $bcd = $action->broadcasting_data;
     switch ($action->action) {
         case 'overwrite':
             // Delete the existing attachment
             $this->debug('Maybe copy attachment: Deleting current attachment %s', $action->target_attachment->ID);
             wp_delete_attachment($action->target_attachment->ID, true);
             // true = Don't go to trash
             // Tell BC to copy the attachment.
             $action->use = false;
             break;
         case 'randomize':
             $filename = $bcd->attachment_data->filename_base;
             $filename = preg_replace('/(.*)\\./', '\\1_' . rand(1000000, 9999999) . '.', $filename);
             $bcd->attachment_data->filename_base = $filename;
             $this->debug('Maybe copy attachment: Randomizing new attachment filename to %s.', $bcd->attachment_data->filename_base);
             // Tell BC to copy the attachment.
             $action->use = false;
             break;
     }
 }
Пример #6
Показать файл Файл: namebay.php Проект: jinguanio/whois
0
 public function remove_surplus($delimiter)
 {
     $body = preg_replace('/^.+\\n/', '', $this->body);
     if ($body) {
         $this->body = $body . "\n";
     }
 }
Пример #7
Показать файл Файл: embed-parser-base.php Проект: macconsultinggroup/WordPress
0
 /**
  * Extract embedded elements from a HTML string.
  * 
  * This function returns an array of <embed> elements found in the input
  * string. Embeds without a 'src' attribute are skipped.
  * 
  * Each array item has the same basic structure as the array items
  * returned by blcUtility::extract_tags(), plus an additional 'embed_code' key 
  * that contains the HTML code for the element. If the embed element is wrapped
  * in an <object>, the 'embed_code' key contains the full HTML for the entire
  * <object> + <embed> structure.
  *  
  * @uses blcUtility::extract_tags() This function is a simple wrapper around extract_tags()
  * 
  * @param string $html
  * @return array 
  */
 function extract_embeds($html)
 {
     $results = array();
     //remove all <code></code> blocks first
     $html = preg_replace('/<code[^>]*>.+?<\\/code>/si', ' ', $html);
     //Find likely-looking <object> elements
     $objects = blcUtility::extract_tags($html, 'object', false, true);
     foreach ($objects as $candidate) {
         //Find the <embed> tag
         $embed = blcUtility::extract_tags($candidate['full_tag'], 'embed', true);
         if (empty($embed)) {
             continue;
         }
         $embed = reset($embed);
         //Take the first (and only) found <embed> element
         if (empty($embed['attributes']['src'])) {
             continue;
         }
         $embed['embed_code'] = $candidate['full_tag'];
         $results[] = $embed;
         //Remove the element so it doesn't come up when we search for plain <embed> elements.
         $html = str_replace($candidate['full_tag'], ' ', $html);
     }
     //Find <embed> elements not wrapped in an <object> element.
     $embeds = blcUtility::extract_tags($html, 'embed', false, true);
     foreach ($embeds as $embed) {
         if (!empty($embed['attributes']['src'])) {
             $embed['embed_code'] = $embed['full_tag'];
             $results[] = $embed;
         }
     }
     return $results;
 }
Пример #8
Показать файл Файл: modifier.cut.php Проект: BGCX261/zhishuicms-svn-to-git
0
function smarty_modifier_cut($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
    global $cfg;
    if ($length == 0) {
        return '';
    }
    $string = preg_replace('/<[^>]*?>/', '', $string);
    $string = preg_replace('/&nbsp;/', '', $string);
    $string = preg_replace('/&quot;/', '"', $string);
    $string = preg_replace('/&rdquo;/', '"', $string);
    $string = preg_replace('/&ldquo;/', '"', $string);
    $string = preg_replace('/&[a-z]*;/', ' ', $string);
    $string = preg_replace('/\\s+/', '', $string);
    if (strlen($string) > $length) {
        $length -= strlen($etc);
        if (!$break_words && !$middle) {
            $string = preg_replace('/\\s+?(\\S+)?$/', '', mb_substr($string, 0, $length + 1, $cfg['mysql_charset']));
        }
        if (!$middle) {
            return mb_substr($string, 0, $length, $cfg['mysql_charset']) . $etc;
        } else {
            return mb_substr($string, 0, $length / 2, $cfg['mysql_charset']) . $etc . mb_substr($string, -$length / 2, $cfg['mysql_charset']);
        }
        return mb_substr($string, 0, $length, $cfg['mysql_charset']) . $etc;
    } else {
        return $string;
    }
}
Пример #9
Показать файл Файл: form.php Проект: Garrett-Sens/portfolio
0
 protected function is_blank($value)
 {
     if ($value === null || strlen($value) <= 0 || strlen(preg_replace('/\\s+/', '', $value)) <= 0) {
         return true;
     }
     return false;
 }
Пример #10
Показать файл Файл: Inline.php Проект: shinichi81/Codeigniter-TDD-with-Hooks
0
 /**
  * Converts a YAML string to a PHP array.
  *
  * @param string  $value                  A YAML string
  * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  * @param Boolean $objectSupport          true if object support is enabled, false otherwise
  *
  * @return array A PHP array representing the YAML string
  */
 public static function parse($value, $exceptionOnInvalidType = false, $objectSupport = false)
 {
     self::$exceptionOnInvalidType = $exceptionOnInvalidType;
     self::$objectSupport = $objectSupport;
     $value = trim($value);
     if (0 == strlen($value)) {
         return '';
     }
     if (function_exists('mb_internal_encoding') && (int) ini_get('mbstring.func_overload') & 2) {
         $mbEncoding = mb_internal_encoding();
         mb_internal_encoding('ASCII');
     }
     $i = 0;
     switch ($value[0]) {
         case '[':
             $result = self::parseSequence($value, $i);
             ++$i;
             break;
         case '{':
             $result = self::parseMapping($value, $i);
             ++$i;
             break;
         default:
             $result = self::parseScalar($value, null, array('"', "'"), $i);
     }
     // some comments are allowed at the end
     if (preg_replace('/\\s+#.*$/A', '', substr($value, $i))) {
         throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)));
     }
     if (isset($mbEncoding)) {
         mb_internal_encoding($mbEncoding);
     }
     return $result;
 }
Пример #11
Показать файл Файл: DateTime.php Проект: evltuma/moodle
0
 /**
  */
 public function __construct($time = null)
 {
     $tz = new DateTimeZone('UTC');
     try {
         parent::__construct($time, $tz);
         return;
     } catch (Exception $e) {
     }
     /* Bug #5717 - Check for UT vs. UTC. */
     if (substr(rtrim($time), -3) === ' UT') {
         try {
             parent::__construct($time . 'C', $tz);
             return;
         } catch (Exception $e) {
         }
     }
     /* Bug #9847 - Catch paranthesized timezone information at end of date
      * string. */
     $date = preg_replace("/\\s*\\([^\\)]+\\)\\s*\$/", '', $time, -1, $i);
     if ($i) {
         try {
             parent::__construct($date, $tz);
             return;
         } catch (Exception $e) {
         }
     }
     parent::__construct('@-1', $tz);
 }
Пример #12
Показать файл Файл: viewbulletin.php Проект: kirkendall/shiftcal
0
function printevent($record, $prettydate)
{
    print "\n" . strtoupper($record["title"]) . "\n";
    $again = repeatfirstinstance($record, $prettydate);
    if ($again) {
        print "See {$again[date]} for details\n";
    } else {
        print hmmpm($record["eventtime"]) . "\n";
        if ($record["locname"]) {
            print "{$record[locname]}, {$record[address]}\n";
        } else {
            print "{$record[address]}\n";
        }
        print wordwrap($record["printdescr"], 68) . "\n";
        if (!$record["hideemail"]) {
            $email = preg_replace("/@/", " at ", $record["email"]);
            $email = preg_replace("/\\./", " dot ", $email);
            if ($record["weburl"] != "") {
                print "{$email}, {$record[weburl]}\n";
            } else {
                print "{$email}\n";
            }
        } else {
            if ($record["weburl"] != "") {
                print "{$record[weburl]}\n";
            }
        }
    }
}
Пример #13
Показать файл Файл: EntryController.php Проект: podemos-info/humhub-modules-calendar
0
 public function actionEdit()
 {
     $calendarEntry = $this->getCalendarEntry(Yii::$app->request->get('id'));
     if ($calendarEntry == null) {
         if (!$this->contentContainer->permissionManager->can(new \humhub\modules\calendar\permissions\CreateEntry())) {
             throw new HttpException(403, 'No permission to add new entries');
         }
         $calendarEntry = new CalendarEntry();
         $calendarEntry->content->container = $this->contentContainer;
         if (Yii::$app->request->get('fullCalendar') == 1) {
             \humhub\modules\calendar\widgets\FullCalendar::populate($calendarEntry, Yii::$app->timeZone);
         }
     } elseif (!$calendarEntry->content->canEdit()) {
         throw new HttpException(403, 'No permission to edit this entry');
     }
     if ($calendarEntry->all_day) {
         // Timezone Fix: If all day event, remove time of start/end datetime fields
         $calendarEntry->start_datetime = preg_replace('/\\d{2}:\\d{2}:\\d{2}$/', '', $calendarEntry->start_datetime);
         $calendarEntry->end_datetime = preg_replace('/\\d{2}:\\d{2}:\\d{2}$/', '', $calendarEntry->end_datetime);
         $calendarEntry->start_time = '00:00';
         $calendarEntry->end_time = '23:59';
     }
     if ($calendarEntry->load(Yii::$app->request->post()) && $calendarEntry->validate() && $calendarEntry->save()) {
         // After closing modal refresh calendar or page
         $output = "<script>";
         $output .= 'if(typeof $("#calendar").fullCalendar != "undefined") { $("#calendar").fullCalendar("refetchEvents"); } else { location.reload(); }';
         $output .= "</script>";
         $output .= $this->renderModalClose();
         return $this->renderAjaxContent($output);
     }
     return $this->renderAjax('edit', ['calendarEntry' => $calendarEntry, 'contentContainer' => $this->contentContainer, 'createFromGlobalCalendar' => false]);
 }
Пример #14
Показать файл Файл: MspabooruBridge.php Проект: ORelio/rss-bridge
0
 public function collectData(array $param)
 {
     $page = 0;
     $tags = '';
     if (isset($param['p'])) {
         $page = (int) preg_replace("/[^0-9]/", '', $param['p']);
         $page = $page - 1;
         $page = $page * 50;
     }
     if (isset($param['t'])) {
         $tags = urlencode($param['t']);
     }
     $html = $this->file_get_html("http://mspabooru.com/index.php?page=post&s=list&tags={$tags}&pid={$page}") or $this->returnError('Could not request Mspabooru.', 404);
     foreach ($html->find('div[class=content] span') as $element) {
         $item = new \Item();
         $item->uri = 'http://mspabooru.com/' . $element->find('a', 0)->href;
         $item->postid = (int) preg_replace("/[^0-9]/", '', $element->getAttribute('id'));
         $item->timestamp = time();
         $item->thumbnailUri = $element->find('img', 0)->src;
         $item->tags = $element->find('img', 0)->getAttribute('alt');
         $item->title = 'Mspabooru | ' . $item->postid;
         $item->content = '<a href="' . $item->uri . '"><img src="' . $item->thumbnailUri . '" /></a><br>Tags: ' . $item->tags;
         $this->items[] = $item;
     }
 }
Пример #15
Показать файл Файл: fix_http_header_inject.func.php Проект: yangfannjx/drafts
0
/**
 * 修复http响应拆分漏洞(php < 5.4 ?)。暂时按照360网站安全检测的建议方案进行修正,虽然感觉strip_tags并非必须。
 * @link http://thread.gmane.org/gmane.comp.php.devel/70584
 * @link https://bugs.php.net/bug.php?id=60227
 * @author Horse Luke
 * @version 0.1 build 20131021
 */
function fix_http_header_inject($str)
{
    if (empty($str)) {
        return $str;
    }
    return trim(strip_tags(preg_replace('/( |\\t|\\r|\\n|\')/', '', $str)));
}
Пример #16
Показать файл Файл: Tools.php Проект: nikulinsanya/exeltek
0
 public function action_discrepancies()
 {
     if (!Group::current('is_admin')) {
         throw new HTTP_Exception_403('Forbidden');
     }
     $list = Database_Mongo::collection('jobs')->find(array('discrepancies' => array('$nin' => array(NULL, '', 0))));
     $ids = array();
     foreach ($list as $job) {
         $discr = Database_Mongo::collection('discrepancies')->find(array('job_key' => $job['_id']))->sort(array('update_time' => -1))->getNext();
         $fl = true;
         foreach ($discr['data'] as $key => $value) {
             if ($key == 44) {
                 $status = preg_replace('/[^a-z]/i', '', strtolower($value['old_value']));
                 $status2 = preg_replace('/[^a-z]/i', '', strtolower($value['new_value']));
                 $status0 = preg_replace('/[^a-z]/i', '', strtolower(Arr::get($job['data'], $key, '')));
                 if ($status == $status0) {
                     continue;
                 }
                 if ($status == 'tested' && $status2 != 'tested' || $status == 'built' && ($status2 != 'built' && $status2 != 'tested') || $status != $status2 && in_array($status2, array('deferred', 'dirty', 'heldnbn'), true)) {
                     $fl = false;
                     continue;
                 }
             } elseif ($value['old_value'] != Arr::get($job['data'], $key, '')) {
                 $fl = false;
                 continue;
             }
         }
         if ($fl) {
             $ids[] = $job['_id'];
         }
     }
     Database_Mongo::collection('jobs')->update(array('_id' => array('$in' => $ids)), array('$unset' => array('discrepancies' => 1)), array('multiple' => 1));
     header('Content-type: application/json');
     die(json_encode(array('success' => true)));
 }
Пример #17
Показать файл Файл: http.php Проект: jacomyma/GEXF-Atlas
0
 /**
  * Processes the standard headers that are not subdivided into other structs.
  */
 protected function processStandardHeaders()
 {
     $req = $this->request;
     $req->date = isset($_SERVER['REQUEST_TIME']) ? new DateTime("@{$_SERVER['REQUEST_TIME']}") : new DateTime();
     if (isset($_SERVER['REQUEST_METHOD'])) {
         switch ($_SERVER['REQUEST_METHOD']) {
             case 'POST':
                 $req->protocol = 'http-post';
                 break;
             case 'PUT':
                 $req->protocol = 'http-put';
                 break;
             case 'DELETE':
                 $req->protocol = 'http-delete';
                 break;
             default:
                 $req->protocol = 'http-get';
         }
     }
     $req->host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain');
     $req->uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
     // remove the query string from the URI
     $req->uri = preg_replace('@\\?.*$@', '', $req->uri);
     // url decode the uri
     $req->uri = urldecode($req->uri);
     // remove the prefix from the URI
     $req->uri = preg_replace('@^' . preg_quote($this->properties['prefix']) . '@', '', $req->uri);
     $req->requestId = $req->host . $req->uri;
     $req->referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
     $req->variables =& $_REQUEST;
     if ($req->protocol == 'http-put') {
         $req->body = file_get_contents("php://input");
     }
 }
Пример #18
Показать файл Файл: dependency.php Проект: knigherrant/decopatio
0
 static function setMessage($file, $name)
 {
     jimport('joomla.filesystem.file');
     $file = str_replace('\\', '/', $file);
     if (strpos($file, '/administrator') === 0) {
         $file = str_replace('/administrator', JPATH_ADMINISTRATOR, $file);
     } else {
         $file = JPATH_SITE . '/' . $file;
     }
     $file = str_replace('//', '/', $file);
     $file_alt = preg_replace('#(com|mod)_([a-z-_]+\\.)#', '\\2', $file);
     if (!JFile::exists($file) && !JFile::exists($file_alt)) {
         $msg = JText::sprintf('NN_THIS_EXTENSION_NEEDS_THE_MAIN_EXTENSION_TO_FUNCTION', JText::_($name));
         $message_set = 0;
         $messageQueue = JFactory::getApplication()->getMessageQueue();
         foreach ($messageQueue as $queue_message) {
             if ($queue_message['type'] == 'error' && $queue_message['message'] == $msg) {
                 $message_set = 1;
                 break;
             }
         }
         if (!$message_set) {
             JFactory::getApplication()->enqueueMessage($msg, 'error');
         }
     }
 }
Пример #19
Показать файл Файл: UploadComponent.php Проект: khaled-saiful-islam/zen_v1.0
0
 /**
  * Save an uploaded file to a new location.
  *
  * @param   mixed    name of $_FILE input or array of upload data
  * @param   string   new filename
  * @param   string   new directory
  * @param   integer  chmod mask
  * @return  string   full path to new file
  */
 public static function save($file, $filename = NULL, $directory = NULL, $chmod = 0755)
 {
     // Load file data from FILES if not passed as array
     $file = is_array($file) ? $file : $_FILES[$file];
     if ($filename === NULL) {
         // Use the default filename, with a timestamp pre-pended
         $filename = time() . $file['name'];
     }
     // Remove spaces from the filename
     $filename = preg_replace('/\\s+/', '_', $filename);
     if ($directory === NULL) {
         // Use the pre-configured upload directory
         $directory = WWW_ROOT . 'files/';
     }
     // Make sure the directory ends with a slash
     $directory = rtrim($directory, '/') . '/';
     if (!is_dir($directory)) {
         // Create the upload directory
         mkdir($directory, 0777, TRUE);
     }
     //if ( ! is_writable($directory))
     //throw new exception;
     if (is_uploaded_file($file['tmp_name']) and move_uploaded_file($file['tmp_name'], $filename = $directory . $filename)) {
         if ($chmod !== FALSE) {
             // Set permissions on filename
             chmod($filename, $chmod);
         }
         //$all_file_name = array(FILE_INFO => $filename);
         // Return new file path
         return $filename;
     }
     return FALSE;
 }
Пример #20
Показать файл Файл: languageoverrides.php Проект: enjoy2000/714water
0
 function beforeLoad(&$params)
 {
     $basePath = JPATH_CONFIGURATION . '/administrator/components/com_jckman/editor/lang';
     $languages = JFolder::files($basePath, '.js$', 1, true);
     $js = "";
     $default = $params->get("joomlaLang", "en");
     foreach ($languages as $language) {
         $content = file_get_contents($language);
         $content = preg_replace("/\\/\\*.*?\\*\\//s", "", $content);
         $content = str_replace('"', "'", $content);
         $language = str_replace("\\", "/", $language);
         $parts = explode("/", $language);
         $lang = preg_replace("/\\.js\$/", "", array_pop($parts));
         $plugin = array_pop($parts);
         if ($lang != $default && $lang != 'en' || $plugin == 'lang') {
             //make sure we always load in default english file
             continue;
         }
         $content = preg_replace("/\\)\$/", ");", trim($content));
         if ($plugin == 'jflash') {
             $plug = 'flash';
         } else {
             $plug = $plugin;
         }
         $js .= "CKEDITOR.on('" . $plugin . "PluginLoaded', function(evt)\r\n            {\r\n               editor.lang." . $plug . " = null;\r\n               evt.data.lang = ['" . $default . "'];             \r\n               " . $content . "           \r\n            });";
     }
     //lets create JS object
     $javascript = new JCKJavascript();
     $javascript->addScriptDeclaration($js);
     return $javascript->toRaw();
 }
Пример #21
Показать файл Файл: App.php Проект: DustySheep/TEST_PMT1
0
 protected function __construct($config)
 {
     if (count($config["db"]) != 4) {
         throw new \Exception("Le nombre d'arguments n'est pas valable!");
     }
     spl_autoload_register(array(__CLASS__, 'autoload'));
     self::$config = $config;
     self::$database = new Core\Db\ConnectPDO(self::$config["db"]);
     self::$baseUrl = rtrim(dirname($_SERVER['PHP_SELF']), '/.\\');
     $route = isset($_GET["r"]) ? $_GET["r"] : $_SERVER["REQUEST_URI"];
     $url = parse_url($route);
     $path = preg_replace('/^' . preg_quote(self::$baseUrl, '/') . '\\//', "", $url["path"]);
     $query = @$url["query"];
     $method = $_SERVER['REQUEST_METHOD'];
     $request = new Core\Http\Request($method, $path, $query);
     $dispatcher = new Core\Http\Dispatcher();
     try {
         $dispatcher->handle($request);
     } catch (Exception $e) {
         $code = '404';
         header($_SERVER["SERVER_PROTOCOL"] . " " . $code);
         $request = new Core\Http\Request('GET', 'Site/error', 'code=' . $code . '&message=' . $e->getMessage());
         $dispatcher->handle($request);
     }
 }
Пример #22
Показать файл Файл: AbstractCtypeRule.php Проект: oz-framework/validation
0
 protected function filterWhiteSpaceOption($input)
 {
     if (!empty($this->additionalChars)) {
         $input = str_replace(str_split($this->additionalChars), '', $input);
     }
     return preg_replace('/\\s/', '', $input);
 }
Пример #23
Показать файл Файл: OpauthOpenId.php Проект: rafaelchavesfreitas/mapasculturais
0
 protected function _init()
 {
     $app = App::i();
     $config = array_merge(['timeout' => '24 hours', 'salt' => 'LT_SECURITY_SALT_SECURITY_SALT_SECURITY_SALT_SECURITY_SALT_SECU', 'login_url' => 'https://www.google.com/accounts/o8/id', 'path' => preg_replace('#^https?\\:\\/\\/[^\\/]*(/.*)#', '$1', $app->createUrl('auth'))], $this->_config);
     $opauth_config = ['Strategy' => ['OpenID' => ['identifier_form' => THEMES_PATH . 'active/views/auth-form.php', 'url' => $config['login_url']]], 'security_salt' => $config['salt'], 'security_timeout' => $config['timeout'], 'path' => $config['path'], 'callback_url' => $app->createUrl('auth', 'response')];
     $opauth = new \Opauth($opauth_config, false);
     $this->opauth = $opauth;
     if ($config['logout_url']) {
         $app->hook('auth.logout:after', function () use($app, $config) {
             $app->redirect($config['logout_url'] . '?next=' . $app->baseUrl);
         });
     }
     // add actions to auth controller
     $app->hook('GET(auth.index)', function () use($app) {
         $app->redirect($this->createUrl('openid'));
     });
     $app->hook('<<GET|POST>>(auth.openid)', function () use($opauth, $config) {
         $_POST['openid_url'] = $config['login_url'];
         $opauth->run();
     });
     $app->hook('GET(auth.response)', function () use($app) {
         $app->auth->processResponse();
         if ($app->auth->isUserAuthenticated()) {
             $app->redirect($app->auth->getRedirectPath());
         } else {
             if ($app->config['app.mode'] === 'production') {
                 $app->redirect($this->createUrl('error'));
             } else {
                 echo '<pre>';
                 var_dump($this->data, $_POST, $_GET, $_REQUEST, $_SESSION);
                 die;
             }
         }
     });
 }
Пример #24
Показать файл Файл: Util.php Проект: matks/vivian
0
 /**
  * Compute string length of only visible characters
  *
  * @param $string
  *
  * @return int
  */
 public static function getVisibleStringLength($string)
 {
     // remove escape characters
     $pattern = '#' . static::ESCAPE_CHARACTER_REGEX . '#';
     $cleanString = preg_replace($pattern, '', $string);
     return strlen($cleanString);
 }
Пример #25
Показать файл Файл: pochePictures.php Проект: akoenig/wallabag
0
/**
 * Retourne le lien absolu
 */
function get_absolute_link($relative_link, $url)
{
    /* return if already absolute URL */
    if (parse_url($relative_link, PHP_URL_SCHEME) != '') {
        return $relative_link;
    }
    /* queries and anchors */
    if ($relative_link[0] == '#' || $relative_link[0] == '?') {
        return $url . $relative_link;
    }
    /* parse base URL and convert to local variables:
       $scheme, $host, $path */
    extract(parse_url($url));
    /* remove non-directory element from path */
    $path = preg_replace('#/[^/]*$#', '', $path);
    /* destroy path if relative url points to root */
    if ($relative_link[0] == '/') {
        $path = '';
    }
    /* dirty absolute URL */
    $abs = $host . $path . '/' . $relative_link;
    /* replace '//' or '/./' or '/foo/../' with '/' */
    $re = array('#(/\\.?/)#', '#/(?!\\.\\.)[^/]+/\\.\\./#');
    for ($n = 1; $n > 0; $abs = preg_replace($re, '/', $abs, -1, $n)) {
    }
    /* absolute URL is ready! */
    return $scheme . '://' . $abs;
}
Пример #26
Показать файл Файл: Command.php Проект: VasekPurchart/khanovaskola-v3
0
 private function formatPath($path)
 {
     $root = realpath(__DIR__ . '/../../../');
     $path = realpath($path);
     $relative = substr($path, strlen($root) + 1);
     return preg_replace('~/([a-z0-9-]+)(\\.[a-z0-9]+)?$~ims', '/<fg=blue>$1</fg=blue>$2', $relative);
 }
Пример #27
Показать файл Файл: configurationProxy.php Проект: surfhh/typo3scripts
0
/**
 * Print the default configuration to ease creation of a config file.
 */
function exportConfig()
{
    $config = "";
    preg_match_all("/# Script Configuration start.+?# Script Configuration end/ms", file_get_contents(INVNAME), $config);
    $_configuration = preg_replace("/\\\$(?P<name>[^=]+)\\s*=\\s*\"(?P<value>[^\"]*)\";/", "\\1=\\2", $config[0][1]);
    echo $_configuration;
}
Пример #28
Показать файл Файл: GenerateScenarios.php Проект: pfz/codeception
0
 private function underscore($name)
 {
     $name = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\\1_\\2', $name);
     $name = preg_replace('/([a-z\\d])([A-Z])/', '\\1_\\2', $name);
     $name = str_replace(array('/', '\\'), array('.', '.'), $name);
     return $name;
 }
Пример #29
Показать файл Файл: OciAdapter.php Проект: 469306621/Languages
0
 public function create_column($column)
 {
     $column['column_name'] = strtolower($column['column_name']);
     $column['data_type'] = strtolower(preg_replace('/\\(.*?\\)/', '', $column['data_type']));
     if ($column['data_default'] !== null) {
         $column['data_default'] = trim($column['data_default'], "' ");
     }
     if ($column['data_type'] == 'number') {
         if ($column['data_scale'] > 0) {
             $column['data_type'] = 'decimal';
         } elseif ($column['data_scale'] == 0) {
             $column['data_type'] = 'int';
         }
     }
     $c = new Column();
     $c->inflected_name = Inflector::instance()->variablize($column['column_name']);
     $c->name = $column['column_name'];
     $c->nullable = $column['nullable'] == 'Y' ? true : false;
     $c->pk = $column['pk'] == 'P' ? true : false;
     $c->length = $column['data_length'];
     if ($column['data_type'] == 'timestamp') {
         $c->raw_type = 'datetime';
     } else {
         $c->raw_type = $column['data_type'];
     }
     $c->map_raw_type();
     $c->default = $c->cast($column['data_default']);
     return $c;
 }
Пример #30
Показать файл Файл: Translit.php Проект: artemkuchma/php_academy_site2
0
 public function __construct($text)
 {
     $this->text = $text;
     $text = (string) $text;
     // преобразуем в строковое значение
     $text = strip_tags($text);
     // убираем HTML-теги
     $text = str_replace(array("\n", "\r"), " ", $text);
     // убираем перевод каретки
     $text = preg_replace("/\\s+/", ' ', $text);
     // удаляем повторяющие пробелы
     $text = trim($text);
     // убираем пробелы в начале и конце строки
     $text = mb_strtolower($text, 'utf-8');
     // переводим строку в нижний регистр
     $text = strtr($text, array('а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'j', 'з' => 'z', 'и' => 'y', 'і' => 'i', 'ї' => 'і', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch', 'ы' => 'y', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya', 'ъ' => '', 'ь' => ''));
     // в данном случае язык
     //будет укр.(изначально скрипт для русского яз.) поэтому некоторые буквы заменены или удалены, а именно ('и'=>'i')
     $text = preg_replace("/[^0-9a-z-_ ]/i", "", $text);
     // очищаем строку от недопустимых символов
     $text = str_replace(" ", "_", $text);
     // заменяем пробелы нижним подчеркиванием
     $text = str_replace("-", "_", $text);
     //заменяет минус на нижнее подчеркивание
     $this->translit = $text;
 }