Example #1
1
 public function encode(\Esendex\Model\DispatchMessage $message)
 {
     if (strlen($message->originator()) < 1) {
         throw new ArgumentException("Originator is invalid");
     }
     if (strlen($message->recipient()) < 1) {
         throw new ArgumentException("Recipient is invalid");
     }
     if ($message->validityPeriod() > 72) {
         throw new ArgumentException("Validity too long, must be less or equal to than 72");
     }
     $doc = new \SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><messages />", 0, false, Api::NS);
     $doc->accountreference = $this->reference;
     $child = $doc->addChild("message");
     $child->from = $message->originator();
     $child->to = $message->recipient();
     $child->body = $message->body();
     $child->type = $message->type();
     if ($message->validityPeriod() > 0) {
         $child->validity = $message->validityPeriod();
     }
     if ($message->language() != null) {
         $child->lang = $message->language();
     }
     return $doc->asXML();
 }
Example #2
0
 /**
  * This method saves all RatePAY Requests and Responses in the database
  * 
  * @param array $loggingInfo
  * @param SimpleXMLElement|null $request
  * @param SimpleXMLElement|null $response
  */
 public function log($loggingInfo, $request, $response)
 {
     $responseXML = '';
     $result = "Service offline.";
     $resultCode = "Service offline.";
     $reasonText = '';
     if (isset($request->content->customer->{'bank-account'})) {
         $request->content->customer->{'bank-account'}->owner = '(hidden)';
         if (isset($request->content->customer->{'bank-account'}->{'iban'})) {
             $request->content->customer->{'bank-account'}->{'iban'} = '(hidden)';
             $request->content->customer->{'bank-account'}->{'bic-swift'} = '(hidden)';
         } else {
             $request->content->customer->{'bank-account'}->{'bank-account-number'} = '(hidden)';
             $request->content->customer->{'bank-account'}->{'bank-code'} = '(hidden)';
         }
     }
     if ($response != null && isset($response) && $response->asXML() != '') {
         $result = (string) $response->head->processing->result;
         $resultCode = (string) $response->head->processing->result->attributes()->code;
         $responseXML = $response->asXML();
         $reasonText = (string) $response->head->processing->reason;
         if ($loggingInfo['requestType'] == 'PAYMENT_INIT') {
             $loggingInfo['transactionId'] = (string) $response->head->{'transaction-id'};
         }
     }
     $this->setId(null)->setOrderNumber(!empty($loggingInfo['orderId']) ? $loggingInfo['orderId'] : 'n/a')->setTransactionId(!empty($loggingInfo['transactionId']) ? $loggingInfo['transactionId'] : 'n/a')->setPaymentMethod(!empty($loggingInfo['paymentMethod']) ? $loggingInfo['paymentMethod'] : 'n/a')->setPaymentType(!empty($loggingInfo['requestType']) ? $loggingInfo['requestType'] : 'n/a')->setPaymentSubtype(!empty($loggingInfo['requestSubType']) ? $loggingInfo['requestSubType'] : 'n/a')->setResult($result)->setRequest($request->asXML())->setRequest($request->asXML())->setResponse($responseXML)->setResultCode($resultCode)->setName($loggingInfo['firstName'] . " " . $loggingInfo['lastName'])->setReason($reasonText)->save();
 }
Example #3
0
 protected function cron(array $args = array())
 {
     //TODO Данные об индексируемых страницах брать из ResManager
     global $general_s;
     //TODO переделать global на параметры
     $this->sxe = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>' . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
     // Главная
     $this->addUrlToSitemap('/', time(), self::NODE_CHANGEFREQ_DAILY, 1.0);
     // Категории
     $categories = $this->repositoryFactory->getCategoryRepository()->query()->getEntity(PHP_INT_MAX);
     foreach ($categories as $category) {
         $this->addUrlToSitemap("/category/{$category->id}", null, self::NODE_CHANGEFREQ_DAILY);
     }
     unset($categories);
     // Вопросы
     $mainQuestions = $this->repositoryFactory->getMainQuestionRepository()->query()->addFilterField('active', true)->getEntity(PHP_INT_MAX);
     foreach ($mainQuestions as $mainQuestion) {
         $this->addUrlToSitemap("/question/{$mainQuestion->id}", $mainQuestion->createDate);
     }
     unset($mainQuestions);
     // Сохранение XML
     $result = $this->sxe->asXML(pathinfo($_SERVER['SCRIPT_FILENAME'], PATHINFO_DIRNAME) . "/{$general_s['sitemap_file']}");
     if ($result === false) {
         $this->setResponseCode(HttpResponseCode::INTERNAL_SERVER_ERROR);
         $this->addResponseMessage("Ошибка создания карты сайта! Проверьте права на запись в файл " . basename($general_s['sitemap_file']), self::MESS_ERROR);
     } else {
         $this->addResponseMessage('Карта сайта успешно создана!');
     }
     unset($this->sxe);
 }
Example #4
0
 public function buildXml($xml)
 {
     $this->root->asXML($xml);
     $xmlContent = $this->getContentXMLFile($xml);
     $this->deleteXMLFile($xml);
     return $xmlContent;
 }
Example #5
0
 /**
  * Format xml with indents and line breaks
  *
  * @return string
  * @author Gary Malcolm
  */
 public function asPrettyXML()
 {
     $string = $this->_xml->asXML();
     // put each element on it's own line
     $string = preg_replace("/>\\s*</", ">\n<", $string);
     // each element to own array
     $xmlArray = explode("\n", $string);
     // holds indentation
     $currIndent = 0;
     $indent = "    ";
     // set xml element first by shifting of initial element
     $string = array_shift($xmlArray) . "\n";
     foreach ($xmlArray as $element) {
         // find open only tags... add name to stack, and print to string
         // increment currIndent
         if (preg_match('/^<([\\w])+[^>\\/]*>$/U', $element)) {
             $string .= str_repeat($indent, $currIndent) . $element . "\n";
             $currIndent += 1;
         } elseif (preg_match('/^<\\/.+>$/', $element)) {
             $currIndent -= 1;
             $string .= str_repeat($indent, $currIndent) . $element . "\n";
         } else {
             $string .= str_repeat($indent, $currIndent) . $element . "\n";
         }
     }
     return $string;
 }
Example #6
0
 /**
  * Export
  */
 protected function createFile()
 {
     $this->XML = new \SimpleXMLElement($this->emptyXml());
     $this->Track = $this->XML->trk->trkseg;
     $this->setTrack();
     $this->FileContent = $this->XML->asXML();
     $this->formatFileContentAsXML();
 }
 /**
  * Dump manifest structure into a XML string.
  *
  * @return string
  */
 public function dump()
 {
     // Create a new XML document
     $document = new \DOMDocument('1.0', 'utf-8');
     $document->preserveWhiteSpace = false;
     $document->formatOutput = true;
     $document->loadXML($this->xml->asXML());
     return $document->saveXML();
 }
Example #8
0
 /**
  * Export
  */
 protected function createFile()
 {
     $this->XML = new \SimpleXMLElement($this->emptyXml());
     $this->Activity = $this->XML->AthleteLog->Activity;
     $this->setGeneralInfo();
     $this->setTrack();
     $this->FileContent = $this->XML->asXML();
     $this->formatFileContentAsXML();
 }
Example #9
0
 /**
  * Export
  */
 protected function createFile()
 {
     $this->XML = new \SimpleXMLElement($this->emptyXml());
     $this->Activity = $this->XML->Activities->Activity;
     $this->setInternalIndicators();
     $this->setGeneralInfo();
     $this->setLaps();
     $this->FileContent = $this->XML->asXML();
     $this->formatFileContentAsXML();
 }
Example #10
0
 public static function saveConfig()
 {
     $filePath = getcwd() . self::CONFIG_FOLDER . self::CONFIG_NAME;
     if (!empty(self::$configTree)) {
         $dom = new \DOMDocument("1.0");
         $dom->formatOutput = true;
         $dom->loadXML(self::$configTree->asXML());
         file_put_contents($filePath, $dom->saveXML());
     }
 }
Example #11
0
 /**
  * Insert a row into the blacklist.xml
  * 
  * @param type $type
  * @param type $table
  * @param type $colum
  */
 function createItem($type, $table, $colum)
 {
     $library = new SimpleXMLElement('xml/blacklist.xml', null, true);
     $book = $library->addChild('ITEM');
     $book->addAttribute('ID', $this->getLastIDItem() + 1);
     $book->addChild('TYPE', $type);
     $book->addChild('TABLE', $table);
     $book->addChild('COLUMN', $colum);
     echo $library->asXML();
     $library->asXML('xml/blacklist.xml');
 }
Example #12
0
 /**
  * Set file content
  */
 protected function setFileContent()
 {
     if (!$this->Context->hasRoute() || !$this->Context->route()->hasPositionData()) {
         $this->addError(__('The training does not contain gps-data and cannot be saved as gpx-file.'));
         return;
     }
     $this->XML = new SimpleXMLElement($this->getEmptyXml());
     $this->Track = $this->XML->trk->trkseg;
     $this->setTrack();
     $this->FileContent = $this->XML->asXML();
     $this->formatFileContentAsXML();
 }
Example #13
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //Проверим запущена ли команда уже, если да то выходим
     $lockHandler = new LockHandler('xml.generate.lock');
     if (!$lockHandler->lock()) {
         $output->writeln('Command is locked');
         return 0;
     }
     $email = $input->getArgument('email');
     if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
         throw new InvalidArgumentException('The argument must be valid email');
     }
     $container = $this->getContainer();
     $em = $container->get('doctrine.orm.entity_manager');
     $persons = $em->getRepository('AppBundle:Person')->findAll();
     $serializer = SerializerBuilder::create()->build();
     //ищем файл XML для экспорта, если нет - создаем
     $fs = new Filesystem();
     $path = $container->get('kernel')->getRootDir() . '/data/result.xml';
     if ($fs->exists($path)) {
         $content = file_get_contents($path);
         $xml = new \SimpleXMLElement($content);
     } else {
         $xml = new \SimpleXMLElement('<persons/>');
         $xml->asXML($path);
     }
     //идем по всем Person и ищем соответствующий айди в XML
     foreach ($persons as $person) {
         $serialized = $serializer->serialize($person, 'xml');
         $t = $xml->xpath(sprintf('//person[@id="%d"]', $person->getId()));
         if ($t) {
             //если находим - удаляем нод
             $dom = dom_import_simplexml($t[0]);
             $dom->parentNode->removeChild($dom);
         }
         //вставляем новый нод
         $target = $xml->xpath('/persons');
         $dom = dom_import_simplexml($target[0]);
         $insertDom = $dom->ownerDocument->importNode(dom_import_simplexml(new \SimpleXMLElement($serialized)), true);
         $dom->appendChild($insertDom);
     }
     $xml->asXML($path);
     $publicPath = $container->get('kernel')->getRootDir() . '/../web/' . XmlCommand::XML_PATH;
     $fs->copy($path, $publicPath);
     $timeFinished = new \DateTime();
     if ($email) {
         $context = $container->get('router')->getContext();
         $message = \Swift_Message::newInstance()->setSubject('Task finished')->setFrom('noreply@' . $context->getHost())->setTo($email)->setBody($container->get('templating')->render('emails/xmlFinished.html.twig', ['taskName' => XmlCommand::TASK_NAME, 'time' => $timeFinished, 'link' => $context->getHost() . '/' . XmlCommand::XML_PATH]), 'text/html');
         $container->get('mailer')->send($message);
     }
     return 0;
 }
Example #14
0
 /**
  * Set file content
  */
 protected function setFileContent()
 {
     if (!$this->Context->hasRoute() || !$this->Context->route()->hasPositionData()) {
         $this->addError(__('The training does not contain gps-data and cannot be saved as tcx-file.'));
         return;
     }
     $this->XML = new SimpleXMLElement($this->getEmptyXml());
     $this->Activity = $this->XML->Activities->Activity;
     $this->setGeneralInfo();
     $this->setLaps();
     $this->FileContent = $this->XML->asXML();
     $this->formatFileContentAsXML();
 }
Example #15
0
 /**
  * @param string|null $expectedResponse the response type which expected
  * @param bool $useSession should the request use an automatic session id?
  * @param bool $secondFail is this the second try of this request?
  * @return \SimpleXMLElement
  * @throws \Exception
  */
 public function send($expectedResponse = null, $useSession = true, $try = 1)
 {
     $this->request['RequestId'] = '33300000-2200-1000-0000-' . substr(md5(uniqid()), 0, 12);
     $this->request['Version'] = $this->smartHome->getVersion();
     if ($useSession) {
         $this->request['SessionId'] = $this->smartHome->getSessionId();
     }
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, 'https://' . $this->smartHome->getHost() . '/' . $this->action);
     if (($clientId = $this->smartHome->getClientId()) !== null || $this->action === 'upd') {
         if ($clientId === null && $this->action === 'upd') {
             throw new \Exception('Unable to get updates if no client id is specified!', 107);
         }
         curl_setopt($ch, CURLOPT_HTTPHEADER, array('ClientId: ' . $clientId));
     }
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_HEADER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt($ch, CURLOPT_SSLVERSION, 3);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->action === 'upd' ? 'upd' : $this->request->asXML());
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
     list($header, $body) = explode("\r\n\r\n", curl_exec($ch), 2);
     $this->setResponse($body);
     $this->setResponseHeader($header);
     curl_close($ch);
     /**
      * Fix the problems
      */
     $responseType = (string) $this->getResponse()->attributes('xsi', true)->type;
     if ($expectedResponse !== null && strtolower($responseType) !== strtolower($expectedResponse)) {
         if ($try > 1) {
             throw new \Exception('Request failed second time. Error: ' . $responseType, 99);
         }
         if ($responseType === 'GenericSHCErrorResponse' || $responseType === 'AuthenticationErrorResponse') {
             $this->smartHome->login(++$try);
             return $this->send($expectedResponse, $useSession, $try);
         } else {
             $try--;
         }
         if ($responseType === 'VersionMismatchErrorResponse') {
             $this->smartHome->setVersion((string) $this->getResponse()->attributes()->ExpectedVersion);
             return $this->send($expectedResponse, $useSession, ++$try);
         } else {
             $try--;
         }
     }
     return $this->getResponse();
 }
Example #16
0
 public function execute()
 {
     //Build command arguments..
     foreach ($this->arguments as $arg) {
         $this->command->addChild("arg", $arg);
     }
     $reqStr = $this->request->asXML();
     $curl = curl_init("http://localhost:8181/rpc/surrogate_api/xmlcmd");
     curl_setopt($curl, CURLOPT_POST, TRUE);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($curl, CURLOPT_POSTFIELDS, $reqStr);
     //echo "Requesting: \n$reqStr\n\n";
     $this->response = curl_exec($curl);
     curl_close($curl);
 }
 /**
  * @param ContentType $contentType
  * @return Response
  */
 public function generateXml(ContentType $contentType)
 {
     $allContent = $this->dm->createQueryBuilder('IntegratedContentBundle:Content\\Content')->hydrate(false)->field('contentType')->equals($contentType->getId())->getQuery()->execute();
     $fieldNames = [];
     foreach ($contentType->getFields() as $field) {
         $fieldNames[$field->getName()] = $field->getName();
     }
     $xml = new \SimpleXMLElement('<xml/>');
     $contents = $xml->addChild('content');
     $mainFields = ['_id', 'contentType', 'createdAt', 'updatedAt', 'publishTime', 'channels', 'class'];
     foreach ($allContent as $content) {
         /* main fields*/
         /** @var Content $content */
         $node = $contents->addChild($content['contentType']);
         $node->addAttribute('id', $content['_id']);
         $node->addChild('contentType', $content['contentType']);
         $node->addChild('createdAt', date('Y-m-d H:i:s', $content['createdAt']->sec));
         $node->addChild('updatedAt', date('Y-m-d H:i:s', $content['updatedAt']->sec));
         $publishTime = $node->addChild('publishTime');
         $publishTime->addChild('startTime', date('Y-m-d H:i:s', $content['publishTime']['startDate']->sec));
         $publishTime->addChild('endTime', date('Y-m-d H:i:s', $content['publishTime']['endDate']->sec));
         $channels = $node->addChild('channels');
         if (isset($content['channels'])) {
             foreach ($content['channels'] as $channel) {
                 $channels->addChild('channel', $channel['$id']);
             }
         }
         /* main fields end */
         foreach ($content as $name => $value) {
             if (!in_array($name, $mainFields) && is_scalar($value)) {
                 $node->addChild($name, $value);
             }
             /* @TODO add data from Embed and Relation Classes */
             if (is_array($value)) {
                 /**/
             }
             /* About 5 seconds until to throwing exception with "execution time exceeded", abort export */
             $executionTime = microtime(1) - $this->startTime;
             $allowedTime = ini_get('max_execution_time');
             if ($allowedTime - $executionTime < 5) {
                 $partialExport = $xml->addChild('PARTIAL_EXPORT');
                 $partialExport->addChild('message', 'THIS IS PARTIAL EXPORT');
                 return new Response($xml->asXML(), 200, ['Content-type' => 'text/xml']);
             }
         }
     }
     return new Response($xml->asXML(), 200, ['Content-type' => 'text/xml']);
 }
Example #18
0
 /**
  * Starts the processing of the current rss-request.
  * Acts like some kind of a main-method, so manages the further control-flow.
  */
 public function processSvn2RssRequest($strFeedParam = "")
 {
     try {
         //start by loading the config-file
         $objConfig = new ConfigReader($strFeedParam);
         //create the svn-reader and pass control
         $objSvnReader = new SvnReader($objConfig);
         $strSvnLog = $objSvnReader->getSvnLogContent();
         //create rss-nodes out of the logfile
         $objRssConverter = new Log2RssConverter($objConfig);
         $objRssRootNode = $objRssConverter->generateRssNodesFromLogContent($strSvnLog);
         $this->strOutput = $objRssRootNode->asXML();
     } catch (Svn2RssException $objException) {
         //Wrap error-message as a rss-feed element, too
         $objFeedRootNode = new SimpleXMLElement("<rss version=\"2.0\"></rss>");
         $objChannel = $objFeedRootNode->addChild("channel");
         $objChannel->addChild("title", "Error");
         $objChannel->addChild("description", "Error while loading feed");
         $objChannel->addChild("link", "n.a.");
         $objChannel->addChild("pubDate", strftime("%a, %d %b %Y %H:%M:%S GMT", time()));
         $objRssItemNode = $objChannel->addChild("item");
         $objRssItemNode->addChild("title", "Something bad happened: \n" . $objException->getMessage() . "");
         $objRssItemNode->addChild("description", "Something bad happened: \n" . $objException->getMessage() . "");
         $objRssItemNode->addChild("pubDate", strftime("%a, %d %b %Y %H:%M:%S GMT", time()));
         $this->strOutput = $objFeedRootNode->asXML();
     }
 }
Example #19
0
 /**
  * Prepare and return XML string for MS Excel XML from array
  *
  * @param array $fields
  * @return string
  */
 protected function _getXmlString(array $fields = array())
 {
     $xmlHeader = '<' . '?xml version="1.0"?' . '>' . "\n";
     $xmlRegexp = '/^<cell><row>(.*)?<\\/row><\\/cell>\\s?$/ms';
     if (is_null($this->_xmlElement)) {
         $xmlString = $xmlHeader . '<cell><row></row></cell>';
         $this->_xmlElement = new SimpleXMLElement($xmlString, LIBXML_NOBLANKS);
     }
     $xmlData = array();
     $xmlData[] = '<Row>';
     foreach ($fields as $value) {
         $this->_xmlElement->row = htmlspecialchars($value);
         $value = str_replace($xmlHeader, '', $this->_xmlElement->asXML());
         $value = preg_replace($xmlRegexp, '\\1', $value);
         $dataType = "String";
         if (is_numeric($value)) {
             $dataType = "Number";
         }
         $value = str_replace("\r\n", '&#10;', $value);
         $value = str_replace("\r", '&#10;', $value);
         $value = str_replace("\n", '&#10;', $value);
         $xmlData[] = '<Cell><Data ss:Type="' . $dataType . '">' . $value . '</Data></Cell>';
     }
     $xmlData[] = '</Row>';
     return join('', $xmlData);
 }
Example #20
0
/**
* Takes xml as a string and returns it nicely indented
*
* @param string $xml The xml to beautify
* @param boolean $html_output If the xml should be formatted for display on an html page
* @return string The beautified xml
*/
function xml_pretty_printer($xml, $html_output = FALSE)
{
    $xml_obj = new SimpleXMLElement($xml);
    $xml_lines = explode("n", $xml_obj->asXML());
    $indent_level = 0;
    $new_xml_lines = array();
    foreach ($xml_lines as $xml_line) {
        if (preg_match('#(<[a-z0-9:-]+((s+[a-z0-9:-]+="[^"]+")*)?>.*<s*/s*[^>]+>)|(<[a-z0-9:-]+((s+[a-z0-9:-]+="[^"]+")*)?s*/s*>)#i', $xml_line)) {
            $new_line = str_pad('', $indent_level * 4) . $xml_line;
            $new_xml_lines[] = $new_line;
        } elseif (preg_match('#<[a-z0-9:-]+((s+[a-z0-9:-]+="[^"]+")*)?>#i', $xml_line)) {
            $new_line = str_pad('', $indent_level * 4) . $xml_line;
            $indent_level++;
            $new_xml_lines[] = $new_line;
        } elseif (preg_match('#<s*/s*[^>/]+>#i', $xml_line)) {
            $indent_level--;
            if (trim($new_xml_lines[sizeof($new_xml_lines) - 1]) == trim(str_replace("/", "", $xml_line))) {
                $new_xml_lines[sizeof($new_xml_lines) - 1] .= $xml_line;
            } else {
                $new_line = str_pad('', $indent_level * 4) . $xml_line;
                $new_xml_lines[] = $new_line;
            }
        } else {
            $new_line = str_pad('', $indent_level * 4) . $xml_line;
            $new_xml_lines[] = $new_line;
        }
    }
    $xml = join("n", $new_xml_lines);
    return $html_output ? '<pre>' . htmlentities($xml) . '</pre>' : $xml;
}
Example #21
0
 public function indexAction()
 {
     $url = $this->getRequest()->getParam('url');
     $xmlString = '<?xml version="1.0" standalone="yes"?><response></response>';
     $xml = new SimpleXMLElement($xmlString);
     if (strlen($url) < 1) {
         $xml->addChild('status', 'failed no url passed');
     } else {
         $shortid = $this->db->fetchCol("select * from urls where url = ?", $url);
         $config = Zend_Registry::getInstance();
         $sh = $config->get('configuration');
         if ($shortid[0]) {
             $hex = dechex($shortid[0]);
             $short = $sh->siteroot . $hex;
         } else {
             //if not insert then return the id
             $data = array('url' => $url, 'createdate' => date("Y-m-d h:i:s"), 'remoteip' => Pandamp_Lib_Formater::getRealIpAddr());
             $insert = $this->db->insert('urls', $data);
             $id = $this->db->lastInsertId('urls', 'id');
             $hex = dechex($id);
             $short = $sh->siteroot . $hex;
         }
         $xml->addChild('holurl', $short);
         $xml->addChild('status', 'success');
     }
     $out = $xml->asXML();
     //This returns the XML xmlreponse should be key value pairs
     $this->getResponse()->setHeader('Content-Type', 'text/xml')->setBody($out);
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender();
 }
Example #22
0
 public function __construct($lg = 'fr')
 {
     parent::__construct($lg);
     $this->lg = URL . 't/' . $lg . '/';
     $base = $this->lg;
     $this->xmlOut = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
     $this->xmlOut .= "<url><loc>{$base}</loc><priority>1.00</priority><changefreq>daily</changefreq></url>";
     $this->Gen();
     $this->xmlOut .= '</urlset>';
     $fileSitemap = BASE . 'sitemap.xml';
     $newXml = new SimpleXMLElement($this->xmlOut);
     $newXml->asXML($fileSitemap);
     $aL = $this->allLanguages;
     foreach ($aL as $k => $v) {
         parent::__construct($k);
         $this->lg = URL . 't/' . $k . '/';
         $base = $this->lg;
         $this->xmlOut = '';
         $this->xmlOut = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
         $this->xmlOut .= "<url><loc>{$base}</loc><priority>1.00</priority><changefreq>daily</changefreq></url>";
         $this->Gen();
         $this->xmlOut .= '</urlset>';
         $fileSitemap = BASE . 't/' . $k . '/sitemap.xml';
         $newXml = new SimpleXMLElement($this->xmlOut);
         $newXml->asXML($fileSitemap);
     }
 }
Example #23
0
 /** Prettifies an XML string into a human-readable and indented work of art
  *  @param string $xml The XML as a string
  *  @param boolean $html_output True if the output should be escaped (for use in HTML)
  */
 public static function xmlpp($xml, $html_output = false)
 {
     $xml_obj = new SimpleXMLElement($xml);
     $level = 4;
     $indent = 0;
     // current indentation level
     $pretty = array();
     // get an array containing each XML element
     $xml = explode("\n", preg_replace('/>\\s*</', ">\n<", $xml_obj->asXML()));
     // shift off opening XML tag if present
     if (count($xml) && preg_match('/^<\\?\\s*xml/', $xml[0])) {
         $pretty[] = array_shift($xml);
     }
     foreach ($xml as $el) {
         if (preg_match('/^<([\\w])+[^>\\/]*>$/U', $el)) {
             // opening tag, increase indent
             $pretty[] = str_repeat(' ', $indent) . $el;
             $indent += $level;
         } else {
             if (preg_match('/^<\\/.+>$/', $el)) {
                 $indent -= $level;
                 // closing tag, decrease indent
             }
             if ($indent < 0) {
                 $indent += $level;
             }
             $pretty[] = str_repeat(' ', $indent) . $el;
         }
     }
     $xml = implode("\n", $pretty);
     return $html_output ? htmlentities($xml) : $xml;
 }
Example #24
0
File: Form.php Project: Hywan/moxl
 public function __toString()
 {
     $xml = '<x xmlns="jabber:x:data" type="submit"></x>';
     $node = new \SimpleXMLElement($xml);
     foreach ($this->_data as $key => $value) {
         $field = $node->addChild('field');
         if ($value == 'true') {
             $value = '1';
         }
         if ($value == 'false') {
             $value = '0';
         }
         $field->addChild('value', trim($value->value));
         /*if(isset($value->attributes->required))
           $field->addChild('required', '');*/
         $field->addAttribute('var', $value->attributes->name);
         //$field->addAttribute('type', $value->attributes->type);
         //$field->addAttribute('label', $value->attributes->label);
     }
     $xml = $node->asXML();
     $doc = new \DOMDocument();
     $doc->loadXML($xml);
     $doc->formatOutput = true;
     return substr($doc->saveXML(), strpos($doc->saveXML(), "\n") + 1);
 }
Example #25
0
 /**
  * Generate TestCase XML
  */
 public function generateXml()
 {
     $xml = simplexml_load_file(__DIR__ . '/testcase.xml');
     $xmlObject = new \SimpleXMLElement($xml->asXML());
     foreach ($xmlObject as $item) {
         $data = $this->getTicketData((array) $item);
         foreach ($data as $key => $field) {
             if ($item->xpath($key)) {
                 continue;
             }
             if (!is_array($field)) {
                 $item->addChild($key, $field);
             } else {
                 $node = $item->addChild($key);
                 foreach ($field as $value) {
                     $node->addChild(substr($key, 0, -1), $value);
                 }
             }
         }
         $this->cnt++;
     }
     // Format XML file
     $dom = new \DOMDocument("1.0");
     $dom->preserveWhiteSpace = false;
     $dom->formatOutput = true;
     $dom->loadXML($xmlObject->asXML());
     $dom->save(__DIR__ . '/testcase.xml');
     \Mtf\Util\Generate\GenerateResult::addResult('Test Case Tickets', $this->cnt);
 }
function displayBookings()
{
    $host;
    $user;
    $pswd;
    $dbnm;
    $connection = mysqli_connect($host, $user, $pswd, $dbnm) or die('Failed to connect.');
    $searchQuery = "SELECT * FROM bookings where status = 'unassigned'";
    $result = mysqli_query($connection, $searchQuery);
    $xml = new SimpleXMLElement('<xml/>');
    if (mysqli_num_rows($result) > 0) {
        while ($result_array = mysqli_fetch_array($result)) {
            $data = $xml->addChild('search');
            $data->addChild('bookingNumber', $result_array['bookingNumber']);
            $data->addChild('customerName', $result_array['customerName']);
            $data->addChild('pickupAddress', $result_array['pickupAddress']);
            $data->addChild('suburb', $result_array['suburb']);
            $data->addChild('destination', $result_array['destination']);
            $data->addChild('phoneNumber', $result_array['contactPhone']);
            $data->addChild('pickUpDate', $result_array['pickUpDate']);
            $data->addChild('pickUpTime', $result_array['pickUpTime']);
            $data->addChild('bookingDate', $result_array['bookingDate']);
            $data->addChild('bookingTime', $result_array['bookingTime']);
        }
    }
    echo $xml->asXML();
}
Example #27
0
 /**
 * Save the setup data
 * @param array $dbconfig
 * @param array $preferences
 * 
 * <?xml version="1.0" encoding="UTF-8"?>
 		<shineisp>
 			<config>
 				<database>
 					<hostname>localhost</hostname>
 					<db>shineisp</db>
 					<username>shineisp</username>
 					<password>shineisp2013</password>
 				</database>
 			</config>
 		</shineisp>
 */
 public static function saveConfig($dbconfig, $version = null)
 {
     try {
         $xml = new SimpleXMLElement('<shineisp></shineisp>');
         if (!empty($version)) {
             $xml->addAttribute('version', $version);
         }
         $xml->addAttribute('setupdate', date('Ymdhis'));
         $config = $xml->addChild('config');
         // Database Configuration
         $database = $config->addChild('database');
         $database->addChild('hostname', $dbconfig->hostname);
         $database->addChild('username', $dbconfig->username);
         $database->addChild('password', $dbconfig->password);
         $database->addChild('database', $dbconfig->database);
         // Get the xml string
         $xmlstring = $xml->asXML();
         // Prettify and save the xml configuration
         $dom = new DOMDocument();
         $dom->loadXML($xmlstring);
         $dom->formatOutput = true;
         $dom->saveXML();
         // Save the config xml file
         if (@$dom->save(APPLICATION_PATH . "/configs/config.xml")) {
             Shineisp_Commons_Utilities::log("Update ShineISP config xml file");
             return true;
         } else {
             throw new Exception("Error on saving the xml file in " . APPLICATION_PATH . "/configs/config.xml <br/>Please check the folder permissions");
         }
     } catch (Exception $e) {
         throw new Exception($e->getMessage());
     }
     return false;
 }
 public function __construct(\SimpleXMLElement $action_xml)
 {
     if ($action_xml == NULL) {
         throw new e\EmptyValueException("The xml cannot be empty.");
     }
     if (self::DEBUG && self::DUMP) {
         DebugUtility::dump(u\XMLUtility::replaceBrackets($action_xml->asXML()));
     }
     $this->action_xml = $action_xml;
     $action_attr = $action_xml->attributes();
     $this->identifier = $action_attr->identifier->__toString();
     if ($action_attr->label) {
         $this->label = $action_attr->label->__toString();
     }
     if ($action_attr->move) {
         $this->move = $action_attr->move->__toString();
     } else {
         $this->move = "";
     }
     if ($action_attr->{"next-id"}) {
         $this->next_id = $action_attr->{"next-id"}->__toString();
     } else {
         $this->next_id = "";
     }
     $this->triggers = array();
     if ($this->action_xml->trigger) {
         foreach ($this->action_xml->trigger as $trigger) {
             $this->triggers[] = new TriggerDefinition($trigger);
         }
     }
 }
Example #29
0
 /**
  * Litle Request
  */
 private static function litle_request($content)
 {
     $xml = new \SimpleXMLElement($content);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text/xml'));
     curl_setopt($ch, CURLOPT_URL, self::$url);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
     curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_SSLVERSION, 3);
     $output = curl_exec($ch);
     $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     if (!$output) {
         throw new \Exception(curl_error($ch));
     } else {
         $p = fopen('/data/litle/' . date('Y-m-d\\.H:i:s'), 'w+');
         fwrite($p, $output);
         fclose($p);
         curl_close($ch);
         return $output;
     }
 }
Example #30
0
 function save($file)
 {
     if (!file_exists($file) && !touch($file)) {
         throw new Exception(sprintf('File %s does NOT exist!', $file));
     } elseif (!is_writable($file)) {
         throw new Exception(sprintf('Cannot write to %s - CHMOD it 766!', $file));
     }
     $xml = new SimpleXMLElement('<rss version="2.0" xml:base="' . $this->base . '"></rss>');
     $rss = $xml->addChild('channel');
     $rss->title = $this->title;
     $rss->link = $this->link;
     $rss->description = $this->desc;
     foreach ($this->data as $x) {
         $item = $rss->addChild('item');
         $item->title = $x['title'];
         $item->description = $x['text'];
         $item->link = $x['url'];
         #Optional tags
         if (isset($x['author'])) {
             $item->author = $x['author'];
         }
         if (isset($x['category'])) {
             $item->category = $x['cat'];
         }
         if (isset($x['date'])) {
             $item->pubDate = $x['date'];
         }
         if (isset($x['id'])) {
             $item->id = $x['ID'];
             $item->id['isPermaLink'] = 'false';
         }
     }
     #Save file
     return $xml->asXML($file);
 }