public function Format($row, $fieldname, $value) { $files = $this->_context->getUploadFileNames(); if ($files[$fieldname] != "") { $fileProcessor = new UploadFilenameProcessor($this->_saveAs); $fileProcessor->setFilenameLocation(ForceFilenameLocation::DefinePath, FileUtil::GetTempDir()); // Save the files in a temporary directory $result = $this->_context->processUpload($fileProcessor, false, $fieldname); // Get a way to rename the files $fileinfo = pathinfo($result[0]); if ($this->_saveAs != "*") { $path_parts = pathinfo($this->_saveAs); } else { $path_parts = pathinfo($result[0]); } $newName = $this->_path . FileUtil::Slash() . $path_parts['filename'] . "." . $fileinfo["extension"]; // Put the image in the right place if (strpos(".jpg.gif.jpeg.png", "." . $fileinfo["extension"]) === false) { rename($result[0], $newName); } else { if ($this->_width > 0 || $this->_height > 0) { $image = new ImageUtil($result[0]); $image->resizeAspectRatio($this->_width, $this->_height, 255, 255, 255)->save($newName); } else { rename($result[0], $newName); } } return $newName; } else { return $row->getField($fieldname); } }
/** * Enter description here... * * @param Context $context * @param string $name * @param bool $breakline * @param bool $canhide * @param string $caption * @return XmlInputGroup */ public function __construct($context, $name = "", $breakline = false, $canhide = false, $caption = "") { if (!$context instanceof Context) { throw new InvalidArgumentException("Class XmlInputGroup must have a value Xmlnuke Context"); } $this->_context = $context; if ($name == "") { $this->_name = "ING" . $this->_context->getRandomNumber(100000); } else { $this->_name = $name; } $this->_canhide = $canhide; $this->_breakline = $breakline; $this->_caption = $caption; }
/** *@desc Get a XMLDocument from a XMLFile *@param XMLFilenameProcessor $xmlFile XML File *@return DOMDocument */ public function getXmlDocument($xmlFile) { $this->_context->setXml($xmlFile->ToString()); // Load XMLDocument and add ALL and INDEX nodes $xmlDoc = new DOMDocument(); try { if (!($xmlFile->getFilenameLocation() == ForceFilenameLocation::PathFromRoot)) { $xmlDoc = $this->_context->getXMLDataBase()->getDocument($xmlFile->FullQualifiedName(), null); } else { $xmlDoc = XmlUtil::CreateXmlDocumentFromFile($xmlFile->FullQualifiedNameAndPath()); } } catch (Exception $ex) { $xmlFileNotFound = new XMLFilenameProcessor("notfound"); if ($this->_context->getXMLDataBase()->existsDocument($xmlFileNotFound->FullQualifiedName())) { $xmlDoc = $this->_context->getXMLDataBase()->getDocument($xmlFileNotFound->FullQualifiedName(), null); } else { throw $ex; } } $xmlRootNode = $xmlDoc->getElementsByTagName("page")->item(0); if ($xmlRootNode != null) { $this->addXMLDefault($xmlRootNode); } return $xmlDoc; }
public function getXsl() { // Avoid to process standard modules with admin and exception templates if ($this->_context->getXsl() == "admin" || $this->_context->getXsl() == "admin") { $this->_context->setXsl($this->_context->get("xmlnuke.DEFAULTPAGE")); } // Default XSL (get from parameter or config) $xslFile = new XSLFilenameProcessor($this->_context->getXsl()); return $xslFile; }
/** *@desc XmlFormCollection construction *@param Context $context *@param string $action *@param string $title */ public function __construct($context, $action, $title) { parent::__construct(); $this->_context = $context; $this->_action = $action; $this->_title = $title; $this->_formname = "frm" . $this->_context->getRandomNumber(10000); $this->_jsValidate = true; $this->_decimalSeparator = $this->_context->Language()->getDecimalPoint(); $this->_dateformat = $this->_context->Language()->getDateFormat(); }
/** *@param string $xslPath *@return string *@desc Return the XSL with snippet to/from cache. */ public function IncludeSnippet($xslPath) { $xslName = $this->_file->ToString() . '.' . strtolower($this->_context->Language()->getName()) . '.xsl'; $cacheEngine = $this->_context->getXSLCacheEngine(); $result = $cacheEngine->get($xslName, 7200); // Create a new stream representing the file to be written to, // and write the stream cache the stream // from the external location to the file (only if doesnt exist) if ($result === false) { $content = ""; $content = file_get_contents($xslPath); try { $cacheEngine->lock($xslName); $iStart = strpos($content, "<xmlnuke-"); while ($iStart !== false) { $iEnd = strpos($content, ">", $iStart + 1); $snippetFile = substr($content, $iStart + 9, $iEnd - $iStart - 10); $snippet = new SnippetFilenameProcessor(trim($snippetFile)); if (!FileUtil::Exists($snippet)) { throw new SnippetNotFoundException("Snippet " . $snippet->FullQualifiedNameAndPath() . " not found"); } $sReadSnippet = file_get_contents($snippet->FullQualifiedNameAndPath()); $content = substr($content, 0, $iStart) . self::LF . $sReadSnippet . substr($content, $iEnd + 1); $iStart = strpos($content, "<xmlnuke-"); } $cacheEngine->unlock($xslName); $cacheEngine->set($xslName, $content); return $content; } catch (Exception $ex) { $cacheEngine->unlock($xslName); $cacheEngine->release($xslName); throw $ex; } } else { // Already in Cache return $result; } }
/** *@param *@return bool *@desc */ public function UseFileFromAnyLanguage() { $langAvail = $this->_context->LanguagesAvailable(); $langAvail["en-us"] = "English (Default)"; if (!$this->exists()) { foreach (array_keys($langAvail) as $key) { $this->setLanguageId($key); if ($this->Exists()) { break; } } } return $this->exists(); }
/** * This method is used only in the Wrappers * So, it can echo string directly * * @param type $buffer */ public function SearchAndReplace($buffer) { $context = Context::getInstance(); $posi = 0; $i = strpos($buffer, "<param-", $posi); while ($i !== false) { echo substr($buffer, $posi, $i - $posi); $if = strpos($buffer, "</param-", $i); $tamparam = $if - $i - 8; $var = substr($buffer, $i + 7, $tamparam); echo $context->get($var); $posi = $if + $tamparam + 9; $i = strpos($buffer, "<param-", $posi); } echo substr($buffer, $posi); }
/** *@param string $param *@return string *@desc Process XHTML file and replace the tags [param:...] to XMLNuke context values */ private function CheckParameters($param) { if ($param == null) { return ""; } $iStart = strpos($param, "[param:"); if ($iStart !== false) { $iEnd; while ($iStart !== false) { $iEnd = strpos($param, "]", $iStart + 1); $paramDesc = substr($param, $iStart + 7, $iEnd - $iStart - 7); $param = substr($param, 0, $iStart) . str_replace("&", "&", $this->_context->get($paramDesc)) . substr($param, $iEnd + 1); $iStart = strpos($param, "[param:"); } } return $param; }
/** * Set the proper Error Handler based on the Output of the page * * @param OutputData $output */ public function setHandler($output) { $this->_whoops->popHandler(); if ($output == OutputData::Json) { $this->_handler = new JsonResponseHandler(); } else { if ($output == OutputData::Xml) { $this->_handler = new XmlResponseHandler(); } else { $this->_handler = new PrettyPageHandler(); if (!Context::getInstance()->getDevelopmentStatus()) { $this->_handler->addResourcePath(\WhoopsResources\Resource::getPath()); } } } $this->_whoops->pushHandler($this->_handler); }
public function handle() { $this->getAccessToken(); $state = $this->getVar('oauth_state'); /* If oauth_token is missing get it */ if ($this->_context->get('oauth_token') != "" && $state === 'start') { /*{{{*/ $this->setVar('oauth_state', 'returned'); $state = 'returned'; } /*}}}*/ $class = new ReflectionClass($this->_className); switch ($state) { /*{{{*/ default: /* Create CredentialsOAuth object with app key/secret */ $to = $class->newInstance($this->_consumer_key, $this->_consumer_secret); /* Request tokens from OAuth Server */ $tok = $to->getRequestToken(); /* Save tokens for later */ $this->setVar('oauth_request_token', $token = $tok['oauth_token']); $this->setVar('oauth_request_token_secret', $tok['oauth_token_secret']); $this->setVar('oauth_state', "start"); /* Build the authorization URL */ $request_link = $to->getAuthorizeURL($token); $this->_context->redirectUrl($request_link); break; case 'returned': /* If the access tokens are already set skip to the API call */ if ($this->getVar('oauth_access_token') === "" && $this->getVar('oauth_access_token_secret') === "") { /* Create CredentialOAuth object with app key/secret and token key/secret from default phase */ $to = $class->newInstance($this->_consumer_key, $this->_consumer_secret, $this->getVar('oauth_request_token'), $this->getVar('oauth_request_token_secret')); /* Request access tokens from OAuth Server */ $tok = $to->getAccessToken(); /* Save the access tokens. Normally these would be saved in a database for future use. */ $this->setVar('oauth_access_token', $tok['oauth_token']); $this->setVar('oauth_access_token_secret', $tok['oauth_token_secret']); $this->saveAccessToken(); } /* Create CredentialsOAuth with app key/secret and user access key/secret */ $to = $class->newInstance($this->_consumer_key, $this->_consumer_secret, $this->getVar('oauth_access_token'), $this->getVar('oauth_access_token_secret')); return $to; break; } /*}}}*/ }
/** *@param AnydatasetBaseFilenameProcessor $langFile *@return void *@desc Load Languages */ public function LoadLanguages($langFile) { $all = $langFile->ToString() == "_all"; if (!$all) { $this->LoadLanguages(new AnydatasetLangFilenameProcessor("_all")); } $this->_loadedFromFile = false; $paths = array(); if ($langFile->getFilenameLocation() == ForceFilenameLocation::UseWhereExists || $langFile->getFilenameLocation() == ForceFilenameLocation::SharedPath) { $paths[] = $langFile->SharedPath(); } if ($langFile->getFilenameLocation() == ForceFilenameLocation::UseWhereExists || $langFile->getFilenameLocation() == ForceFilenameLocation::PrivatePath) { $paths = array_merge($paths, $langFile->PrivatePath()); } foreach ($paths as $path) { $filename = $path . $langFile->FullQualifiedName(); $this->_debugInfo .= $langFile->ToString() . " in " . $filename . ' '; if (!FileUtil::Exists($filename)) { $this->_debugInfo .= "[Does not exists]; \n"; continue; } $this->_debugInfo .= "[Exists]; \n"; $curLang = strtolower($this->_context->Language()->getName()); try { $lang = new AnyDataset($filename); } catch (Exception $e) { throw new EngineException('Can\'t load language file "' . $langFile->FullQualifiedName() . '"! ' . $e->getMessage()); } $itf = new IteratorFilter(); $itf->addRelation("LANGUAGE", Relation::EQUAL, $curLang); //AnyIterator $it = $lang->getIterator($itf); if ($it->hasNext()) { //SingleRow $sr = $it->moveNext(); $names = $sr->getFieldNames(); foreach ($names as $name) { $this->addText($curLang, $name, $sr->getField($name)); } $this->_loadedFromFile = true; } } }
/** * Handle OAuth 2.0 Flow * @return BaseOAuth20 */ public function handle() { // Get Var Elements $accessToken = $this->getAccessToken(); $state = $this->getVar("state"); // Initiate OAuth Client with Specific server configuration $to = new $this->_className(); // Try to Handle the Authentication Process if ($accessToken == "") { $code = $this->_context->get("code"); // If not received the "Code" Parameter, initiate the autorization request if ($code == "") { $state = md5(uniqid(rand(), TRUE)); //CSRF protection $this->setVar("state", $state); $params = array("client_id" => $this->_client_id, "redirect_uri" => $this->_redirect_uri, "state" => $state, "scope" => $this->_scope); if (count($this->_extraArgs) > 0) { $params = array_merge($params, $this->_extraArgs); } $req = new WebRequest($to->authorizationURL()); $req->redirect($params, $this->_window_top); } // Request the Access Token if ($this->_context->get("state") == $this->getVar("state")) { $params = array("client_id" => $this->_client_id, "redirect_uri" => $this->_redirect_uri, "client_secret" => $this->_client_secret, "code" => $code, "grant_type" => "authorization_code"); $req = new WebRequest($to->accessTokenURL()); $result = $req->post($params); $accessToken = $to->decodeAccessToken($result); $this->setVar("access_token", $accessToken); $to->setAccessToken($accessToken); $this->saveAccessToken(); if ($this->_app_uri != "") { $req = new WebRequest($this->_app_uri); $response = $req->redirect(); } } } else { $to->setAccessToken($this->getVar('access_token')); } return $to; }
public function Process() { /** * @var Context */ $context = Context::getInstance(); $name = $context->getVirtualCommand(); if ($name == "") { $this->printHelp(); // END exit; } require_once PHPXMLNUKEDIR . "src/Xmlnuke/Library/webservice/webservice.php"; $className = '\\' . str_replace('.', '\\', $name); $rClass = new ReflectionClass($className); $class = $rClass->newInstance(); if ($class instanceof \Services_Webservice) { $class->handle(); } else { throw new InvalidArgumentException("Class '{$name}' is not a WebServices"); } }
/** * * @param type $field * @param type $value * @return \ByJG\AnyDataset\Repository\SingleRow */ public static function getInfoLocaleDB($field, $value) { if (self::$_localeData == null) { $file = new \Xmlnuke\Core\Processor\AnydatasetSetupFilenameProcessor('locale'); self::$_localeData = new \ByJG\AnyDataset\Repository\AnyDataset($file->FullQualifiedNameAndPath()); } if (!isset(self::$_localeDbCache[$field])) { $filter = new \ByJG\AnyDataset\Repository\IteratorFilter(); $filter->addRelation($field, \ByJG\AnyDataset\Enum\Relation::CONTAINS, $value); $it = self::$_localeData->getIterator($filter); if ($it->hasNext()) { self::$_localeDbCache[$field] = $it->moveNext(); } else { $sr = new \ByJG\AnyDataset\Repository\SingleRow(); \Xmlnuke\Core\Engine\Context::getInstance()->WriteWarningMessage("The language {$value} was not found in locale.anydata.xml file"); $sr->AddField('name', $value . ' ???'); $sr->AddField('shortname', $value); self::$_localeDbCache[$field] = $sr; } } return self::$_localeDbCache[$field]; }
<?php use Captcha\Captcha; use Xmlnuke\Core\Engine\Context; ############################################# # To create a XMLNuke capable PHP5 page # require_once "xmlnuke.inc.php"; ############################################# $context = Context::getInstance(); $cq = $context->get("xmlnuke.CAPTCHACHALLENGE") != "easy"; $c = intval($context->get("xmlnuke.CAPTCHALETTERS")); $captcha = new Captcha($context, $cq, $c); $captcha->show();
/** *@desc Generate $page, processing yours childs. *@param DOMNode $current *@return void */ public function generateObject($current) { $nodeWorking = XmlUtil::CreateChild($current, "editlist", ""); XmlUtil::AddAttribute($nodeWorking, "module", $this->_module); XmlUtil::AddAttribute($nodeWorking, "title", $this->_title); XmlUtil::AddAttribute($nodeWorking, "name", $this->_name); if ($this->_new) { XmlUtil::AddAttribute($nodeWorking, "new", "true"); } if ($this->_edit) { XmlUtil::AddAttribute($nodeWorking, "edit", "true"); } if ($this->_view) { XmlUtil::AddAttribute($nodeWorking, "view", "true"); } if ($this->_delete) { XmlUtil::AddAttribute($nodeWorking, "delete", "true"); } if ($this->_readonly) { XmlUtil::AddAttribute($nodeWorking, "readonly", "true"); } if ($this->_selecttype == SelectType::CHECKBOX) { XmlUtil::AddAttribute($nodeWorking, "selecttype", "check"); } if ($this->_extraParam != null) { foreach ($this->_extraParam as $key => $value) { $param = XmlUtil::CreateChild($nodeWorking, "param", ""); XmlUtil::AddAttribute($param, "name", $key); XmlUtil::AddAttribute($param, "value", $value); } } $processor = new ParamProcessor(); if ($this->_customButton != null) { for ($i = 0, $customButtonsLength = sizeof($this->_customButton); $i < $customButtonsLength; $i++) { // CustomButtons $cb $cb = $this->_customButton[$i]; if ($cb->enabled) { $nodeButton = XmlUtil::CreateChild($nodeWorking, "button"); if ($cb->url != "") { $cb->url = str_replace("&", "&", $processor->GetFullLink($cb->url)); } XmlUtil::AddAttribute($nodeButton, "custom", $i + 1); XmlUtil::AddAttribute($nodeButton, "acao", $cb->action); XmlUtil::AddAttribute($nodeButton, "alt", $cb->alternateText); XmlUtil::AddAttribute($nodeButton, "url", $cb->url); XmlUtil::AddAttribute($nodeButton, "img", $cb->icon); XmlUtil::AddAttribute($nodeButton, "multiple", $cb->multiple); XmlUtil::AddAttribute($nodeButton, "message", $cb->message); } } } $qtd = 0; $qtdPagina = 0; $page = 0; $started = !$this->_enablePages; $first = true; $firstRow = true; $summaryFields = array(); if (!$this->_it instanceof IteratorInterface) { throw new InvalidArgumentException('You have to pass an IteratorInterface object to the XmlEditList'); } // Generate XML With Data while ($this->_it->hasNext()) { //com.xmlnuke.anydataset.SingleRow $registro = $this->_it->moveNext(); // Insert fields if none is passed. if (sizeof($this->_fields) == 0) { foreach ($registro->getFieldNames() as $key => $fieldname) { $fieldtmp = new EditListField(true); $fieldtmp->editlistName = $fieldname; $fieldtmp->fieldData = $fieldname; $fieldtmp->fieldType = EditListFieldType::TEXT; $this->addEditListField($fieldtmp); if (sizeof($this->_fields) == 1) { $this->addEditListField($fieldtmp); } } } // Fill values if ($this->_enablePages) { $page = intval($qtd / $this->_qtdRows) + 1; $started = $page == $this->_curPage; } if ($started) { //\DOMNode $row = XmlUtil::CreateChild($nodeWorking, "row", ""); $currentNode = null; if (is_null($this->_fields)) { throw new InvalidArgumentException("No such EditListField Object", 850); } foreach ($this->_fields as $chave => $field) { if ($field->newColumn || $currentNode == null) { $currentNode = XmlUtil::CreateChild($row, "field", ""); if ($firstRow) { if (!$first) { XmlUtil::AddAttribute($currentNode, "name", $field->editlistName); } else { $first = false; } XmlUtil::AddAttribute($currentNode, "source", $field->fieldData); } } else { XmlUtil::CreateChild($currentNode, "br", ""); } $this->renderColumn($currentNode, $registro, $field); // Check if this fields requires summary if ($field->summary != EditListFieldSummary::NONE) { $summaryFields[$field->fieldData] += $this->_context->Language()->getDoubleVal($registro->getField($field->fieldData)); } } $firstRow = false; $qtdPagina++; } $qtd += 1; } // Generate SUMMARY Information if (sizeof($summaryFields) > 0) { $anydata = new AnyDataset(); $anydata->appendRow(); foreach ($this->_fields as $chave => $field) { switch ($field->summary) { case EditListFieldSummary::SUM: $value = $summaryFields[$field->fieldData]; break; case EditListFieldSummary::AVG: $value = $summaryFields[$field->fieldData] / $qtdPagina; break; case EditListFieldSummary::COUNT: $value = $qtdPagina; break; default: $value = ""; break; } $anydata->addField($field->fieldData, $value); } $ittemp = $anydata->getIterator(); $registro = $ittemp->moveNext(); $row = XmlUtil::CreateChild($nodeWorking, "row", ""); XmlUtil::AddAttribute($row, "total", "true"); foreach ($this->_fields as $chave => $field) { $currentNode = null; if ($field->newColumn || $currentNode == null) { $currentNode = XmlUtil::CreateChild($row, "field", ""); } else { XmlUtil::CreateChild($currentNode, "br", ""); } $this->renderColumn($currentNode, $registro, $field); } } // Create other properties XmlUtil::AddAttribute($nodeWorking, "cols", sizeof($this->_fields)); if ($this->_enablePages) { if ($this->_curPage > 1) { XmlUtil::AddAttribute($nodeWorking, "pageback", strval($this->_curPage - 1)); } if (!$started) { XmlUtil::AddAttribute($nodeWorking, "pagefwd", strval($this->_curPage + 1)); } XmlUtil::AddAttribute($nodeWorking, "curpage", strval($this->_curPage)); XmlUtil::AddAttribute($nodeWorking, "offset", strval($this->_qtdRows)); XmlUtil::AddAttribute($nodeWorking, "pages", strval($page)); } if ($this->_customsubmit != "") { XmlUtil::AddAttribute($nodeWorking, "customsubmit", $this->_customsubmit); } if (!is_null($this->_objXmlHeader)) { $nodeHeader = XmlUtil::CreateChild($nodeWorking, "xmlheader", ""); $this->_objXmlHeader->generateObject($nodeHeader); } return $nodeWorking; }
/** * Locate and create custom module if exists. Otherwise throw exception. * * Important: * A module must reside on a folder named 'Modules'. * You can call a module by \namespace\Modules\ModuleName or just \namespace\ModuleName * * @param string $modulename * @param object $o * @return IModule */ public static function GetModule($modulename, $o = null) { $context = Context::getInstance(); $basePath = ""; $classNameAr = explode('.', $modulename); if (strpos($modulename, '.Modules.') === false) { array_splice($classNameAr, count($classNameAr) - 1, 0, array('Modules')); } $className = '\\' . implode('\\', $classNameAr); if (class_exists($className, true)) { $result = new $className(); } else { throw new ModuleNotFoundException("Module \"{$modulename}\" not found"); } if (!$result instanceof IModule) { throw new InvalidArgumentException('Class "' . $className . '" is not a IModule object'); } // ---------------------------------------------------------- // Activate the Module // ---------------------------------------------------------- $xml = new XMLFilenameProcessor($modulename); $result->Setup($xml, $o); $urlSSL = ""; $isHttps = $context->get("HTTPS") == "on" || $context->get("HTTP_X_FORWARDED_PROTO") == "https"; $requireSSL = $result->requiresSSL(); if ($requireSSL == SSLAccess::ForcePlain && $isHttps) { $urlSSL = "http://" . $context->get("HTTP_HOST") . $context->get("REQUEST_URI"); } else { if ($requireSSL == SSLAccess::ForceSSL && !$isHttps) { $urlSSL = "https://" . $context->get("HTTP_HOST") . $context->get("REQUEST_URI"); } } $output = $result->getOutputFormat(); if ($output != null) { $context->setOutputFormat($output); ErrorHandler::getInstance()->setHandler($output); } if (strlen($urlSSL) > 0) { if ($context->get("REQUEST_METHOD") == "GET") { $context->redirectUrl($urlSSL); } else { echo "<html><body>"; echo "<div style='font-family: arial; font-size: 14px; background-color: lightblue; line-height: 24px; width: 80px; text-align: center'>Switching...</div>"; echo '<form action="' . $urlSSL . '" method="post">'; foreach ($_POST as $key => $value) { echo "<input type='hidden' name='{$key}' value='{$value}' />"; } echo "<script language='JavaScript'>document.forms[0].submit()</script>"; echo "</body></html>"; die; } } if ($result->requiresAuthentication()) { if ($result->getAuthMode() == AuthMode::Form && !$context->IsAuthenticated()) { throw new NotAuthenticatedException("You need login to access this feature"); } elseif ($result->getAuthMode() == AuthMode::HttpBasic) { $realm = 'Restricted area'; if (empty($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="' . $realm . '"'); header('HTTP/1.0 401 Unauthorized'); die('You have to provide your credentials before proceed.'); } else { $usersDb = $context->getUsersDatabase(); $users = $usersDb->getUserName($_SERVER['PHP_AUTH_USER']); if ($users == null) { header('HTTP/1.1 403 Forbiden'); die('Wrong Credentials!'); } $userTable = $usersDb->getUserTable(); // Check if Username and plain password is valid. If dont try to check if the SHA1 password is ok if (!$usersDb->isValidUser($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) { $password = $users->getField($userTable->Password); if ($password != $_SERVER['PHP_AUTH_PW']) { header('HTTP/1.1 403 Forbiden'); die('Wrong Credentials!'); } } $context->MakeLogin($users->getField($userTable->Username), $users->getField($userTable->Id)); } } elseif ($result->getAuthMode() == AuthMode::HttpDigest) { $realm = 'Restricted area'; if (empty($_SERVER['PHP_AUTH_DIGEST'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="' . $realm . '",qop="auth",nonce="' . uniqid() . '",opaque="' . md5($realm) . '"'); die('You have to provide your credentials before proceed.'); } // analyze the PHP_AUTH_DIGEST variable if (!($data = self::httpDigestParse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($data['username'])) { die('Wrong Credentials!'); } // Validate if the username and password are valid $usersDb = $context->getUsersDatabase(); $users = $usersDb->getUserName($data['username']); if ($users == null) { header('HTTP/1.1 403 Forbiden'); die('Wrong Credentials!'); } $userTable = $usersDb->getUserTable(); $password = $users->getField($userTable->Password); // generate the valid response $A1 = md5($data['username'] . ':' . $realm . ':' . $password); $A2 = md5($_SERVER['REQUEST_METHOD'] . ':' . $data['uri']); $valid_response = md5($A1 . ':' . $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $A2); if ($data['response'] != $valid_response) { header('HTTP/1.1 403 Forbiden'); die('Wrong Credentials!'); } // ok, valid username & password $context->MakeLogin($users->getField($userTable->Username), $users->getField($userTable->Id)); } if (!$result->accessGranted()) { $result->processInsufficientPrivilege(); } } return $result; }
/** * @param string $duallistaname * @return string[] */ public static function Parse($sortableName) { $context = Context::getInstance(); $cols = $context->get($sortableName . "_columns"); if ($cols == "") { return null; } $arCols = explode("|", $cols); $ret = array(); foreach ($arCols as $col) { $value = $context->get($sortableName . "_" . $col); $ret[$col] = explode("|", $value); } return $ret; }
/** * Process Vote. Note that the system ONLY process the vote if there is no another equal IP. * * @param int $width * @param int $height */ public function processVote($width = 450, $height = 400) { if ($this->_context->get("xcrt") == "") { // Is The Post values needed to process vote exists? if ($this->_context->get("xmlnuke_poll") != "" && $this->_context->get("xmlnuke_polllang") != "" && $this->_context->get("xmlnuke_pollanswer") != "") { $this->_poll = $this->_context->get("xmlnuke_poll"); $this->_lang = $this->_context->get("xmlnuke_polllang"); $ok = true; // Check if IP already voted -> Freeze IP for 5 days. if ($this->_isdb) { // Remove Old Entries $dbdata = new DBDataset($this->_connection); $sql = "delete from :table where register < now() - interval 5 day "; $sql = \ByJG\AnyDataset\Database\SQLHelper::createSafeSQL($sql, array(':table' => $this->_tbllastip)); $dbdata->execSQL($sql); // Check if exists $sql = "select count(1) from :table where ip = [[ip]] and name = [[name]] "; $sql = \ByJG\AnyDataset\Database\SQLHelper::createSafeSQL($sql, array(':table' => $this->_tbllastip)); $param = array("ip" => $this->_context->getClientIp(), "name" => $this->_poll); $count = $dbdata->getScalar($sql, $param); $ok = false; if ($count == 0) { $ok = true; $sql = "insert into :table (ip, name, register) values ([[ip]], [[name]], now()) "; $sql = \ByJG\AnyDataset\Database\SQLHelper::createSafeSQL($sql, array(':table' => $this->_tbllastip)); $param = array("ip" => $this->_context->getClientIp(), "name" => $this->_poll); try { $dbdata->execSQL($sql, $param); } catch (\PDOException $ex) { $ok = false; } } } // Is My IP Unique? If true I can process the vote. // Note if the poll name, lang and code are wrong the system does not do anything. if ($ok) { // Get Data $itf = new IteratorFilter(); $itf->addRelation("name", Relation::EQUAL, $this->_poll); $itf->addRelation("lang", Relation::EQUAL, $this->_lang); $itf->addRelation("code", Relation::EQUAL, $this->_context->get("xmlnuke_pollanswer")); if ($this->_isdb) { $dbdata = new DBDataset($this->_connection); $param = array(); $sql = "update :table set votes = IFNULL(votes,0) + 1 where :filter "; $sql = \ByJG\AnyDataset\Database\SQLHelper::createSafeSQL($sql, array(':table' => $this->_tblanswer, ':filter' => $itf->getFilter(IteratorFilter::SQL, $param))); $dbdata->execSQL($sql, $param); } else { $this->getAnyData(); $itAnswer = $this->_anyAnswer->getIterator($itf); if ($itAnswer->hasNext()) { $sr = $itAnswer->moveNext(); $sr->setField("votes", intval($sr->getField("votes")) + 1); $this->_anyAnswer->Save(); } } } $this->_processed = true; } } else { $this->_processed = true; } $this->_width = $width; $this->_height = $height; }
/** *@desc Contains specific instructions to generate all XML informations-> This method is processed only one time-> Usually is the last method processed-> *@param DOMNode $current \DOMNode where the XML will be created-> *@return void */ public function generateObject($current) { // Improve Security $wrongway = !$this->_edit && ($this->_currentAction == self::ACTION_EDIT || $this->_currentAction == self::ACTION_EDIT_CONFIRM); $wrongway = $wrongway || !$this->_new && ($this->_currentAction == self::ACTION_NEW || $this->_currentAction == self::ACTION_NEW_CONFIRM); $wrongway = $wrongway || !$this->_delete && ($this->_currentAction == self::ACTION_DELETE || $this->_currentAction == self::ACTION_DELETE_CONFIRM); if ($wrongway) { $message = $this->_lang->Value("MSG_DONT_HAVEGRANT"); $p = new XmlParagraphCollection(); $p->addXmlnukeObject(new XmlnukeText($message, true, true, false)); $p->generateObject($current); return; } // Checkings! if ($this->_context->get(self::PARAM_CANCEL) != "") { $this->listAllRecords()->generateObject($current); } else { if (strpos($this->_currentAction, "_confirm") !== false) { try { $validateResult = $this->updateRecord(); } catch (Exception $ex) { $nvc = array($ex->getMessage()); //XmlParagraphCollection $p $p = new XmlParagraphCollection(); $p->addXmlnukeObject(new XmlEasyList(EasyListType::UNORDEREDLIST, "Error", $this->_lang->Value("ERR_FOUND"), $nvc, "")); //XmlAnchorCollection $a $a = new XmlAnchorCollection("javascript:history.go(-1)", ""); $a->addXmlnukeObject(new XmlnukeText($this->_lang->Value("TXT_GOBACK"))); $p->addXmlnukeObject($a); $validateResult = $p; } if (is_null($validateResult)) { $this->_context->redirectUrl($this->redirProcessPage(false)); } else { $validateResult->generateObject($current); if ($this->_currentAction != XmlnukeCrudBase::ACTION_NEW_CONFIRM) { $this->showCurrentRecord()->generateObject($current); } } } else { if ($this->_currentAction == self::ACTION_MSG) { $this->showResultMessage()->generateObject($current); $this->listAllRecords()->generateObject($current); } else { if ($this->_currentAction == self::ACTION_NEW || $this->_currentAction == self::ACTION_VIEW || $this->_currentAction == self::ACTION_EDIT || $this->_currentAction == self::ACTION_DELETE) { $this->showCurrentRecord()->generateObject($current); } else { $this->listAllRecords()->generateObject($current); } } } } }
/** * Validate if the text type by the user matchs with the text generated by the * XmlInputImageValidate is correct or not * * @param Context $context * @param string $text */ public static function validateText($context) { return Captcha::TextIsValid($context->get("imagevalidate")); }
/** * Parse RESULTSS from DualList object * * @param Context $context * @param string $duallistaname * @return string[] */ public static function Parse($context, $duallistaname) { $val = $context->get($duallistaname); if ($val != "") { return explode(",", $val); } else { return array(); } }
public function Process() { $context = Context::getInstance(); /* You must have pass a parameter called CN. Example: chart.php?cn=NAME XmlNuke will Try load the class called "NAME" and execute the Method: getChartObject() */ try { $cn = $context->get("cn"); if ($cn != "") { $cn = '\\' . str_replace('.', '\\', $context->get("cn")); $chartObj = new $cn(); $chart = $chartObj->getChartObject(); //$chart = new \Xmlnuke\Core\Classes\ChartObject(); $params = array(); if ($chart->getChartType() == ChartType::Area) { $params['cht'] = '1c'; } else { if ($chart->getChartType() == ChartType::Line) { $params['cht'] = '1c'; } else { if ($chart->getChartType() == ChartType::Pie && !$chart->getIs3d()) { $params['cht'] = 'p'; } else { if ($chart->getChartType() == ChartType::Pie && $chart->getIs3d()) { $params['cht'] = 'p3'; } else { if ($chart->getChartType() == ChartType::Donut) { $params['cht'] = 'p'; } else { if ($chart->getChartType() == ChartType::Bar) { $params['cht'] = 'bhg'; } else { if ($chart->getChartType() == ChartType::Column) { $params['cht'] = 'bvg'; } else { $params['cht'] = 'bvg'; } } } } } } } /* The formula below is necessary because Google have a maximum limit of 480.000. This is basic rule of three R = W/H --> W = R*H Wo*Ho => (Wo*Ho)/10000 R*H² => 30 . . . H² = (30*Wo*Ho) / (R*((Wo*Ho)/10000)) */ $size = $chart->getWidth() * $chart->getHeight() / 10000; if ($size > 30) { $ratio = $chart->getWidth() / $chart->getHeight(); $chart->setHeight(intval(sqrt(30 * $chart->getWidth() * $chart->getHeight() / ($ratio * $size)))); $chart->setWidth(intval($ratio * $chart->getHeight())); } $params['chs'] = $chart->getWidth() . 'x' . $chart->getHeight(); $iter = $chart->getSerie(); $params['chd'] = 't:'; $data = array(); foreach ($iter as $serie) { if (!isset($params['chdl'])) { $serieData = $serie->toArray(); unset($serieData['data_0']); $params['chdl'] = implode('|', $serieData); } else { $serieData = $serie->toArray(); for ($i = 1; $i < count($serieData); $i++) { if (!isset($data[$i])) { $data[$i] = array(); } $data[$i][] = $serieData["data_{$i}"]; } } } foreach ($data as $itemData) { $params['chd'] .= implode(',', $itemData) . "|"; } $params['chd'] = substr($params['chd'], 0, strlen($params['chd']) - 1); $colors = array('#FFF8A3', '#A9CC8F', '#B2C8D9', '#BEA37A', '#F3AA79', '#B5B5A9', '#E6A5A4', '#F8D753', '#5C9746', '#3E75A7', '#7A653E', '#E1662A', '#74796F', '#C4384F', '#F0B400', '#1E6C0B', '#00488C', '#332600', '#D84000', '#434C43', '#B30023', '#FAE16B', '#82B16A', '#779DBF', '#907A52', '#EB8953', '#8A8D82', '#D6707B', '#F3C01C', '#3D8128', '#205F9A', '#63522B', '#DC5313', '#5D645A', '#BC1C39'); $params['chco'] = str_replace('#', '', implode('|', $colors)); $strParams = ""; foreach ($params as $key => $value) { $strParams .= $key . "=" . str_replace("'", "", $value) . "&"; } $strParams .= 'chds=a'; header("Content-Type: image/png"); $imageData = file_get_contents('http://chart.apis.google.com/chart?cht=p3&chd=t:39,47,8,4,2&chs=380x180&chl=IE|Firefox|Chrome|Safari|Opera'); echo $imageData; } } catch (Exception $ex) { echo "Chart Error: " . $ex->getMessage(); } }
/** * * @return BaseProcessResult */ protected function getProcessResult() { $context = Context::getInstance(); $className = $context->get('xmlnuke.POST_PROCESS_RESULT'); if (empty($className)) { $className = "\\Xmlnuke\\Core\\Processor\\BaseProcessResult"; } $class = new $className(); return $class; }