Пример #1
0
 public function renderFile()
 {
     header("Content-Type: application/json;charset=utf-8");
     $aRequest = array();
     $sContentType = 'application/x-www-form-urlencoded';
     if (isset($_SERVER['CONTENT_TYPE'])) {
         $sContentType = $_SERVER['CONTENT_TYPE'];
     }
     if (isset($_SERVER['HTTP_CONTENT_TYPE'])) {
         $sContentType = $_SERVER['HTTP_CONTENT_TYPE'];
     }
     if (StringUtil::startsWith($sContentType, 'application/json')) {
         $aRequest = json_decode(file_get_contents('php://input'), true);
     } else {
         foreach ($_REQUEST as $sKey => $sValue) {
             $aRequest[$sKey] = json_decode($sValue, true);
         }
     }
     $oSession = Session::getSession();
     if (!isset($aRequest['session_language']) && $oSession->isAuthenticated()) {
         $aRequest['session_language'] = $oSession->getUser()->getLanguageId();
     }
     $sPrevSessionLanguage = null;
     $sSetSessionLanguage = null;
     if (isset($aRequest['session_language'])) {
         $sPrevSessionLanguage = Session::language();
         $sSetSessionLanguage = $aRequest['session_language'];
         $oSession->setLanguage($sSetSessionLanguage);
     }
     try {
         try {
             $mJSONData = $this->getJSON($aRequest);
             $sResult = json_encode($mJSONData);
             $iError = json_last_error();
             if ($iError !== JSON_ERROR_NONE) {
                 throw new LocalizedException('wns.error.json', array('json_error' => $iError, 'json_error_message' => self::$JSON_ERRORS[$iError]));
             }
             print $sResult;
         } catch (Exception $e) {
             //Handle the gift, not the wrapping…
             if ($e->getPrevious()) {
                 throw $e->getPrevious();
             } else {
                 throw $e;
             }
         }
     } catch (LocalizedException $ex) {
         LinkUtil::sendHTTPStatusCode(500, 'Server Error');
         print json_encode(array('exception' => array('message' => $ex->getLocalizedMessage(), 'code' => $ex->getCode(), 'file' => $ex->getFile(), 'line' => $ex->getLine(), 'trace' => $ex->getTrace(), 'parameters' => $ex->getMessageParameters(), 'exception_type' => $ex->getExceptionType())));
     } catch (Exception $ex) {
         LinkUtil::sendHTTPStatusCode(500, 'Server Error');
         ErrorHandler::handleException($ex, true);
         print json_encode(array('exception' => array('message' => "Exception when trying to execute the last action {$ex->getMessage()}", 'code' => $ex->getCode(), 'file' => $ex->getFile(), 'line' => $ex->getLine(), 'trace' => $ex->getTrace(), 'exception_type' => get_class($ex))));
     }
     //If we changed the session language and no widget willfully changed it as well, reset it to the previous state
     if ($sPrevSessionLanguage !== null && Session::language() === $sSetSessionLanguage) {
         $oSession->setLanguage($sPrevSessionLanguage);
     }
 }
Пример #2
0
 public function __call($sMethodName, $aParameters)
 {
     //Event name
     if (!StringUtil::startsWith($sMethodName, 'handle')) {
         return 0;
     }
     $sEventName = substr($sMethodName, strlen('handle'));
     return $this->doHandleEvent($sEventName, $aParameters);
 }
Пример #3
0
 public static function prepareUrlForCurl($url)
 {
     $url = StringUtil::startsWith($url, '//') ? 'http:' . $url : $url;
     // URL encode based of MDN spec
     // http://stackoverflow.com/a/19858404
     return preg_replace_callback("{[^0-9a-z_.!~*'();,/?:@&=+\$#]}i", function ($m) {
         return sprintf('%%%02X', ord($m[0]));
     }, $url);
 }
 public function onRichtextWriteTagForIdentifier($sTagName, $aParameters, $oIdentifier, $sTagContent, $oLink)
 {
     if (Manager::getCurrentManager() instanceof BackendManager || $oIdentifier->getName() !== 'external_link' || !StringUtil::startsWith($aParameters[0]['href'], 'subs://') || !$oLink instanceof Link) {
         return;
     }
     $aParameters[0]['href'] = EXT_WEB_DIR_FE . '/' . substr($aParameters[0]['href'], strlen('subs://'));
     $aParameters[0]['class'] = 'internal_link subsite';
     $aParameters[0]['rel'] = 'internal';
 }
Пример #5
0
 public static function suite()
 {
     $oResult = new PHPUnit_Framework_TestSuite("ResourceFinder test suite");
     foreach (ResourceFinder::getFolderContents(dirname(__FILE__)) as $sFileName => $sFilePath) {
         if (StringUtil::endsWith($sFileName, "Tests.php") && (StringUtil::startsWith($sFileName, "ResourceFinder") || StringUtil::startsWith($sFileName, "FileResource") || StringUtil::startsWith($sFileName, "ResourceIncluder"))) {
             $oResult->addTestFile($sFilePath);
         }
     }
     return $oResult;
 }
Пример #6
0
 public static function suite()
 {
     $oResult = new PHPUnit_Framework_TestSuite("Complete test suite");
     foreach (ResourceFinder::getFolderContents(dirname(__FILE__)) as $sFileName => $sFilePath) {
         if (StringUtil::endsWith($sFileName, ".php") && StringUtil::startsWith($sFileName, "Test") && !StringUtil::startsWith($sFileName, "TestUtil") && $sFilePath !== __FILE__) {
             require_once $sFilePath;
             $oResult->addTest(call_user_func(array(substr($sFileName, 0, -strlen('.php')), "suite")));
         }
     }
     return $oResult;
 }
 public static function processCSSContent($sContent, $oFile)
 {
     $oCache = new Cache('preview_css' . $oFile->getInternalPath(), DIRNAME_TEMPLATES);
     header("Content-Type: text/css;charset=" . Settings::getSetting('encoding', 'browser', 'utf-8'));
     if ($oCache->entryExists() && !$oCache->isOutdated($oFile->getFullPath())) {
         $oCache->sendCacheControlHeaders();
         $oCache->passContents();
         exit;
     }
     $oParser = new Sabberworm\CSS\Parser($sContent, Sabberworm\CSS\Settings::create()->withDefaultCharset(Settings::getSetting('encoding', 'browser', 'utf-8')));
     $oCssContents = $oParser->parse();
     //Make all rules important
     // foreach($oCssContents->getAllRuleSets() as $oCssRuleSet) {
     //	foreach($oCssRuleSet->getRules() as $oRule) {
     //		$oRule->setIsImportant(true);
     //	}
     // }
     //Multiply all rules and prepend specific strings
     $aPrependages = array('#rapila_admin_menu', '.filled-container.editing', '.ui-dialog', '.cke_dialog_contents', '#widget-notifications', '.cke_reset', 'body > .cke_reset_all', '.tag_panel');
     foreach ($oCssContents->getAllDeclarationBlocks() as $oBlock) {
         $aNewSelector = array();
         foreach ($oBlock->getSelectors() as $iKey => $oSelector) {
             $sSelector = $oSelector->getSelector();
             if (StringUtil::startsWith($sSelector, "body ") || StringUtil::startsWith($sSelector, "html ")) {
                 $aNewSelector[] = $sSelector;
             } else {
                 foreach ($aPrependages as $sPrependage) {
                     if (StringUtil::startsWith($sSelector, "{$sPrependage} ") || StringUtil::startsWith($sSelector, "{$sPrependage}.") || $sSelector === $sPrependage) {
                         $aNewSelector[] = $sSelector;
                     } else {
                         $aNewSelector[] = "{$sPrependage} {$sSelector}";
                     }
                 }
             }
         }
         $oBlock->setSelector($aNewSelector);
     }
     //Absolutize all URLs
     foreach ($oCssContents->getAllValues() as $oValue) {
         if ($oValue instanceof Sabberworm\CSS\Value\URL) {
             $sURL = $oValue->getURL()->getString();
             if (!StringUtil::startsWith($sURL, '/') && !preg_match('/^\\w+:/', $sURL)) {
                 $sURL = $oFile->getFrontendDirectoryPath() . DIRECTORY_SEPARATOR . $sURL;
             }
             $oValue->setURL(new Sabberworm\CSS\Value\CSSString($sURL));
         }
     }
     $sContents = $oCssContents->render(Sabberworm\CSS\OutputFormat::createCompact());
     $oCache->setContents($sContents);
     $oCache->sendCacheControlHeaders();
     print $sContents;
 }
 private function createMethodGetter($methodName, $isSpecialColumn = false)
 {
     if (StringUtil::startsWith($methodName, $this->formatMethodPrefix)) {
         $conversion = null;
     } else {
         $formatMethod = preg_replace('/^get/', $this->formatMethodPrefix, $methodName, 1);
         if (method_exists($this->class, $formatMethod)) {
             $methodName = $formatMethod;
             $conversion = null;
         } else {
             $conversion = $this->formatConversion;
         }
     }
     return new afMethodGetter($methodName, $conversion, $isSpecialColumn);
 }
Пример #9
0
 public function getMissingRights($mPage, $bInheritedOnly = false)
 {
     $oRightMethods = get_class_methods("Right");
     $aResult = array();
     foreach ($oRightMethods as $iKey => $sRightMethodName) {
         if (!StringUtil::startsWith($sRightMethodName, 'getMay')) {
             continue;
         }
         $sRightName = substr($sRightMethodName, strlen('getMay'));
         if (!$this->may($mPage, $sRightName, $bInheritedOnly)) {
             $aResult[] = $sRightName;
         }
     }
     return $aResult;
 }
Пример #10
0
 public function __call($sMethodName, $aArguments)
 {
     if ($this->aFilterTypes !== null && StringUtil::startsWith($sMethodName, 'set') && $sMethodName[3] === strtoupper($sMethodName[3])) {
         $sFilterColumn = StringUtil::deCamelize(lcfirst(substr($sMethodName, 3)));
         if ($this->filterTypeForColumn($sFilterColumn) !== null) {
             return $this->oListSettings->setFilterColumnValue($sFilterColumn, $aArguments[0]);
         }
     }
     if ($this->aFilterTypes !== null && StringUtil::startsWith($sMethodName, 'get') && $sMethodName[3] === strtoupper($sMethodName[3])) {
         $sFilterColumn = StringUtil::deCamelize(lcfirst(substr($sMethodName, 3)));
         if ($this->filterTypeForColumn($sFilterColumn) !== null) {
             return $this->oListSettings->getFilterColumnValue($sFilterColumn);
         }
     }
     return call_user_func_array(array($this->oCriteriaDelegate, $sMethodName), $aArguments);
 }
Пример #11
0
 public static function getResourceIncluderContents($oIncluder)
 {
     $sContents = '';
     foreach ($oIncluder->getResourceInfosForIncludedResourcesOfPriority() as $aInfo) {
         if (isset($aInfo['file_resource'])) {
             $sContents .= file_get_contents($aInfo['file_resource']->getFullPath());
         } else {
             $sLocation = $aInfo['location'];
             if (StringUtil::startsWith($sLocation, '//')) {
                 $sLocation = 'http:' . $sLocation;
             }
             $sContents .= file_get_contents($sLocation);
         }
     }
     return $sContents;
 }
Пример #12
0
 public function setConnectionCharset($sAdapter, $sCharset, PDOConnection $oConnection = null)
 {
     if ($oConnection === null) {
         $oConnection = Propel::getConnection();
     }
     $sCharset = self::convertEncodingNameToSql($sCharset);
     if (StringUtil::startsWith($sAdapter, 'mysql')) {
         $sAdapter = 'mysql';
     }
     $sFile = ResourceFinder::create(array('data', 'sql', 'charset', "{$sAdapter}.dump"))->find();
     if ($sFile === null) {
         return;
     }
     $sCharsetCode = file_get_contents($sFile);
     $sCharsetCode = str_replace('{{charset}}', $sCharset, $sCharsetCode);
     $oConnection->exec($sCharsetCode);
 }
Пример #13
0
 public function loadFromBackup($sFileName = null)
 {
     $sFilePath = ResourceFinder::findResource(array(DIRNAME_DATA, 'sql', $sFileName));
     $oConnection = Propel::getConnection();
     $bFileError = false;
     if ($sFilePath === null) {
         $bFileError = true;
     }
     if (!$bFileError) {
         if (!is_readable($sFilePath)) {
             $bFileError = true;
         }
         if (!$bFileError) {
             $rFile = fopen($sFilePath, 'r');
             if (!$rFile) {
                 $bFileError = true;
             }
         }
     }
     // throw error and filename on error
     if ($bFileError) {
         throw new LocalizedException('wns.backup.loader.load_error', array('filename' => $sFilePath));
     }
     // continue importing from local file
     $sStatement = "";
     $sReadLine = "";
     $iQueryCount = 1;
     while (($sReadLine = fgets($rFile)) !== false) {
         if ($sReadLine !== "\n" && !StringUtil::startsWith($sReadLine, "#") && !StringUtil::startsWith($sReadLine, "--")) {
             $sStatement .= $sReadLine;
         }
         if ($sReadLine === "\n" || StringUtil::endsWith($sReadLine, ";\n")) {
             if (trim($sStatement) !== "") {
                 $oConnection->exec($sStatement);
                 $iQueryCount++;
             }
             $sStatement = "";
         }
     }
     if (trim($sStatement) !== "") {
         $oConnection->exec($sStatement);
     }
     Cache::clearAllCaches();
     return $iQueryCount;
 }
Пример #14
0
 /**
  * Redirects (locally by default).
  * Use with LinkUtil::link()ed URLs (because this redirect does not add the base path/context MAIN_DIR_FE).
  * Discards all buffered output and exits
  * Pass $sHost = false to mark $sLocation as absolute URL
  */
 public static function redirect($sLocation, $sHost = null, $sProtocol = 'default', $bPermanent = true)
 {
     while (ob_get_level() > 0) {
         ob_end_clean();
     }
     if ($bPermanent) {
         self::sendHTTPStatusCode(301, "Moved Permanently");
     } else {
         self::sendHTTPStatusCode(302, "Found");
     }
     if ($sHost !== false) {
         $sLocation = self::absoluteLink($sLocation, $sHost, $sProtocol);
     }
     if (StringUtil::startsWith($sLocation, '//')) {
         $sLocation = (self::isSSL() ? 'https:' : 'http:') . $sLocation;
     }
     $sRedirectString = "Location: {$sLocation}";
     header($sRedirectString);
     exit;
 }
Пример #15
0
 public static function getCustomMethods()
 {
     $aMethods = array();
     $aStaticMethods = array();
     $oSuperClass = new ReflectionClass('WidgetModule');
     $oClass = new ReflectionClass(get_called_class());
     foreach ($oClass->getMethods(ReflectionMethod::IS_PUBLIC) as $oMethod) {
         if (StringUtil::startsWith($oMethod->getName(), '__')) {
             continue;
         }
         if ($oSuperClass->hasMethod($oMethod->getName())) {
             continue;
         }
         if ($oMethod->isStatic()) {
             $aStaticMethods[] = $oMethod->getName();
         } else {
             $aMethods[] = $oMethod->getName();
         }
     }
     $aMethods[] = 'getInputName';
     $aMethods[] = 'setInputName';
     return array('static' => $aStaticMethods, 'instance' => $aMethods);
 }
 public function onNavigationItemChildrenRequested(NavigationItem $oNavigationItem)
 {
     if (!($oNavigationItem instanceof PageNavigationItem && $oNavigationItem->getIdentifier() === self::PARENT_PAGE_IDENTIFIER)) {
         return;
     }
     $aDocumentationPartKeys = array();
     foreach (DocumentationProviderTypeModule::completeMetaData() as $sPart => $aLanguages) {
         if (isset($aLanguages[Session::language()])) {
             $aDocumentationPartKeys[$sPart] = false;
         }
     }
     foreach (DocumentationPartQuery::create()->filterByLanguageId(Session::language())->select('Key')->find() as $sPart) {
         $aDocumentationPartKeys[$sPart] = true;
     }
     ksort($aDocumentationPartKeys);
     $aDocumentations = DocumentationsFrontendModule::listQuery()->select(array('Key', 'Name', 'Title', 'NameSpace'))->find();
     foreach ($aDocumentations as $aParams) {
         $aConfiguredParts = array();
         foreach ($aDocumentationPartKeys as $sKey => $bIsInternal) {
             if (StringUtil::startsWith($sKey, $aParams['NameSpace'] . '.')) {
                 $aConfiguredParts[$sKey] = $bIsInternal;
                 unset($aDocumentationPartKeys[$sKey]);
             } else {
                 if ($sKey > $aParams['NameSpace'] . '.') {
                     break;
                 }
             }
         }
         $sTitle = $aParams['Title'] != null ? $aParams['Title'] : $aParams['Name'];
         $oNavItem = new VirtualNavigationItem(self::ITEM_TYPE, $aParams['Key'], 'Dokumentation ' . $sTitle, $aParams['Name'], $aConfiguredParts);
         $oNavigationItem->addChild($oNavItem);
     }
     // if(count($aDocumentationPartKeys) > 0) {
     // 	$oNavItem = new VirtualNavigationItem(self::ITEM_TYPE_UNCATEGORIZED, 'uncategorized', TranslationPeer::getString('documentations.uncategorized'), null, $aDocumentationPartKeys);
     // 	$oNavigationItem->addChild($oNavItem);
     // }
 }
Пример #17
0
/**
 * Returns an array mapping user, password, host and database to their respective values.
 **/
function db_splitDsn($dsn = null)
{
    $result = array();
    if (!$dsn) {
        $dsn = pref_getServerPreference('database');
    }
    $prefix = 'mysql://';
    assert(StringUtil::startsWith($dsn, $prefix));
    $dsn = substr($dsn, strlen($prefix));
    $parts = preg_split("/[:@\\/]/", $dsn);
    assert(count($parts) == 3 || count($parts) == 4);
    if (count($parts) == 4) {
        $result['user'] = $parts[0];
        $result['password'] = $parts[1];
        $result['host'] = $parts[2];
        $result['database'] = $parts[3];
    } else {
        $result['user'] = $parts[0];
        $result['host'] = $parts[1];
        $result['database'] = $parts[2];
        $result['password'] = '';
    }
    return $result;
}
Пример #18
0
 /**
  * Ensures that startsWith() returns false if the string is shorter than the
  * prefix and equals the first part of the prefix.
  */
 public function testStartsWithReturnsFalseIfStringEqualsFirstPartOfPrefix()
 {
     $result = StringUtil::startsWith('test', 'testprefix');
     $this->assertFalse($result);
 }
 /**
  * Removes _* keys from the list of keys.
  */
 private static function pruneKeys(&$keys)
 {
     foreach ($keys as $i => $key) {
         if (StringUtil::startsWith($key, '_')) {
             unset($keys[$i]);
         }
     }
 }
Пример #20
0
 $lexemMap = array();
 $errorMap = array();
 $deleteMap = array();
 foreach ($_REQUEST as $name => $value) {
     if ((StringUtil::startsWith($name, 'caps_') || StringUtil::startsWith($name, 'model_') || StringUtil::startsWith($name, 'comment_') || StringUtil::startsWith($name, 'singular_') || StringUtil::startsWith($name, 'plural_') || StringUtil::startsWith($name, 'verifSp_') || StringUtil::startsWith($name, 'delete_') || StringUtil::startsWith($name, 'deleteConfirm_')) && $value) {
         $parts = preg_split('/_/', $name);
         assert(count($parts) == 2);
         $lexemId = $parts[1];
         if (!array_key_exists($lexemId, $lexemMap)) {
             $lexemMap[$lexemId] = Lexem::get_by_id($lexemId);
         }
         $l = $lexemMap[$lexemId];
         $lm = $l->getFirstLexemModel();
         switch ($parts[0]) {
             case 'caps':
                 if (StringUtil::startsWith($l->form, "'")) {
                     $l->form = "'" . AdminStringUtil::capitalize(mb_substr($l->form, 1));
                 } else {
                     $l->form = AdminStringUtil::capitalize($l->form);
                 }
                 $l->formNoAccent = str_replace("'", '', $l->form);
                 break;
             case 'singular':
                 $lm->restriction = 'S';
                 break;
             case 'plural':
                 $lm->restriction = 'P';
                 break;
             case 'model':
                 if ($value) {
                     $m = Model::factory('FlexModel')->where_raw("concat(modelType, number) = '{$value}'")->find_one();
Пример #21
0
<?php

require_once "../../phplib/util.php";
util_assertModerator(PRIV_EDIT);
util_assertNotMirror();
$submitButton = util_getRequestParameter('submitButton');
if ($submitButton) {
    $defId = util_getRequestParameter('definitionId');
    $def = Definition::get_by_id($defId);
    // Collect the user choices
    $choices = array();
    foreach ($_REQUEST as $name => $value) {
        if (StringUtil::startsWith($name, 'radio_')) {
            $choices[substr($name, 6)] = $value;
        }
    }
    // Collect the positions of ambiguous abbreviations
    $matches = array();
    AdminStringUtil::markAbbreviations($def->internalRep, $def->sourceId, $matches);
    usort($matches, 'positionCmp');
    $s = $def->internalRep;
    foreach ($matches as $i => $m) {
        if ($choices[count($choices) - 1 - $i] == 'abbrev') {
            $orig = substr($s, $m['position'], $m['length']);
            $replacement = StringUtil::isUppercase(StringUtil::getCharAt($orig, 0)) ? AdminStringUtil::capitalize($m['abbrev']) : $m['abbrev'];
            $s = substr_replace($s, "#{$replacement}#", $m['position'], $m['length']);
        }
    }
    $def->internalRep = $s;
    $def->htmlRep = AdminStringUtil::htmlize($def->internalRep, $def->sourceId);
    $def->abbrevReview = ABBREV_REVIEW_COMPLETE;
 public function replaceIn($oIdentifier)
 {
     $sText = $oIdentifier->getValue();
     $sReplacement = $oIdentifier->getParameter('with');
     if ($oIdentifier->hasParameter('matching')) {
         $sPattern = $oIdentifier->getParameter('matching');
         if (!StringUtil::startsWith($sPattern, '/')) {
             $sPattern = '/' . $sPattern . '/';
         }
         return preg_replace($sPattern, $sReplacement, $sText);
     } else {
         $sSearch = $oIdentifier->getParameter('string');
         return str_replace($sSearch, $sReplacement, $sText);
     }
 }
Пример #23
0
/**
 * Read forms and isLoc/recommended checkboxes from the request.
 * The map is already populated with all the applicable inflection IDs.
 * InflectionId's and variants are coded in the request parameters.
 **/
function readRequest(&$map)
{
    foreach ($_REQUEST as $name => $value) {
        if (StringUtil::startsWith($name, 'forms_')) {
            $parts = preg_split('/_/', $name);
            assert(count($parts) == 3);
            assert($parts[0] == 'forms');
            $inflId = $parts[1];
            $variant = $parts[2];
            $form = trim($value);
            if ($form) {
                $map[$inflId][$variant] = array('form' => $form, 'isLoc' => false, 'recommended' => false);
            }
        } else {
            if (StringUtil::startsWith($name, 'isLoc_')) {
                $parts = preg_split('/_/', $name);
                assert(count($parts) == 3);
                assert($parts[0] == 'isLoc');
                $inflId = $parts[1];
                $variant = $parts[2];
                if (array_key_exists($variant, $map[$inflId])) {
                    $map[$inflId][$variant]['isLoc'] = true;
                }
            } else {
                if (StringUtil::startsWith($name, 'recommended_')) {
                    $parts = preg_split('/_/', $name);
                    assert(count($parts) == 3);
                    assert($parts[0] == 'recommended');
                    $inflId = $parts[1];
                    $variant = $parts[2];
                    if (array_key_exists($variant, $map[$inflId])) {
                        $map[$inflId][$variant]['recommended'] = true;
                    }
                }
            }
        }
    }
    // Now reindex the array, in case the admin left, for example, variant 1 empty but filled in variant 2.
    foreach ($map as $inflId => $variants) {
        $map[$inflId] = array_values($variants);
    }
}
Пример #24
0
if ($newLocVersion) {
    if ($locVersion == $newLocVersion) {
        FlashMessage::add('Ați selectat aceeași versiune LOC de două ori');
        util_redirect('scrabble-loc');
    }
    $file1 = tempnam('/tmp', 'loc_diff_');
    $file2 = tempnam('/tmp', 'loc_diff_');
    writeLexems($locVersion, $file1);
    writeLexems($newLocVersion, $file2);
    $diff = OS::executeAndReturnOutput("diff {$file1} {$file2} || true");
    print "<pre>\n";
    foreach ($diff as $line) {
        if (StringUtil::startsWith($line, '< ')) {
            print sprintf("<span style=\"color: red\">%s: %s</span>\n", $locVersion, substr($line, 2));
        } else {
            if (StringUtil::startsWith($line, '> ')) {
                print sprintf("<span style=\"color: green\">%s: %s</span>\n", $newLocVersion, substr($line, 2));
            }
        }
    }
    print "</pre>\n";
    util_deleteFile($file1);
    util_deleteFile($file2);
    exit;
}
if ($locVersion) {
    header('Content-type: text/plain; charset=UTF-8');
    writeLexems($locVersion, 'php://output');
    exit;
}
setlocale(LC_ALL, "ro_RO.utf8");
Пример #25
0
 private function consolidationStepForResourceType($sType, $bExcludeExternal, $iPriority, $sKey, &$aConsolidatorInfo, &$resource_type, &$file_resource, &$location, &$content, &$template, &$media, $aResourceInfo)
 {
     $sSSLMode = 'default';
     if ($resource_type !== $sType && $resource_type !== "inline_{$sType}") {
         return;
     }
     //External location (no file_resource given) or location not determinable
     $bIsExternal = $file_resource === null && $content === null;
     // Files with external references should only be consolidated if explicitly requested (resource_includer.yml/general/consolidate_resources == 'internal' disables this)
     $bShouldNotBeConsolidated = $bIsExternal && ($bExcludeExternal || $location === null);
     // Files with an IE condition can’t be consolidated because the condition (unlike CSS media queries) can only be set in HTML
     $bShouldNotBeConsolidated = $bShouldNotBeConsolidated || isset($aResourceInfo['ie_condition']);
     if ($bShouldNotBeConsolidated) {
         $this->cleanupConsolidator($aConsolidatorInfo);
     } else {
         $this->initConsolidator($sType, $iPriority, $sKey, $aConsolidatorInfo);
         $oCache = new Cache('consolidated-' . $sKey, DIRNAME_PRELOAD, CachingStrategy::fromConfig('file'));
         if (!$oCache->entryExists()) {
             $sRelativeLocationRoot = null;
             $sContents = '';
             if ($file_resource !== null) {
                 // We have a file resource
                 $sContents = file_get_contents($file_resource->getFullPath());
                 $sRelativeLocationRoot = LinkUtil::absoluteLink($file_resource->getFrontendPath(), null, $sSSLMode, true);
             } else {
                 if ($location !== null) {
                     // No file resource given, we only have a URL to go on
                     if (StringUtil::startsWith($location, '//')) {
                         $location = substr($location, strlen('//'));
                         // The path is a protocol-relative URL. Absolutize for file_get_contents and relativize for linking (according to linking/always_link_absolutely)
                         $sRelativeLocationRoot = LinkUtil::getProtocol() . $location;
                         $mProtocolSetting = 'auto';
                         $location = LinkUtil::getProtocol($mProtocolSetting) . $location;
                     } else {
                         if (StringUtil::startsWith($location, '/')) {
                             // The path is a domain-relative-URL. Absolutize for file_get_contents and relativize for linking (according to linking/always_link_absolutely)
                             $sRelativeLocationRoot = LinkUtil::absoluteLink($location, null, $sSSLMode, true);
                             $location = LinkUtil::absoluteLink($location, null, LinkUtil::isSSL());
                         } else {
                             $sRelativeLocationRoot = $location;
                         }
                     }
                     $sContents = file_get_contents($location);
                 } else {
                     if ($content !== null) {
                         if ($content instanceof Template) {
                             $content = $content->render();
                         }
                         $sContents = $content;
                     }
                 }
             }
             if ($sType === self::RESOURCE_TYPE_CSS && $media) {
                 $sContents = "@media {$media} { {$sContents} }";
             }
             // Fix relative locations in CSS
             if ($sType === self::RESOURCE_TYPE_CSS && $sRelativeLocationRoot !== null) {
                 //Remove the protocol so our slash-detection logic works correctly (because the protocol may also contain slashes)
                 if (preg_match(',^([a-z][a-z.\\-+]*:)?//,', $sRelativeLocationRoot, $sProtocol) === 1) {
                     $sProtocol = $sProtocol[0];
                 } else {
                     $sProtocol = '';
                 }
                 $sRelativeLocationRoot = substr($sRelativeLocationRoot, strlen($sProtocol));
                 $sAbsoluteLocationRoot = $sRelativeLocationRoot;
                 $bHasTruncatedTail = false;
                 $iSlashPosition = null;
                 // Calculate the absolute location root (will be "" most of the time unless the CSS was loaded from an external domain or linking/always_link_absolutely is true)
                 while (($iSlashPosition = strrpos($sAbsoluteLocationRoot, '/')) !== false) {
                     $sAbsoluteLocationRoot = substr($sAbsoluteLocationRoot, 0, $iSlashPosition);
                     if (!$bHasTruncatedTail) {
                         // Remove the last part from the relative location as it’s the resource itself
                         $sRelativeLocationRoot = "{$sAbsoluteLocationRoot}/";
                         $bHasTruncatedTail = true;
                     }
                 }
                 // Re-add the protocol part
                 $sRelativeLocationRoot = $sProtocol . $sRelativeLocationRoot;
                 $sAbsoluteLocationRoot = $sProtocol . $sAbsoluteLocationRoot;
                 // Find url() tokens
                 $sContents = preg_replace_callback(',url\\s*\\(\\s*(\'[^\']+\'|\\"[^\\"]+\\"|[^(\'\\"]+?)\\s*\\),', function ($aMatches) use($sRelativeLocationRoot, $sAbsoluteLocationRoot) {
                     // Convert /something/../ to /
                     $sQuote = '';
                     $sUrl = $aMatches[1];
                     $sFirst = substr($sUrl, 0, 1);
                     if ($sFirst === '"' || $sFirst === "'") {
                         $sQuote = $sFirst;
                         $sUrl = substr($sUrl, 1, -1);
                     }
                     if (StringUtil::startsWith($sUrl, '//')) {
                         // URL is protocol-relative. Do nothing.
                         // If this were pointing to the local host, we’d need to respect linking/ssl_in_absolute_links
                         // but if it did come from a file resource, we’d already have that
                     } else {
                         if (StringUtil::startsWith($sUrl, '/')) {
                             // URL absolute. That means relative to $sAbsoluteLocationRoot
                             $sUrl = $sAbsoluteLocationRoot . $sUrl;
                         } else {
                             if (!preg_match(',^[a-z][a-z.\\-+]*:,', $sUrl)) {
                                 // URL is relative to the resource being changed. That means relative to $sRelativeLocationRoot
                                 // Absolutize only relative URLs (the ones not starting with a protocol)
                                 // Prepend the coomon root for the relative location
                                 $sUrl = $sRelativeLocationRoot . $sUrl;
                                 // Fix explicit relative URLs (./)
                                 $sUrl = preg_replace(',/\\./,', '/', $sUrl);
                                 // Resolve Uplinks (/some-place/../)
                                 $sParentPattern = ',/[^/]+/\\.\\./,';
                                 while (preg_match($sParentPattern, $sUrl) === 1) {
                                     $sUrl = preg_replace($sParentPattern, '/', $sUrl, 1);
                                 }
                             }
                         }
                     }
                     return "url({$sQuote}{$sUrl}{$sQuote})";
                 }, $sContents);
             }
             $oCache->setContents($sContents);
         }
         $aConsolidatorInfo['contents'][$sKey] = $oCache;
     }
 }
Пример #26
0
<?php

require_once "../../phplib/util.php";
util_assertModerator(PRIV_EDIT);
util_assertNotMirror();
$submitButton = util_getRequestParameter('submitButton');
if ($submitButton) {
    foreach ($_REQUEST as $name => $position) {
        if (StringUtil::startsWith($name, 'position_')) {
            $parts = preg_split('/_/', $name);
            assert(count($parts) == 2);
            assert($parts[0] == 'position');
            $lexem = Lexem::get_by_id($parts[1]);
            $noAccent = util_getRequestParameter('noAccent_' . $lexem->id);
            if ($noAccent) {
                $lexem->noAccent = 1;
                $lexem->save();
            } else {
                if ($position != -1) {
                    $lexem->form = mb_substr($lexem->form, 0, $position) . "'" . mb_substr($lexem->form, $position);
                    $lexem->save();
                    foreach ($lexem->getLexemModels() as $lm) {
                        $lm->regenerateParadigm();
                    }
                }
            }
        }
    }
    util_redirect("placeAccents.php");
}
$chars = array();
Пример #27
0
/**
 * Attempts to assign an image automatically for the given date and word.
 * Returns the image name on success, null on failure
 **/
function assignImageByName($wotd, $def)
{
    global $staticFiles;
    $yearMonth = substr($wotd->displayDate, 0, 7);
    $strippedLexicon = stripImageName($def->lexicon);
    foreach ($staticFiles as $file) {
        if (StringUtil::startsWith($file, "img/wotd/{$yearMonth}/")) {
            $file = basename(trim($file));
            $strippedFile = stripImageName($file);
            if (preg_match("/{$strippedLexicon}\\.(png|jpg|jpeg)/", $strippedFile)) {
                return "{$yearMonth}/{$file}";
            }
        }
    }
    return null;
}
Пример #28
0
 /**
  * Returns an /absolute URL.
  */
 public static function abs($url)
 {
     if (StringUtil::startsWith($url, 'http://')) {
         return $url;
     }
     if (StringUtil::startsWith($url, 'https://')) {
         return $url;
     }
     if (!StringUtil::startsWith($url, '/')) {
         $url = '/' . $url;
     }
     return $url;
 }
Пример #29
0
<?php

require_once "../../phplib/util.php";
util_assertModerator(PRIV_EDIT);
util_assertNotMirror();
$suffix = util_getRequestParameter('suffix');
$submitButton = util_getRequestParameter('submitButton');
if ($submitButton) {
    foreach ($_REQUEST as $name => $modelId) {
        if (StringUtil::startsWith($name, 'lexem_')) {
            $parts = preg_split('/_/', $name);
            assert(count($parts) == 2);
            assert($parts[0] == 'lexem');
            $lexem = Lexem::get_by_id($parts[1]);
            if ($modelId) {
                $parts = preg_split('/_/', $modelId);
                assert(count($parts) == 2);
                $lm = $lexem->getFirstLexemModel();
                $lm->modelType = $parts[0];
                $lm->modelNumber = $parts[1];
                $lm->restriction = util_getRequestParameter('restr_' . $lexem->id);
                $lm->save();
                $lm->regenerateParadigm();
            } else {
                $lexem->comment = util_getRequestParameter('comment_' . $lexem->id);
                $lexem->save();
            }
        }
    }
    util_redirect("bulkLabel.php?suffix={$suffix}");
}
Пример #30
0
 public function identifiersMatching($sName = null, $sValue = null, $aParameters = null, $bFindFirst = false, $iStartPosition = 0)
 {
     $aResult = array();
     $aIdentifiers = $this->allIdentifiers();
     if ($iStartPosition) {
         $aIdentifiers = array_slice($aIdentifiers, $iStartPosition, null, true);
     }
     foreach ($aIdentifiers as $iKey => $mValue) {
         if ($sName === null || $mValue->getName() === $sName && ($sValue === self::$ANY_VALUE || $mValue->getValue() === $sValue)) {
             if ($aParameters === null || count($aParameters) === 0) {
                 if ($bFindFirst) {
                     return $mValue;
                 } else {
                     $aResult[$iKey] = $mValue;
                     continue;
                 }
             }
             $bMatches = true;
             foreach ($aParameters as $sParameterName => $sParameterValue) {
                 if (is_string($sParameterValue) && StringUtil::startsWith($sParameterValue, "!")) {
                     //search for non-matching values
                     $sParameterValue = substr($sParameterValue, 1);
                     if ($mValue->hasParameter($sParameterName) && $mValue->getParameter($sParameterName) === $sParameterValue) {
                         $bMatches = false;
                         break;
                     }
                 } else {
                     if (!$mValue->hasParameter($sParameterName) || $sParameterValue !== self::$ANY_VALUE && $mValue->getParameter($sParameterName) !== $sParameterValue) {
                         $bMatches = false;
                         break;
                     }
                 }
             }
             if ($bMatches === true) {
                 if ($bFindFirst) {
                     return $mValue;
                 } else {
                     $aResult[$iKey] = $mValue;
                 }
             }
         }
     }
     if ($bFindFirst) {
         return null;
     }
     return $aResult;
 }