/**
  * {@inheritDoc}
  */
 public function parseArtifact(Build $build, $artifact)
 {
     $this->build = $build;
     $this->artifact = $artifact ? new \SimpleXMLElement($artifact) : false;
     $this->details['totalMethods'] = 0;
     $this->details['totalStatements'] = 0;
     $this->details['totalConditionals'] = 0;
     $this->details['coveredMethods'] = 0;
     $this->details['coveredStatements'] = 0;
     $this->details['coveredConditionals'] = 0;
     $this->details['total'] = 0;
     $this->details['covered'] = 0;
     if ($this->artifact) {
         foreach ($this->artifact->xpath('//file/class/metrics') as $metric) {
             $this->details['totalMethods'] += (int) $metric['methods'];
             $this->details['totalStatements'] += (int) $metric['statements'];
             $this->details['totalConditionals'] += (int) $metric['conditionals'];
             $this->details['coveredMethods'] += (int) $metric['coveredmethods'];
             $this->details['coveredStatements'] += (int) $metric['coveredstatements'];
             $this->details['coveredConditionals'] += (int) $metric['coveredconditionals'];
             $this->details['total'] += (int) $metric['methods'] + (int) $metric['statements'] + (int) $metric['conditionals'];
             $this->details['covered'] += (int) $metric['coveredmethods'] + (int) $metric['coveredstatements'] + (int) $metric['coveredconditionals'];
         }
     }
     $this->calculateTotals();
     if ($build->getParent()) {
         $parent = $build->getParent();
         $statistics = $parent->getFlatStatistics();
         $this->generateCoverageComparisonStatistics($statistics);
     }
 }
 /**
  * {@inheritDoc}
  */
 public function getSimpleTextResult()
 {
     $violationCount = 0;
     if ($this->artifact) {
         foreach ($this->artifact->xpath('//file') as $file) {
             foreach ($file->xpath('//violation') as $violation) {
                 $violationCount++;
             }
         }
         $result = $violationCount . ' instance' . ($violationCount > 1 ? 's ' : ' ') . "of messy code found\n";
     } else {
         $result = "No Messy Code Detected\n";
     }
     return $result;
 }
예제 #3
0
function explodeXML($xml)
{
    $objXML = new SimpleXmlElement($xml);
    if (strpos($xml, 'soap:') !== false) {
        $objXML->registerXPathNamespace('soap', 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeConsulta2');
        $xml2 = (array) $objXML->xpath('//soap:Body');
    } else {
        $objXML->registerXPathNamespace('soapenv', 'http://www.w3.org/2003/05/soap-envelope');
        $xml2 = $objXML->xpath('//soapenv:Body');
    }
    $xml2[0]->children()->children()->children()->cStat;
    $xml2[0]->children()->children()->children()->xMotivo;
    $xml2[0]->children()->children()->children()->protNFe->infProt->dhRecbto;
    $xml2[0]->children()->children()->children()->protNFe->infProt->nProt;
}
 /**
  * Log any build exceptions from the CheckStyle report.
  */
 public function logBuildExceptions()
 {
     if ($this->artifact) {
         foreach ($this->artifact->xpath('//file') as $file) {
             foreach ($file->xpath('//error') as $error) {
                 $exception = new Build\BuildException();
                 $exception->setAsset(basename($file['name']));
                 $exception->setReference($error['line']);
                 $exception->setType('E');
                 $exception->setMessage($error['message']);
                 $this->build->addException($exception);
             }
         }
     }
 }
예제 #5
0
 /**
  * Parse Links
  *
  * Parses an XML file returned by a link resolver
  * and converts it to a standardised format for display
  *
  * @param string $xmlstr Raw XML returned by resolver
  *
  * @return array         Array of values
  */
 public function parseLinks($xmlstr)
 {
     $records = [];
     // array to return
     try {
         $xml = new \SimpleXmlElement($xmlstr);
     } catch (\Exception $e) {
         return $records;
     }
     $root = $xml->xpath("//ctx_obj_targets");
     $xml = $root[0];
     foreach ($xml->children() as $target) {
         $record = [];
         $record['title'] = (string) $target->target_public_name;
         $record['href'] = (string) $target->target_url;
         $record['service_type'] = (string) $target->service_type;
         if (isset($target->coverage->coverage_text)) {
             $coverageText =& $target->coverage->coverage_text;
             $record['coverage'] = (string) $coverageText->threshold_text->coverage_statement;
             if (isset($coverageText->embargo_text->embargo_statement)) {
                 $record['coverage'] .= ' ' . (string) $coverageText->embargo_text->embargo_statement;
                 $record['embargo'] = (string) $coverageText->embargo_text->embargo_statement;
             }
         }
         if (isset($target->coverage)) {
             $record['coverage_details'] = json_decode(json_encode($target->coverage), true);
         }
         array_push($records, $record);
     }
     return $records;
 }
 /**
  * {@inheritDoc}
  */
 public function getSimpleTextResult()
 {
     $totalTests = 0;
     $totalAssertions = 0;
     $totalFailures = 0;
     $totalErrors = 0;
     if ($this->artifact) {
         foreach ($this->artifact->xpath('//testsuite') as $suite) {
             $totalTests += (int) $suite['tests'];
             $totalAssertions += (int) $suite['assertions'];
             $totalFailures += (int) $suite['failures'];
             $totalErrors += (int) $suite['errors'];
         }
     }
     $result = 'PHPUnit tests ' . ($totalErrors + $totalFailures > 0 ? 'failed' : 'passed') . ".\n\n" . "Tests: " . $totalTests . "\n" . "Assertions: " . $totalAssertions . "\n" . "Failures: " . $totalFailures . "\n" . "Errors: " . $totalErrors . "\n";
     return $result;
 }
예제 #7
0
 public function getLayoutUpdates()
 {
     $updates = $this->xml->xpath('//layout/updates/*');
     $res = array();
     foreach ($updates as $update) {
         $res[$update->getName()] = array('file' => (string) $update->file, 'area' => (string) $update->xpath('../../..')[0]->getName());
     }
     return $res;
 }
 public function getBlogPosts(SimpleXmlElement $xml)
 {
     $blogs = array();
     $natureBlogs = $xml->xpath("//source[@source='Nature']/citations/citation");
     if ($natureBlogs) {
         foreach ($natureBlogs as $citation) {
             $blog = array();
             $blog['uri'] = (string) $citation->attributes()->uri;
             $blog['from'] = "Nature via Plos";
             $blog['pubDate'] = date('c', strtotime($citation->post[0]->attributes()->created_at));
             $blog['title'] = (string) $citation->post[0]->attributes()->title;
             $blog['natureBlogId'] = (string) $citation->post[0]->attributes()->blog_id;
             $blogs[] = $blog;
         }
     }
     $postGenomicBlogs = $xml->xpath("//source[@source='Postgenomic']/citations/citation");
     if ($postGenomicBlogs) {
         foreach ($postGenomicBlogs as $citation) {
             $blog = array();
             $blog['uri'] = (string) $citation->attributes()->uri;
             $blog['from'] = "Postgenomic via Plos";
             $blog['pubDate'] = date('c', strtotime($citation->pubdate[0]));
             $blog['title'] = (string) $citation->title[0];
             $blog['blogName'] = (string) $citation->blog_name[0];
             $blogs[] = $blog;
         }
     }
     $researchBlogsBlogs = $xml->xpath("//source[@source='Research Blogging']/citations/citation");
     if ($researchBlogsBlogs) {
         foreach ($researchBlogsBlogs as $citation) {
             $blog = array();
             $blog['uri'] = (string) $citation->attributes()->uri;
             $blog['from'] = "Research Blogging via Plos";
             $blog['pubDate'] = date('c', strtotime($citation->details[0]->attributes()->receiveddate));
             $blog['title'] = (string) $citation->details[0]->attributes()->title;
             $blog['blogName'] = (string) $citation->details[0]->attributes()->name;
             $blogs[] = $blog;
         }
     }
     return $blogs ? $this->escArray($blogs) : false;
 }
예제 #9
0
 /**
  * Retrieve the messages and set the cookies
  *
  * @return void
  */
 protected function set_messages()
 {
     if (!isset($_COOKIE['messages'][$this->language]) || $this->config['cookie'] == false) {
         $xml = file_get_contents("{$this->config['path']}{$this->language}.xml");
         if (!($xml = new SimpleXmlElement($xml))) {
             throw new Exception('Cannot recover language file');
         }
         foreach ($xml->xpath('//message') as $msg) {
             $this->messages[(string) $msg->attributes()->id[0]] = (string) $msg;
             if ($this->config['cookie'] == true) {
                 setcookie("messages[{$this->language}][{$msg->attributes()->id[0]}]", (string) $msg, time() + 60 * 60 * 24 * 30);
             }
         }
     } else {
         foreach ($_COOKIE['messages'][$this->language] as $k => $v) {
             $this->messages[$k] = $v;
         }
     }
 }
예제 #10
0
 /**
  * Gets all classes and interfaces from the file and puts them in an easy
  * to use array.
  *
  * @param SimpleXmlElement $xml
  * @return void
  */
 protected function getClassDefinitions(SimpleXmlElement $xml)
 {
     foreach ($xml->xpath('file/class|file/interface') as $class) {
         $className = (string) $class->full_name;
         $className = ltrim($className, '\\');
         $fileName = str_replace('\\', '-', $className) . '.md';
         $implements = array();
         if (isset($class->implements)) {
             foreach ($class->implements as $interface) {
                 $implements[] = ltrim((string) $interface, '\\');
             }
         }
         $extends = array();
         if (isset($class->extends)) {
             foreach ($class->extends as $parent) {
                 $extends[] = ltrim((string) $parent, '\\');
             }
         }
         $classNames[$className] = array('fileName' => $fileName, 'className' => $className, 'shortClass' => (string) $class->name, 'namespace' => (string) $class['namespace'], 'description' => (string) $class->docblock->description, 'longDescription' => (string) $class->docblock->{"long-description"}, 'implements' => $implements, 'extends' => $extends, 'isClass' => $class->getName() === 'class', 'isInterface' => $class->getName() === 'interface', 'abstract' => (string) $class['abstract'] == 'true', 'deprecated' => count($class->xpath('docblock/tag[@name="deprecated"]')) > 0, 'methods' => $this->parseMethods($class), 'properties' => $this->parseProperties($class), 'constants' => $this->parseConstants($class));
     }
     $this->classDefinitions = $classNames;
 }
예제 #11
0
파일: Fn.php 프로젝트: hopitio/framework
/**
 * 
 * @param SimpleXmlElement $dom
 * @param type $xpath
 * @param type $method
 * @return SimpleXmlElement
 */
function xpath($dom, $xpath, $method = 1)
{
    if ($dom instanceof SimpleXMLElement == false) {
        switch ($method) {
            case XPATH_STRING:
                return '';
            case XPATH_ARRAY:
                return array();
            case XPATH_DOM:
                return null;
        }
    }
    $r = $dom->xpath($xpath);
    switch ($method) {
        case XPATH_ARRAY:
            return $r;
        case XPATH_DOM:
            return $r[0];
        case XPATH_STRING:
        default:
            return count($r) ? (string) $r[0] : null;
    }
}
예제 #12
0
파일: Pecl.php 프로젝트: m6w6/pharext
 /**
  * Generate a list of files from the package.xml
  * @return Generator
  */
 private function generateFiles()
 {
     /* hook  */
     $temp = tmpfile();
     fprintf($temp, "<?php\nreturn new %s(__DIR__);\n", get_class($this));
     rewind($temp);
     (yield "pharext_package.php" => $temp);
     /* deps */
     $dependencies = $this->sxe->xpath("/pecl:package/pecl:dependencies/pecl:required/pecl:package");
     foreach ($dependencies as $key => $dep) {
         if ($glob = glob("{$this->path}/{$dep->name}-*.ext.phar*")) {
             usort($glob, function ($a, $b) {
                 return version_compare(substr($a, strpos(".ext.phar", $a)), substr($b, strpos(".ext.phar", $b)));
             });
             (yield end($glob));
         }
     }
     /* files */
     (yield realpath($this->file));
     foreach ($this->sxe->xpath("//pecl:file") as $file) {
         (yield realpath($this->path . "/" . $this->dirOf($file) . "/" . $file["name"]));
     }
 }
 public function testSelectsCorrectDate()
 {
     $this->dateTimeForm->setDateTime('2000-01-01 01:01:01');
     $xml = '<minacl>' . $this->dateTimeForm->__toString() . '</minacl>';
     /*
      * replace the &nbsp; with nothing otherwise it'll cause an error
      * (as we are not including the html entity definitions here)
      */
     $xml = str_replace('&nbsp;', '', $xml);
     $dom = new SimpleXmlElement($xml);
     $year = $dom->xpath("//select[@id='test_year']/option[@selected='selected']");
     $this->assertEquals('2000', (string) $year[0], 'Selected year is 2000');
     $month = $dom->xpath("//select[@id='test_month']/option[@selected='selected']");
     $this->assertEquals('January', (string) $month[0], 'Selected month is January');
     $day = $dom->xpath("//select[@id='test_day']/option[@selected='selected']");
     $this->assertEquals('01', (string) $day[0], 'Selected day is 01');
     $hour = $dom->xpath("//select[@id='test_hour']/option[@selected='selected']");
     $this->assertEquals('01', (string) $hour[0], 'Selected hour is 01');
     $minutes = $dom->xpath("//select[@id='test_minute']/option[@selected='selected']");
     $this->assertEquals('01', (string) $minutes[0], 'Selected minutes is 01');
     $seconds = $dom->xpath("//select[@id='test_second']/option[@selected='selected']");
     $this->assertEquals('01', (string) $seconds[0], 'Selected seconds is 01');
 }
예제 #14
0
 public static function getLanguage($xml, $langCode, $fallbackCode = 'en-gb', $opts = array())
 {
     if (!isset($xml)) {
         return '';
     }
     $retVal = $xml;
     if (strpos($xml, '<languages>') !== false) {
         if ($fallbackCode == null || !isset($fallbackCode)) {
             $fallbackCode = self::$defaultFallbackCode;
         }
         $langCode = strtolower($langCode);
         $fallbackCode = strtolower($fallbackCode);
         if (strlen($langCode) > 2) {
             $langCode = substr($langCode, 0, 2);
         }
         if (strlen($fallbackCode) > 2) {
             $fallbackCode = substr($fallbackCode, 0, 2);
         }
         $xml = self::stripInvalidXml($xml);
         $xdoc = new SimpleXmlElement($xml);
         $item = $xdoc->xpath("language [@code='" . $langCode . "']");
         $result = '';
         $retVal = '';
         if (!empty($item)) {
             $result = (string) $item[0];
         }
         if ($result == '' && $fallbackCode != '') {
             $item = $xdoc->xpath("language [@code='" . $fallbackCode . "']");
         }
         if (!empty($item)) {
             $retVal = (string) $item[0];
         }
         //$retVal = (string)$item[0];
     }
     if (isset($opts) && count($opts) > 0) {
         foreach ($opts as $key => $opt) {
             switch (strtolower($key)) {
                 case 'ln2br':
                     $retVal = nl2br($retVal, true);
                     break;
                 case 'htmlencode':
                     $retVal = htmlentities($retVal, ENT_COMPAT);
                     break;
                 case 'striptags':
                     $retVal = strip_tags($retVal, "<br><br/>");
                     break;
                 case 'nomore1br':
                     $retVal = preg_replace("/\n+/", "\n", $retVal);
                     break;
                 default:
                     break;
             }
         }
     }
     return $retVal;
 }
 /**
  * Handle form input related to backdropPost(). Ensure that the specified fields
  * exist and attempt to create POST data in the correct manner for the particular
  * field type.
  *
  * @param $post
  *   Reference to array of post values.
  * @param $edit
  *   Reference to array of edit values to be checked against the form.
  * @param $submit
  *   Form submit button value.
  * @param SimpleXmlElement $form
  *   A SimpleXmlElement containing the form.
  * @return
  *   Submit value matches a valid submit input in the form.
  */
 protected function handleForm(&$post, &$edit, &$upload, $submit, $form)
 {
     // Retrieve the form elements.
     $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
     $submit_matches = FALSE;
     foreach ($elements as $element) {
         // SimpleXML objects need string casting all the time.
         $name = (string) $element['name'];
         // This can either be the type of <input> or the name of the tag itself
         // for <select> or <textarea>.
         $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
         $value = isset($element['value']) ? (string) $element['value'] : '';
         $done = FALSE;
         if (isset($edit[$name])) {
             switch ($type) {
                 case 'color':
                 case 'email':
                 case 'hidden':
                 case 'number':
                 case 'range':
                 case 'text':
                 case 'tel':
                 case 'textarea':
                 case 'url':
                 case 'password':
                 case 'search':
                     $post[$name] = $edit[$name];
                     unset($edit[$name]);
                     break;
                 case 'radio':
                     if ($edit[$name] == $value) {
                         $post[$name] = $edit[$name];
                         unset($edit[$name]);
                     }
                     break;
                 case 'checkbox':
                     // To prevent checkbox from being checked.pass in a FALSE,
                     // otherwise the checkbox will be set to its value regardless
                     // of $edit.
                     if ($edit[$name] === FALSE) {
                         unset($edit[$name]);
                         continue 2;
                     } else {
                         unset($edit[$name]);
                         $post[$name] = $value;
                     }
                     break;
                 case 'select':
                     $new_value = $edit[$name];
                     $options = $this->getAllOptions($element);
                     if (is_array($new_value)) {
                         // Multiple select box.
                         if (!empty($new_value)) {
                             $index = 0;
                             $key = preg_replace('/\\[\\]$/', '', $name);
                             foreach ($options as $option) {
                                 $option_value = (string) $option['value'];
                                 if (in_array($option_value, $new_value)) {
                                     $post[$key . '[' . $index++ . ']'] = $option_value;
                                     $done = TRUE;
                                     unset($edit[$name]);
                                 }
                             }
                         } else {
                             // No options selected: do not include any POST data for the
                             // element.
                             $done = TRUE;
                             unset($edit[$name]);
                         }
                     } else {
                         // Single select box.
                         foreach ($options as $option) {
                             if ($new_value == $option['value']) {
                                 $post[$name] = $new_value;
                                 unset($edit[$name]);
                                 $done = TRUE;
                                 break;
                             }
                         }
                     }
                     break;
                 case 'file':
                     $upload[$name] = $edit[$name];
                     unset($edit[$name]);
                     break;
             }
         }
         if (!isset($post[$name]) && !$done) {
             switch ($type) {
                 case 'textarea':
                     $post[$name] = (string) $element;
                     break;
                 case 'select':
                     $single = empty($element['multiple']);
                     $first = TRUE;
                     $index = 0;
                     $key = preg_replace('/\\[\\]$/', '', $name);
                     $options = $this->getAllOptions($element);
                     foreach ($options as $option) {
                         // For single select, we load the first option, if there is a
                         // selected option that will overwrite it later.
                         if ($option['selected'] || $first && $single) {
                             $first = FALSE;
                             if ($single) {
                                 $post[$name] = (string) $option['value'];
                             } else {
                                 $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
                             }
                         }
                     }
                     break;
                 case 'file':
                     break;
                 case 'submit':
                 case 'image':
                     if (isset($submit) && $submit == $value) {
                         $post[$name] = $value;
                         $submit_matches = TRUE;
                     }
                     break;
                 case 'radio':
                 case 'checkbox':
                     if (!isset($element['checked'])) {
                         break;
                     }
                     $post[$name] = $value;
                     break;
                 default:
                     $post[$name] = $value;
             }
         }
     }
     return $submit_matches;
 }
예제 #16
0
 /**
  * Parse Links
  *
  * Parses an XML file returned by a link resolver
  * and converts it to a standardised format for display
  *
  * @param string $xmlstr Raw XML returned by resolver
  *
  * @return array         Array of values
  */
 public function parseLinks($xmlstr)
 {
     $records = array();
     // array to return
     try {
         $xml = new \SimpleXmlElement($xmlstr);
     } catch (\Exception $e) {
         return $records;
     }
     $root = $xml->xpath("//ctx_obj_targets");
     $xml = $root[0];
     foreach ($xml->children() as $target) {
         $record = array();
         $record['title'] = (string) $target->target_public_name;
         $record['href'] = (string) $target->target_url;
         $record['service_type'] = (string) $target->service_type;
         $record['coverage'] = (string) $target->coverage->coverage_text->threshold_text->coverage_statement;
         array_push($records, $record);
     }
     return $records;
 }
예제 #17
0
 /**
  * Get the last child object.
  *
  * @param SimpleXmlElement $ref Reference node, or null if current is to be used.
  * @return mixed SimpleXmlElement or false if no children.
  */
 public function lastChild($ref = null)
 {
     if ($ref === null) {
         return current($this->xpath('./*[last()]'));
     }
     return current($ref->xpath('./*[last()]'));
 }
예제 #18
0
 /**
  * @param SimpleXmlElement $xml_obj
  */
 private function _processXML($xml_obj)
 {
     $forms = $xml_obj->xpath('/forms');
     //process each layout
     foreach ($forms as $form) {
         $form = $form->form;
         /* Determin an action tag in all patent elements. Action can be insert, update and delete 
         		       Default action (if not provided) is update
         		       ->>> action = insert 
         					Before loading the layout, determin if same layout exists with same name, template and type comdination. 
         					If does exists, return and log error 
         		       ->>> action = update (default) 
         					Before loading the layout, determin if same layout exists with same name, template and type comdination. 
         					If does exists, write new settings over existing
         		       ->>> action = delete 
         					Delete the element provided from databse and delete relationships to other elements linked to currnet one
         					
         				NOTE: Parent level delete action is cascaded to all childer elements 
         				
         				TODO: Need to use transaction sql here to prevent partual load or partual delete in case of error
         			*/
         //check if form with same name exists
         $this->__construct($form->form_name);
         if (!$this->form_id && in_array($form->action, array("", null, "update"))) {
             $form->action = 'insert';
         }
         $form->status = strtolower($form->status) == 'active' ? 1 : 0;
         if ($form->action == "delete") {
             if ($this->form_id) {
                 $sql = array();
                 $sql[] = "DELETE FROM " . DB_PREFIX . "field_values WHERE field_id IN ( SELECT field_id FROM " . DB_PREFIX . "fields WHERE form_id = '" . $this->form_id . "')";
                 $sql[] = "DELETE FROM " . DB_PREFIX . "field_descriptions WHERE field_id IN ( SELECT field_id FROM " . DB_PREFIX . "fields WHERE form_id = '" . $this->form_id . "')";
                 $sql[] = "DELETE FROM " . DB_PREFIX . "fields_group_descriptions WHERE group_id IN ( SELECT group_id FROM " . DB_PREFIX . "form_groups WHERE form_id = '" . $this->form_id . "')";
                 $sql[] = "DELETE FROM " . DB_PREFIX . "fields_groups WHERE group_id IN ( SELECT group_id FROM " . DB_PREFIX . "form_groups WHERE form_id = '" . $this->form_id . "')";
                 $sql[] = "DELETE FROM " . DB_PREFIX . "form_groups WHERE form_id  = '" . $this->form_id . "'";
                 $sql[] = "DELETE FROM " . DB_PREFIX . "fields WHERE form_id = '" . $this->form_id . "'";
                 $sql[] = "DELETE FROM " . DB_PREFIX . "pages_forms WHERE form_id = '" . $this->form_id . "'";
                 $sql[] = "DELETE FROM " . DB_PREFIX . "form_descriptions WHERE form_id = '" . $this->form_id . "'";
                 $sql[] = "DELETE FROM " . DB_PREFIX . "forms WHERE form_id = '" . $this->form_id . "'";
                 foreach ($sql as $query) {
                     $this->db->query($query);
                 }
             }
             continue;
             // well done
         } elseif ($form->action == 'insert') {
             // if form exists
             if ($this->form_id) {
                 $errmessage = 'Error: cannot insert form (name: "' . $form->form_name . '") because it already exists in database.';
                 $error = new AError($errmessage);
                 $error->toLog()->toDebug();
                 $this->errors = 1;
                 continue;
             }
             $query = "INSERT INTO " . DB_PREFIX . "forms (`form_name`, `controller`, `success_page`, `status`) \n\t\t\t\t\t\t\tVALUES ('" . $this->db->escape($form->form_name) . "','" . $this->db->escape($form->controller) . "','" . $this->db->escape($form->success_page) . "','" . $this->db->escape($form->status) . "')";
             $this->db->query($query);
             $this->form_id = $this->db->getLastId();
             if ($form->form_descriptions->form_description) {
                 foreach ($form->form_descriptions->form_description as $form_description) {
                     $language_id = $this->_getLanguageIdByName($form_description->language);
                     if (!$language_id) {
                         $errmessage = 'Error: cannot insert form description because it language: "' . $form_description->language . '" is not exists in database.';
                         $error = new AError($errmessage);
                         $error->toLog()->toDebug();
                         $this->errors = 1;
                         continue 2;
                     }
                     $this->language->replaceDescriptions('form_descriptions', array('form_id' => (int) $this->form_id), array($language_id => array('description' => (string) $form_description->description)));
                     /*
                     						$query = "INSERT INTO " . DB_PREFIX . "form_descriptions(form_id, language_id,description) 
                     									VALUES ('" . $this->form_id . "','" . $language_id . "','" . $this->db->escape ( $form_description->description ) . "')";
                     						$this->db->query ( $query );*/
                 }
             }
             if ($form->fields->field) {
                 foreach ($form->fields->field as $field) {
                     $this->_processFieldXML($field);
                 }
             }
             if ($form->fields->field_groups->field_group) {
                 foreach ($form->fields->field_groups->field_group as $field_group) {
                     $this->_processFieldGroupXML($field_group);
                 }
             }
         } else {
             // update form info
             $query = "UPDATE " . DB_PREFIX . "forms \n\t\t\t\t\t\t\tSET `form_name` = '" . $this->db->escape($form->form_name) . "',\n\t\t\t\t\t\t\t\t `controller`='" . $this->db->escape($form->controller) . "',\n\t\t\t\t\t\t\t\t `success_page` = '" . $this->db->escape($form->success_page) . "',\n\t\t\t\t\t\t\t\t `status` = '" . $this->db->escape($form->status) . "'\n\t\t\t\t\t\tWHERE form_id = '" . $this->form_id . "'";
             $this->db->query($query);
             if ($form->form_descriptions->form_description) {
                 foreach ($form->form_descriptions->form_description as $form_description) {
                     $language_id = $this->_getLanguageIdByName($form_description->language);
                     if (!$language_id) {
                         $errmessage = 'Error: cannot update form description because it language: "' . $form_description->language . '" is not exists in database.';
                         $error = new AError($errmessage);
                         $error->toLog()->toDebug();
                         $this->errors = 1;
                         continue 2;
                     }
                     $this->language->replaceDescriptions('form_descriptions', array('form_id' => (int) $this->form_id), array($language_id => array('description' => (string) $form_description->description)));
                 }
             }
             if ($form->fields->field) {
                 foreach ($form->fields->field as $field) {
                     $this->_processFieldXML($field);
                 }
             }
             if ($form->fields->field_groups->field_group) {
                 foreach ($form->fields->field_groups->field_group as $field_group) {
                     $this->_processFieldGroupXML($field_group);
                 }
             }
         }
     }
     //end of form manipulation
     return;
 }
예제 #19
0
 /**
  * Translate Primo's XML into array of arrays.
  *
  * @param array $data The raw xml from Primo
  *
  * @return array      The processed response from Primo
  */
 protected function process($data)
 {
     $res = parent::process($data);
     // Load API content as XML objects
     $sxe = new \SimpleXmlElement($data);
     if ($sxe === false) {
         throw new \Exception('Error while parsing the document');
     }
     // Register the 'sear' namespace at the top level to avoid problems:
     $sxe->registerXPathNamespace('sear', 'http://www.exlibrisgroup.com/xsd/jaguar/search');
     // Get the available namespaces. The Primo API uses multiple namespaces.
     // Will be used to navigate the DOM for elements that have namespaces
     $namespaces = $sxe->getNameSpaces(true);
     $docset = $sxe->xpath('//sear:DOC');
     if (empty($docset) && isset($sxe->JAGROOT->RESULT->DOCSET->DOC)) {
         $docset = $sxe->JAGROOT->RESULT->DOCSET->DOC;
     }
     for ($i = 0; $i < count($docset); $i++) {
         $doc = $docset[$i];
         // Set OpenURL
         $sear = $doc->children($namespaces['sear']);
         if ($openUrl = $this->getOpenUrl($sear)) {
             $res['documents'][$i]['url'] = $openUrl;
         } else {
             unset($res['documents'][$i]['url']);
         }
         // Prefix records id's
         $res['documents'][$i]['recordid'] = 'pci.' . $res['documents'][$i]['recordid'];
         // Process highlighting
         if ($this->highlighting) {
             // VuFind strips Primo highlighting tags from the description,
             // so we need to re-read the field (preserving highlighting tags).
             $description = isset($doc->PrimoNMBib->record->display->description) ? (string) $doc->PrimoNMBib->record->display->description : (string) $doc->PrimoNMBib->record->search->description;
             $description = trim(mb_substr($description, 0, 2500, 'UTF-8'));
             // these may contain all kinds of metadata, and just stripping
             //   tags mushes it all together confusingly.
             $description = str_replace("P>", "p>", $description);
             $d_arr = explode("<p>", $description);
             foreach ($d_arr as &$value) {
                 $value = trim($value);
                 if (trim(strip_tags($value)) === '') {
                     // get rid of entries that would just have spaces
                     unset($d_arr[$value]);
                 }
             }
             // now all paragraphs are converted to linebreaks
             $description = implode("<br>", $d_arr);
             $res['documents'][$i]['description'] = $description;
             $fieldList = ['title' => 'title', 'creator' => 'author', 'description' => 'description'];
             $start = '<span class="searchword">';
             $end = '</span>';
             $hilited = [];
             foreach ($fieldList as $field => $hiliteField) {
                 if (!isset($res['documents'][$i][$field])) {
                     continue;
                 }
                 $val = $res['documents'][$i][$field];
                 $values = is_array($val) ? $val : [$val];
                 $valuesHilited = [];
                 foreach ($values as $val) {
                     if (stripos($val, $start) !== false && stripos($val, $end) !== false) {
                         // Replace Primo hilite-tags
                         $hilitedVal = $val;
                         $hilitedVal = str_replace($start, '{{{{START_HILITE}}}}', $hilitedVal);
                         $hilitedVal = str_replace($end, '{{{{END_HILITE}}}}', $hilitedVal);
                         $valuesHilited[] = $hilitedVal;
                         // Strip Primo hilite-tags from record fields
                         $val = str_replace($start, '', $val);
                         $val = str_replace($end, '', $val);
                         $res['documents'][$i][$field] = is_array($res['documents'][$i][$field]) ? [$val] : $val;
                     }
                 }
                 if (!empty($valuesHilited)) {
                     $hilited[$hiliteField] = $valuesHilited;
                 }
             }
             $res['documents'][$i]['highlightDetails'] = $hilited;
         }
     }
     return $res;
 }
 public function loadCommittees(SimpleXmlElement $person, GovtrackPerson $p)
 {
     $committees = $person->xpath('current-committee-assignment');
     while ($committee = current($committees)) {
         $committeeAry = current($committee);
         $pc = new GovtrackPersonCommittee();
         $pc->Person = $p;
         if (!($c = Doctrine::getTable('GovtrackCommittee')->findOneByName($committeeAry['committee']))) {
             $c = new GovtrackCommittee();
             $c->name = $committeeAry['committee'];
             $c->save();
         }
         $pc->Committee = $c;
         if (isset($committeeAry['role'])) {
             $pc->role = $committeeAry['role'];
         }
         if (isset($committeeAry['subcommittee'])) {
             if (!($s = Doctrine::getTable('GovtrackSubcommittee')->findOneByName($committeeAry['subcommittee']))) {
                 $s = new GovtrackSubcommittee();
                 $s->name = $committeeAry['subcommittee'];
                 $s->Committee = $c;
                 $s->save();
             }
             $pc->Subcommittee = $s;
             $s->free(true);
         }
         $c->free(true);
         unset($c);
         $pc->save();
         $pc->free();
         next($committees);
     }
 }
예제 #21
0
 /**
  * Special case: collect declaration of helpers and modules in layout files and figure out helper class names
  *
  * @param SimpleXmlElement $xml
  * @param array &$classes
  */
 protected function _collectLayoutHelpersAndModules($xml, &$classes)
 {
     $nodes = $xml->xpath('/layout//@helper | /layout//@module') ?: array();
     foreach ($nodes as $node) {
         $node = (array) $node;
         if (isset($node['@attributes']['helper'])) {
             $class = explode('::', $node['@attributes']['helper']);
             $classes[array_shift($class)] = 1;
         }
         if (isset($node['@attributes']['module'])) {
             $class = $node['@attributes']['module'] . '_Helper_Data';
             $classes[$class] = 1;
         }
     }
 }
예제 #22
0
 /**
  * Translate Primo's XML into array of arrays.
  *
  * @param array $data The raw xml from Primo
  *
  * @return array      The processed response from Primo
  */
 protected function process($data)
 {
     // make sure data exists
     if (strlen($data) == 0) {
         throw new \Exception('Primo did not return any data');
     }
     // Load API content as XML objects
     $sxe = new \SimpleXmlElement($data);
     if ($sxe === false) {
         throw new \Exception('Error while parsing the document');
     }
     // some useful data about these results
     $totalhitsarray = $sxe->xpath("//@TOTALHITS");
     // if totalhits is missing but we have a message, this is an error
     // situation.
     if (!isset($totalhitsarray[0])) {
         $messages = $sxe->xpath("//@MESSAGE");
         $message = isset($messages[0]) ? (string) $messages[0] : "TOTALHITS attribute missing.";
         throw new \Exception($message);
     } else {
         $totalhits = (int) $totalhitsarray[0];
     }
     // TODO: would these be useful?
     //$firsthit = $sxe->xpath('//@FIRSTHIT');
     //$lasthit = $sxe->xpath('//@LASTHIT');
     // Register the 'sear' namespace at the top level to avoid problems:
     $sxe->registerXPathNamespace('sear', 'http://www.exlibrisgroup.com/xsd/jaguar/search');
     // Get the available namespaces. The Primo API uses multiple namespaces.
     // Will be used to navigate the DOM for elements that have namespaces
     $namespaces = $sxe->getNameSpaces(true);
     // Get results set data and add to $items array
     // This foreach grabs all the child elements of sear:DOC,
     //   except those with namespaces
     $items = [];
     $docset = $sxe->xpath('//sear:DOC');
     if (empty($docset) && isset($sxe->JAGROOT->RESULT->DOCSET->DOC)) {
         $docset = $sxe->JAGROOT->RESULT->DOCSET->DOC;
     }
     foreach ($docset as $doc) {
         $item = [];
         // Due to a bug in the primo API, the first result has
         //   a namespace (prim:) while the rest of the results do not.
         //   Those child elements do not get added to $doc.
         //   If the bib parent element (PrimoNMBib) is missing for a $doc,
         //   that means it has the prim namespace prefix.
         // So first set the right prefix
         $prefix = $doc;
         if ($doc->PrimoNMBib != 'true' && isset($namespaces['prim'])) {
             // Use the namespace prefix to get those missing child
             //   elements out of $doc.
             $prefix = $doc->children($namespaces['prim']);
         }
         // Now, navigate the DOM and set values to the array
         // cast to (string) to get the element's value not an XML object
         $item['recordid'] = substr((string) $prefix->PrimoNMBib->record->control->recordid, 3);
         $item['title'] = (string) $prefix->PrimoNMBib->record->display->title;
         // format
         $item['format'] = ucwords(str_replace('_', ' ', (string) $prefix->PrimoNMBib->record->display->type));
         // creators
         $creator = trim((string) $prefix->PrimoNMBib->record->display->creator);
         if (strlen($creator) > 0) {
             $item['creator'] = array_map('trim', explode(';', $creator));
         }
         // subjects
         $subject = trim((string) $prefix->PrimoNMBib->record->display->subject);
         if (strlen($subject) > 0) {
             $item['subjects'] = explode(';', $subject);
         }
         $item['ispartof'] = (string) $prefix->PrimoNMBib->record->display->ispartof;
         // description is sort of complicated
         // TODO: sometimes the entire article is in the description.
         $description = isset($prefix->PrimoNMBib->record->display->description) ? (string) $prefix->PrimoNMBib->record->display->description : (string) $prefix->PrimoNMBib->record->search->description;
         $description = trim(mb_substr($description, 0, 2500, 'UTF-8'));
         // these may contain all kinds of metadata, and just stripping
         //   tags mushes it all together confusingly.
         $description = str_replace("P>", "p>", $description);
         $d_arr = explode("<p>", $description);
         foreach ($d_arr as &$value) {
             // strip tags, trim so array_filter can get rid of
             // entries that would just have spaces
             $value = trim(strip_tags($value));
         }
         $d_arr = array_filter($d_arr);
         // now all paragraphs are converted to linebreaks
         $description = implode("<br>", $d_arr);
         $item['description'] = $description;
         // and the rest!
         $item['language'] = (string) $prefix->PrimoNMBib->record->display->language;
         $item['source'] = implode('; ', (array) $prefix->PrimoNMBib->record->display->source);
         $item['identifier'] = (string) $prefix->PrimoNMBib->record->display->identifier;
         $item['fulltext'] = (string) $prefix->PrimoNMBib->record->delivery->fulltext;
         $item['issn'] = [];
         foreach ($prefix->PrimoNMBib->record->search->issn as $issn) {
             $item['issn'][] = (string) $issn;
         }
         //Are these two needed?
         //$item['publisher'] =
         //    (string)$prefix->PrimoNMBib->record->display->publisher;
         //$item['peerreviewed'] =
         //    (string)$prefix->PrimoNMBib->record->display->lds50;
         // Get the URL, which has a separate namespace
         $sear = $doc->children($namespaces['sear']);
         $item['url'] = !empty($sear->LINKS->openurl) ? (string) $sear->LINKS->openurl : (string) $sear->GETIT->attributes()->GetIt2;
         // Container data
         $addata = $prefix->PrimoNMBib->record->addata;
         $item['container_title'] = (string) $addata->jtitle;
         $item['container_volume'] = (string) $addata->volume;
         $item['container_issue'] = (string) $addata->issue;
         $item['container_start_page'] = (string) $addata->spage;
         $item['container_end_page'] = (string) $addata->epage;
         foreach ($addata->eissn as $eissn) {
             if (!in_array((string) $eissn, $item['issn'])) {
                 $item['issn'][] = (string) $eissn;
             }
         }
         foreach ($addata->issn as $issn) {
             if (!in_array((string) $issn, $item['issn'])) {
                 $item['issn'][] = (string) $issn;
             }
         }
         // Remove dash-less ISSNs if there are corresponding dashed ones
         // (We could convert dash-less ISSNs to dashed ones, but try to stay
         // true to the metadata)
         $callback = function ($issn) use($item) {
             return strlen($issn) != 8 || !in_array(substr($issn, 0, 4) . '-' . substr($issn, 4), $item['issn']);
         };
         $item['issn'] = array_values(array_filter($item['issn'], $callback));
         $item['fullrecord'] = $prefix->PrimoNMBib->record->asXml();
         $items[] = $item;
     }
     // Set up variables with needed attribute names
     // Makes matching attributes and getting their values easier
     $att = 'NAME';
     $key = 'KEY';
     $value = 'VALUE';
     // Get facet data and add to multidimensional $facets array
     // Start by getting XML for each FACET element,
     //  which has the name of the facet as an attribute.
     // We only get the first level of elements
     //   because child elements have a namespace prefix
     $facets = [];
     $facetSet = $sxe->xpath('//sear:FACET');
     if (empty($facetSet)) {
         if (!empty($sxe->JAGROOT->RESULT->FACETLIST)) {
             $facetSet = $sxe->JAGROOT->RESULT->FACETLIST->children($namespaces['sear']);
         }
     }
     foreach ($facetSet as $facetlist) {
         // Set first level of array with the facet name
         $facet_name = (string) $facetlist->attributes()->{$att};
         // Use the namespace prefix to get second level child elements
         //   (the facet values) out of $facetlist.
         $sear_facets = $facetlist->children($namespaces['sear']);
         foreach ($sear_facets as $facetvalues) {
             // Second level of the array is facet values and their counts
             $facet_key = (string) $facetvalues->attributes()->{$key};
             $facets[$facet_name][$facet_key] = (string) $facetvalues->attributes()->{$value};
         }
     }
     $didYouMean = [];
     $suggestions = $sxe->xpath('//sear:QUERYTRANSFORMS');
     foreach ($suggestions as $suggestion) {
         $didYouMean[] = (string) $suggestion->attributes()->QUERY;
     }
     return ['recordCount' => $totalhits, 'documents' => $items, 'facets' => $facets, 'didYouMean' => $didYouMean];
 }
예제 #23
0
 /**
  * getArguments
  *
  * @param \SimpleXmlElement $element
  * @param mixed             $data
  *
  * @return  array
  */
 protected static function getArguments($element, $data, $argumrntTag = 'argument')
 {
     $args = $element->xpath($argumrntTag);
     $return = array();
     foreach ($args as $arg) {
         if (isset($arg['data'])) {
             $return[] = ArrayHelper::getByPath($data, (string) $arg['data']);
         } else {
             if (strtolower($arg) == 'null') {
                 $arg = null;
             }
             if (strtolower($arg) == 'false') {
                 $arg = false;
             }
             $return[] = String::parseVariable((string) $arg, $data);
         }
     }
     return $return;
 }
예제 #24
0
 /**
  * Count Simple Xml Element children
  *
  * @param SimpleXmlElement $parent
  *
  * @return int
  */
 private function countChildren($parent)
 {
     $elementsCount = 0;
     foreach ($parent->xpath('*') as $sub) {
         $elementsCount++;
     }
     return $elementsCount;
 }
예제 #25
0
 /**
  * renderChildren
  *
  * @param XulEngine         $engine
  * @param \SimpleXmlElement $element
  * @param mixed             $data
  *
  * @return  string
  */
 public static function renderChildren(XulEngine $engine, $element, $data)
 {
     $html = new HtmlElements();
     if (!$data instanceof Data) {
         $data = new Data($data);
     }
     $data = clone $data;
     $children = $element->xpath('*');
     if (count($children)) {
         foreach ($children as $child) {
             // Replace all attributes with variable.
             foreach ($child->attributes() as $key => $attr) {
                 $child[$key] = String::parseVariable((string) $attr, $data);
             }
             $namespaces = $child->getNamespaces();
             $name = $class = $child->getName();
             $ns = 'Control';
             if (array_key_exists('html', $namespaces)) {
                 $ns = 'Html';
                 $class = 'Html';
             }
             $renderer = XmlHelper::get($child, 'renderer');
             if (!$renderer || !is_subclass_of($renderer, __CLASS__)) {
                 $prefix = $data->xulControl->classPrefix;
                 $renderer = $engine->findRenderer($class, $ns, $prefix);
             }
             $html[] = call_user_func_array(array($renderer, 'render'), array($name, $engine, $child, $data));
         }
     } else {
         $html = String::parseVariable((string) $element, $data);
     }
     return $html;
 }
예제 #26
0
파일: Config.php 프로젝트: vectrex/vxphp
 /**
  * parse settings for binaries
  *
  * @param SimpleXmlElement $binaries
  * @throws ConfigException
  */
 private function parseBinariesSettings(\SimpleXmlElement $binaries)
 {
     $context = $this->isLocalhost ? 'local' : 'remote';
     $e = $binaries->xpath("executables[@context='{$context}']");
     if (empty($e)) {
         $e = $binaries->xpath('executables');
     }
     if (!empty($e)) {
         $p = $e[0]->path;
         if (empty($p)) {
             throw new ConfigException('Malformed "site.ini.xml"! Missing path for binaries.');
         }
         $this->binaries = new \stdClass();
         $this->binaries->path = rtrim((string) $p[0], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
         foreach ($e[0]->executable as $v) {
             $id = (string) $v->attributes()->id;
             foreach ($v->attributes() as $k => $v) {
                 $this->binaries->executables[$id][$k] = (string) $v;
             }
         }
     }
 }
예제 #27
0
    //Esegue la sessione cURL
    $retValue = curl_exec($curl);
    //Chiudo la sessione cURL
    curl_close($curl);
    return $retValue;
}
//Converto l'URL in stringa
$sXML = download_page($url);
//Converto l'URL da stringa a oggetto, per interagirci con xpath
$oXML = new SimpleXmlElement($sXML);
//Creo un nuovo documento DOM
$doc = new DOMDocument("1.0", "UTF-8");
//Inizializzo la radice Aggregatori
$root = $doc->appendChild($doc->createElement("Aggregatori"));
//Eseguo ciclo sull'URL oggetto
foreach ($oXML->xpath("//catalogo/@url") as $valore) {
    //Se riesce a caricare la porzione di URL interessata
    if ($xml2 = simplexml_load_file($valore)) {
        //Per tutti gli aggregatori prelevo id e url
        $id = $xml2->xpath("//aggregatore/@id");
        $url = $xml2->xpath("//aggregatore/@url");
        //Popolo il documento XML appendendo ogni aggregatore trovato
        //e settando per ciascuno gli attributi id e url
        for ($in = 0; $in < count($url); $in++) {
            $x = $root->appendChild($doc->createElement("aggregatore"));
            $x->setAttribute("id", $id[$in]);
            $x->setAttribute("url", $url[$in]);
        }
    }
}
//Creo il documento XML dalla sua rappresentazione DOM
예제 #28
0
 /**
  * @return string
  */
 public function getClassName()
 {
     $res = $this->xml->xpath('//node:Stmt_Class/subNode:name/scalar:string');
     return $res ? (string) $res[0] : '';
 }