public function updateLocales($args)
 {
     $fileSearch = I2CE::getFileSearch();
     if ($fileSearch instanceof I2CE_FileSearch_Caching) {
         $fileSearch->clearCache();
     }
 }
 /**
  * Loads in the file containing mime types and extensions
  */
 protected static function loadMimeTypes()
 {
     self::$extToMimeTypes = array();
     $mime_file = null;
     if (I2CE::getConfig()->setIfIsSet($mime_file, "/modules/MimeTypes/mime_types")) {
         $mime_file = I2CE::getFileSearch()->search('MIME', $mime_file);
     }
     if (empty($mime_file)) {
         I2CE::raiseError('Unable to find mime.types file.', E_USER_WARNING);
         return;
     }
     $a = file($mime_file);
     if (empty($a)) {
         I2CE::raiseError('mime.types file is empty.', E_USER_WARNING);
         return;
     }
     foreach ($a as $l) {
         $l = trim($l);
         if (strlen($l) < 1 || $l[0] == '#') {
             //skip comments
             continue;
         }
         $pieces = preg_split("/\\s+/", $l, -1, PREG_SPLIT_NO_EMPTY);
         if (empty($pieces)) {
             //a blank line
             continue;
         }
         $mime = strtolower(array_shift($pieces));
         foreach ($pieces as $ext) {
             self::$extToMimeTypes[strtolower($ext)] = $mime;
         }
     }
 }
Exemple #3
0
function getAvailableModules()
{
    global $configurator;
    global $modules;
    global $search_dirs;
    global $found_modules;
    global $booleans;
    if (is_array($found_modules)) {
        return $found_modules;
    }
    $found_modules = array();
    $bad_modules = array();
    foreach ($search_dirs as $dir) {
        foreach (glob($dir) as $d) {
            $d = realpath($d);
            I2CE::raiseError("Searching {$d}");
            I2CE::setupFileSearch(array('MODULES' => $d));
            $fileSearch = I2CE::getFileSearch();
            $top_module = $configurator->findAvailableConfigs($fileSearch, false);
            if (!is_array($top_module) || count($top_module) != 1) {
                I2CE::raiseError("WARNING:  no top-level module found for {$dir} -- Skipping.");
                continue;
            }
            $top_module = $top_module[0];
            I2CE::raiseError("Found {$top_module} as top-level module for {$d}");
            $searchPath = $fileSearch->getSearchPath('MODULES', true);
            if ($booleans['limit_search']) {
                I2CE::raiseError("Limiting search to {$d}");
                $avail_modules = $configurator->findAvailableConfigs($fileSearch, true, $d);
            } else {
                $avail_modules = $configurator->findAvailableConfigs($fileSearch, true);
            }
            if (is_array($modules)) {
                $avail_modules = array_intersect($modules, $avail_modules);
            }
            foreach ($avail_modules as $m) {
                if (array_key_exists($m, $found_modules)) {
                    I2CE::raiseError("WARNING: conflict with module {$m}.  Found more than once -- Skipping");
                    $found_modules[$m] = false;
                    $bad_modules[] = $m;
                } else {
                    $found_modules[$m] = $top_module;
                }
            }
        }
    }
    foreach ($bad_modules as $m) {
        unset($found_modules[$m]);
    }
    if (count($found_modules) == 0) {
        usage("No modules files found in this directory:\n\t" . implode("\n\t", $search_dirs) . "\n");
    }
    return $found_modules;
}
 /**
  * Return the HTML file name for the view template for this form.
  * @return string
  */
 public function getViewTemplate($type = 'default')
 {
     if (!$type || $type == 'default') {
         if ($template_file = I2CE::getFileSearch()->search('TEMPLATES', "view_list_" . $this->getName() . ".html")) {
             return $template_file;
         } else {
             return "view_list_simple_coded.html";
         }
     } else {
         if ($template_file = I2CE::getFileSearch()->search('TEMPLATES', "view_list_" . $this->getName() . "_alternate_{$type}.html")) {
             return $template_file;
         } else {
             return "view_list_simple_coded_alternate_{$type}.html";
         }
     }
 }
 protected function getXSLTS()
 {
     $file_search = I2CE::getFileSearch();
     $file_search->loadPaths('XSLTS');
     $files = $file_search->findByGlob('XSLTS', array('*XSL', '*xsl'), true);
     $pathset = $file_search->getSearchPath('XSLTS');
     $options = array();
     foreach ($files as $file) {
         foreach ($pathset as $paths) {
             foreach ($paths as $path) {
                 if (strpos($file, $path) === 0) {
                     $options[] = substr($file, strlen($path) + 1);
                     continue 3;
                 }
             }
         }
     }
     return $options;
 }
 /**
  * Set the data for the chart.
  * @return boolean
  */
 protected function setData()
 {
     if (count($this->request_remainder) > 0) {
         $csv = array_shift($this->request_remainder);
     } else {
         I2CE::raiseError("No CSV file given for pChart File.");
         return false;
     }
     $csv_file = I2CE::getFileSearch()->search("PCHART_DATA", $csv);
     if ($csv_file === null) {
         I2CE::raiseError("Unable to find CSV file ({$csv}) for pChart File.");
         return false;
     }
     $options = array();
     if ($this->get_exists('header')) {
         $options['GotHeader'] = true;
     }
     $this->chartData->importFromCSV($csv_file, $options);
     return true;
 }
 /**
  * Abstract business method to render a text element from the elements tree
  * @param int $left_x
  * @param int $top_y
  * @param array $formData of I2CE_Form
  * @param array $textProps
  * @param I2CE_MagicDataNode $elementConfig The node defining the element
  * @returns boolean. True on success
  */
 protected function processElement_image($left_x, $top_y, $formData, $textProps, $elementConfig)
 {
     $image = '';
     if (!$elementConfig->setIfIsSet($image, "image") || !$image) {
         I2CE::raiseError("No image set");
         return true;
         //error silently
     }
     $image_file = false;
     if (substr($image, 0, 7) == 'form://') {
         $image = substr($image, 7);
         if (strlen($image) == 0) {
             I2CE::raiseError("No image from form set");
             return true;
         }
         list($namedform, $field) = array_pad(explode('+', $image, 2), 2, '');
         if (!$namedform || !$field) {
             I2CE::raiseError("Image form {$image} is not in relationship");
             return true;
         }
         if (!array_key_exists($namedform, $formData)) {
             I2CE::raiseError("Form {$namedform} is not in relationship");
             return true;
         }
         if (!($fieldObj = $formData[$namedform]->getField($field)) instanceof I2CE_FormField_IMAGE) {
             I2CE::raiseError("Field {$field} of form {$namedform} is not an image");
             return true;
         }
         if (!$fieldObj->isValid()) {
             return true;
         }
         $image_content = $fieldObj->getBinaryData();
         if (strlen($image_content) == 0) {
             //no data
             return true;
         }
         $image_file = $image . '@' . $this->getCurrentId() . '.' . $fieldObj->getExtension();
         $this->pdf->addImageContent($image_content, $image_file);
     } else {
         $image_file = I2CE::getFileSearch()->search('PDF_IMAGES', $image);
         if (!$image_file) {
             $msg = "Header image ({$image}) not found" . "\nSearch Path is:\n" . print_r(I2CE::getFileSearch()->getSearchPath('PDF_IMAGES'), true);
             I2CE::raiseError($msg);
             return true;
             //error silently'
         }
     }
     $horiz_min = false;
     if (!$elementConfig->setIfIsSet($horiz_min, "horiz_min")) {
         I2CE::raiseError("horiz_min not set");
         return true;
         //error silently
     }
     $horiz_min = (int) $horiz_min;
     $horiz_min = max(0, $horiz_min);
     if ($horiz_min >= $this->layoutOptions['form_width']) {
         I2CE::raiseError("Element does not fit in form");
     }
     $vert_min = false;
     if (!$elementConfig->setIfIsSet($vert_min, "vert_min")) {
         I2CE::raiseError("vert_min not set");
         return true;
         //error silently
     }
     $horiz_max = false;
     $vert_min = max(0, $vert_min);
     if ($vert_min >= $this->layoutOptions['form_height']) {
         I2CE::raiseError("Element does not fit in form");
         return true;
         //error silently
     }
     $elementConfig->setIfIsSet($horiz_max, "horiz_max");
     $vert_max = false;
     $elementConfig->setIfIsSet($vert_max, "vert_max");
     if ($horiz_max == false) {
         $w = 0;
     } else {
         $w = min($horiz_max, $this->layoutOptions['form_width']) - $horiz_min;
     }
     if ($vert_max == false) {
         $h = 0;
     } else {
         $h = min($vert_max, $this->layoutOptions['form_height']) - $vert_min;
     }
     $k = $this->pdf->getScaleFactor();
     $this->pdf->SetXY($left_x + $horiz_min, $top_y + $vert_min);
     $this->pdf->Image($image_file, $left_x + $horiz_min, $top_y + $vert_min, $w, $h);
     return true;
 }
 /**
  * Adds any report display controls that can be added for this view.
  * @param DOMNode $conentNode
  * @param mixed $controls  If null (default), we display all the report controls.  If string or an
  *                         array of string, we only display the indicated controls
  * @returns boolean 
  */
 protected function displayReportControls($contentNode, $controls = null)
 {
     $this->template->addHeaderLink('mootools-core.js');
     $this->template->addHeaderLink('I2CE_ClassValues.js');
     $this->template->addHeaderLink('I2CE_SubmitButton.js');
     $displays = array();
     $displayConfig = I2CE::getConfig()->modules->CustomReports->displays;
     if (!in_array('Default', $displays)) {
         $displays[] = 'Default';
     }
     if (is_string($controls)) {
         $controls = array($controls);
     }
     if (is_array($controls)) {
         $displays = array_intersect($displays, $controls);
     }
     if (count($displays) == 0) {
         $displays[] = 'Default';
     }
     if (in_array('Default', $displays) && count($displays) > 1) {
         foreach ($displays as $i => $display) {
             $hide = false;
             $displayConfig->setIfIsSet($hide, "{$display}/hide_with_default");
             if ($hide) {
                 unset($displays[$i]);
             }
         }
     }
     if (count($displays) > 1 && I2CE::getFileSearch()->search('TEMPLATES', "customReports_display_limit_apply_{$this->display}.html")) {
         $reportLimitsNode = $this->template->getElementById('report_limits');
         if ($reportLimitsNode instanceof DOMNode) {
             $applyNode = $this->template->appendFileByNode("customReports_display_limit_apply_{$this->display}.html", "tr", $reportLimitsNode);
         }
     }
     foreach ($displays as $display) {
         if ($display != $this->display) {
             if (!($displayObj = $this->page->instantiateDisplay($display, "UserStatistics")) instanceof I2CE_CustomReport_Display) {
                 continue;
             }
             if (!$displayObj->canView()) {
                 continue;
             }
         } else {
             $displayObj = $this;
         }
         $controlNode = $this->template->createElement('span', array('class' => 'CustomReport_control', 'id' => "CustomReport_controls_{$display}"));
         $contentNode->appendChild($controlNode);
         $displayObj->displayReportControl($controlNode);
     }
     return true;
 }
 protected function dump($vars)
 {
     $file_name = $vars['name'];
     if (empty($file_name)) {
         //do nothing if name is not set
         I2CE::raiseError("No file specified", E_USER_NOTICE);
         return;
     }
     //get the extension
     if (array_key_exists('ext', $vars)) {
         $ext = strtolower($vars['ext']);
     } else {
         $ext = strtolower(substr(strrchr($file_name, "."), 1));
     }
     $category = null;
     if (array_key_exists('cat', $vars)) {
         $category = $vars['cat'];
     }
     if (empty($category)) {
         //try to see if we have a default category
         if (array_key_exists($ext, $this->default_categories)) {
             $category = $this->default_categories[$ext];
         }
         if (empty($category)) {
             //do nothing if no category found
             I2CE::raiseError("No file category specified for ({$file_name}). Valid categories are:" . print_r($this->default_categories, true), E_USER_NOTICE);
             I2CE::raiseError(print_r($this->default_categories, true));
             return;
         }
     }
     if (!in_array($category, $this->allowedCategories)) {
         //we are not allowed to search this category
         I2CE::raiseError("Not allowed to search category ({$category}).  Allowed are:\n" . print_r($this->allowedCategories, true), E_USER_NOTICE);
         return;
     }
     $file_loc = I2CE::getFileSearch()->search($category, $file_name);
     $locale = I2CE::getFileSearch()->getLocaleOfLastSearch();
     if (!$file_loc) {
         //do nothing if we can't find the file
         I2CE::raiseError("Cannot find ({$file_name}). Search category is {$category} , Path is:\n" . print_r(I2CE::getFileSearch()->getSearchPath($category), true), E_USER_NOTICE);
         return;
     }
     if (!array_key_exists('apdContent', $vars)) {
         $vars['apdContent'] = null;
     }
     if (!array_key_exists('content', $vars)) {
         $vars['content'] = null;
     }
     //$headers = $this->doHeader($file_name,$file_loc,$ext,$vars['content'],$vars['apdContent']);
     $headers = $this->doHeader($file_name, $ext, $vars['content'], $vars['apdContent']);
     $config = I2CE::getConfig();
     $cacheTime = 600;
     // defaults to 10 minutes
     if (isset($config->modules->FileDump->cache_time)) {
         $cacheTime = $config->modules->FileDump->cache_time * 60;
     }
     $ttl = 3600;
     // defaults to one hour
     if ($config->is_scalar("/modules/FileDump/ttl")) {
         $ttl = $config->modules->FileDump->ttl * 60;
     }
     if (I2CE_Dumper::dumpContents($file_loc, $headers, $cacheTime)) {
         I2CE_Dumper::cacheFileLocation(MDB2::singleton()->database_name, $file_name, $locale, $headers, $file_loc, $cacheTime, $ttl);
     }
 }
Exemple #10
0
 protected function load_file($category, $file_name)
 {
     $file = I2CE::getFileSearch()->search($category, $file_name);
     if (!$file) {
         I2CE::raiseError("Cannot find file ({$file_name})", E_USER_ERROR);
     }
     $a = file($file);
     if (empty($a)) {
         I2CE::raiseError("File ({$file}) is empty", E_USER_ERROR);
     }
     return $a;
 }
 function read_post()
 {
     $f = $this->gotoTable('post');
     /*Table 72: 'post' table
      *Type Name Description
      *Fixed format Format of this table
      *Fixed italicAngle Italic angle in degrees
      *FWord underlinePosition Underline position
      *FWord underlineThickness Underline thickness
      *uint32 isFixedPitch Font is monospaced; set to 1 if the font is monospaced and 0 otherwise 
      *       (N.B., to maintain compatibility with older versions of the TrueType spec, accept 
      *        any non-zero value as meaning that the font is monospaced)
      *uint32 minMemType42 Minimum memory usage when a TrueType font is downloaded as a Type 42 font
      *uint32 maxMemType42 Maximum memory usage when a TrueType font is downloaded as a Type 42 font
      *uint32 minMemType1 Minimum memory usage when a TrueType font is downloaded as a Type 1 font
      *uint32 maxMemType1 Maximum memory usage when a TrueType font is downloaded as a Type 1 font
      */
     $format_pieces = $this->read_fixed_pieces();
     $this->setDirection('-1');
     $this->setFontCharacteristic('ItalicAngle', $this->read_fixed_pieces());
     //FIXME
     $this->setFontCharacteristic('UnderlinePosition', $this->read_FWord());
     $this->setFontCharacteristic('UnderlineThickness', $this->read_FWord());
     $this->setFixedWidth($this->read_uint32() > 0);
     $this->read_uint32();
     $this->read_uint32();
     $this->read_uint32();
     $this->read_uint32();
     switch ($format_pieces[2]) {
         case 1:
             //258 GIDs in the standard mac ordering
             die("UNFINISHED BUSINESS\n");
             break;
         case 2:
             switch ($format_pieces[1]) {
                 case 0:
                     //format is 2.0
                     //this is the useful one.
                     /* Format 2 is used for fonts that contain some glyphs not in the standard set or whose glyph 
                      *ordering is non-standard. The glyph name index array in this subtable maps the glyphs in this 
                      *font to a name index. If the name index is between 0 and 257, treat the name index as a glyph 
                      *index in the Macintosh standard order. If the name index is between 258 and 32767, then subtract 
                      *258 and use that to index into the list of Pascal strings at the end of the table. In this manner 
                      *a font may map some of its glyphs to the standard glyph names, and some to its own names
                      */
                     /*Table 73: 'post' format 2
                      *Type Name Description
                      *uint16 numberOfGlyphs number of glyphs
                      *uint16 glyphNameIndex[numberOfGlyphs] Ordinal number of this glyph in 'post' string tables. This is not an offset.
                      *Pascal string names[numberNewGlyphs] glyph names with length bytes [variable] (a Pascal string)
                      */
                     $num_glyphs = $this->read_uint16();
                     if ($num_glyphs != $this->num_glyphs) {
                         die("Glyph number mismatch!\n");
                     }
                     $glyphNameIndex = array();
                     $numberNewGlyphs = 0;
                     for ($gid = 0; $gid < $num_glyphs; $gid++) {
                         $nameIndex = $this->read_uint16();
                         $glyphNameIndex[$gid] = $nameIndex;
                         if (258 < $nameIndex) {
                             $numberNewGlyphs++;
                         }
                     }
                     $name = array();
                     $mac_ordering_file = I2CE::getFileSearch()->search('PDF_CORE', 'mac-ordering');
                     if (!$mac_ordering_file) {
                         die("Cannont find the file <mac-ordering>\n");
                     }
                     $a = $this->loadin($mac_ordering_file);
                     $n = 0;
                     foreach ($a as $l) {
                         $l = rtrim($l);
                         $e = explode(" ", $l);
                         $names[(int) $e[0]] = $e[1];
                         $n++;
                     }
                     if ($n != 258) {
                         die("Invalid number of encodings in {$mac_ordering_file}");
                     }
                     for ($n = 258; $n <= 258 + $numberNewGlyphs; $n++) {
                         //read in pascal strings.  these are strings that are prefixed with a
                         //byte value which is their length;
                         $str_len = $this->read_uint8();
                         $names[$n] = fread($f, $str_len);
                         //READ PASCAL STRING
                     }
                     //read in the file containing postisctip name /codepoint mapping
                     $glyphToCP = array();
                     $postscript_names_file = I2CE::getFileSearch()->search('PDF_CORE', 'glyphlist.txt');
                     if (!$postscript_names_file) {
                         die("Cannont find the file <glyphlist.txt>\n");
                     }
                     $a = $this->loadin($postscript_names_file);
                     foreach ($a as $l) {
                         $l = trim($l);
                         if (strpos($l, '#') === 0) {
                             continue;
                         }
                         $e = explode(";", rtrim($l));
                         $cps = explode(' ', trim($e[1]));
                         foreach ($cps as $n => $cp) {
                             $cps[$n] = hexdec($cp);
                         }
                         $glyphToCP[$e[0]] = $cps;
                     }
                     //fix some incorrect glyphnames:
                     foreach ($names as $idx => $name) {
                         if (isset(self::$fix[$name])) {
                             $names[$idx] = self::$fix[$name];
                         }
                     }
                     //now convert glyphames to codepoints
                     $this->GIDtoCPs = array();
                     for ($gid = 0; $gid < $num_glyphs; $gid++) {
                         $cps = $glyphToCP[$names[$glyphNameIndex[$gid]]];
                         if ($cps === null) {
                             $name = $names[$glyphNameIndex[$gid]];
                             //Check to see if name starts with 'uni' followed by a 4 digit  hexadicimal 'uniHHHH'
                             //pull out the hexadecimal part
                             if ($name == '.notdef') {
                                 $cps = array(0xfffd);
                             } else {
                                 if (preg_match('/^uni([0-9A-Fa-f]{4,4})/', $name, $matches)) {
                                     $cps = array(hexdec($matches[1]));
                                 } else {
                                     if (preg_match('/^([0-9A-Fa-f]{4,4})$/', $name, $matches)) {
                                         $cps = array(hexdec($matches[1]));
                                     } else {
                                         //mark it as unknown.  we may try to fix it in setCIDtoGIDmap
                                         I2CE::raiseError("Warning: Unknown unicode codepoint for glyphname <{$name}>", E_NOTICE);
                                         $cps = array(-1);
                                     }
                                 }
                             }
                         }
                         $this->GIDtoCPs[$gid] = $cps;
                     }
                     break;
                 default:
                     //format is 2.5
                     break;
             }
             break;
         case 3:
             //useless
             break;
         case 4:
             //japanese/korean/chinese
             break;
     }
 }
 public function testGetFileSearch()
 {
     $fs = I2CE::getFileSearch();
     $this->assertTrue($fs instanceof I2CE_FileSearch);
 }
 /**
  *  Load the hyphenation dictionary.
  *
  *  The file is expected to be a 'mashed up' version of a .tex
  *  hyphenation dictionary geneareted by using substrings.pl
  *  as in the stand-along hyphenation code of
  *  http://lingucomponent.openoffice.org/hyphenator.html
  *  @param string $file file containing the dictionary
  */
 public function LoadHyphenDictionary($file)
 {
     /* we are working on the assumpition that $file is in ASCII  compatible ecoding */
     $found_file = I2CE::getFileSearch()->search('HYPHEN_PATH', $file);
     if (!$found_file) {
         die("Cannot find hyphenation file <{$file}>\n");
     }
     $f = fopen($found_file, 'rb');
     if (!$f) {
         die("Cannot open hyphenation file: <{$found_file}>");
     }
     $line = trim(fgets($f));
     //read in the characterset line
     if (!$line) {
         die("Empty hyphenation dictionary file/Cannot read: <{$found_file}>");
     }
     if (strpos($line, 'ISO8') === 0) {
         //we forgot a hyphen
         $character_set = 'ISO-' . substr($line, 3);
         //the character set of the  hyphenation dictionary
     } else {
         $character_set = $line;
     }
     $convert = false;
     $mb_encoding = $this->enc->getEncodingType();
     $convert = $mb_encoding == $character_set;
     $this->patterns = array();
     $this->trans = array();
     $nums = array();
     for ($i = 0; $i <= 9; $i++) {
         $nums[$i] = mb_convert_encoding("{$i}", $mb_encoding);
     }
     while ($line = trim(fgets($f))) {
         //read  in a line of the dictionary file
         if ($convert) {
             $line = mb_convert_encoding($line, $mb_encoding, $character_set);
         }
         if (mb_substr($line, 0, 1, $mb_encoding) != '%') {
             // this line is not a comment
             $pattern = array();
             $word = mb_convert_encoding('', $mb_encoding);
             $prev_char_was_letter = true;
             $line_len = mb_strlen($line, $mb_encoding);
             for ($i = 0; $i < $line_len; $i++) {
                 $curr_char = mb_substr($line, $i, 1, $mb_encoding);
                 $not_a_number = true;
                 $j = -1;
                 do {
                     $j++;
                     $not_a_number = $curr_char != $nums[$j];
                 } while ($j < 9 && $not_a_number);
                 if (!$not_a_number) {
                     $pattern[] = $j;
                     $prev_char_was_letter = false;
                 } else {
                     $word .= $curr_char;
                     if ($prev_char_was_letter) {
                         $pattern[] = 0;
                     }
                     $prev_char_was_letter = true;
                 }
             }
             if ($prev_char_was_letter) {
                 $pattern[] = 0;
             }
             $this->patterns[$word] = $pattern;
             $word_len = mb_strlen($word, $mb_encoding);
             for ($i = 1; $i <= $word_len; $i++) {
                 $this->trans[mb_substr($word, 0, $i)] = true;
             }
         }
     }
     fclose($f);
 }
 /**
  *Abstract method to render the form. Makes sure all ducks are in a row
  * @returns boolean true on sucess.
  */
 public function render()
 {
     if (count($this->ids) != 1) {
         I2CE::raiseError("Exactly one ID must be specifed (currently)");
         return false;
     }
     if (!is_string($this->std_form) || strlen($this->std_form) == 0) {
         I2CE::raiseError("No standard printed form set");
         return false;
     }
     $this->stdConfig = I2CE::getConfig()->traverse('/modules/PrintedForms/forms/' . $this->std_form, false);
     if (!$this->stdConfig instanceof I2CE_MagicDataNode) {
         I2CE::raiseError("No standard printed form   /modules/PrintedForms/forms/" . $this->std_form);
         return false;
     }
     if (!$this->stdConfig->setIfIsSet($relationship, 'relationship')) {
         I2CE::raiseError("No relationship set");
         return false;
     }
     try {
         $this->rel = new I2CE_FormRelationship($relationship, $this->base_rel_config);
     } catch (Exception $e) {
         I2CE::raiseError("Could not instatiate relationship {$relationship}");
         return false;
     }
     $template = false;
     $template_upload = false;
     if ($this->stdConfig->setIfIsSet($template_upload, 'template_upload', true) && array_key_exists('content', $template_upload) && $template_upload['content'] && array_key_exists('name', $template_upload) && $template_upload['name']) {
         $name = $template_upload['name'];
         $pos = strrpos($name, '.');
         if ($pos !== false) {
             $name = substr($name, 0, $pos);
         }
         $this->template_file = tempnam(sys_get_temp_dir(), basename($name . '_')) . '.odt';
         file_put_contents($this->template_file, $template_upload['content']);
     } else {
         if ($this->stdConfig->setIfIsSet($template, 'template')) {
             $this->template_file = I2CE::getFileSearch()->search('ODT_TEMPLATES', $template);
             if (!$this->template_file) {
                 I2CE::raiseError("No template file found from {$template}");
                 return false;
             }
         } else {
             I2CE::raiseError("No template  set");
             return false;
         }
     }
     $template_contents = new ZipArchive();
     if ($template_contents->open($this->template_file) !== TRUE) {
         I2CE::raiseError("Could not extract odt file");
         return;
     }
     $this->template_vars = array();
     for ($i = 0; $i < $template_contents->numFiles; $i++) {
         $stats = $template_contents->statIndex($i);
         if ($stats['name'] != 'content.xml') {
             continue;
         }
         $matches = array();
         //pull out all the template variables for processing.
         preg_match_all('/{{{([0-9a-zA-Z_\\-\\+\\,\\=\\.]+(\\(.*?\\))?)}}}/', $template_contents->getFromIndex($i), $matches, PREG_SET_ORDER);
         foreach ($matches as $match) {
             if (!is_array($match) || count($match) < 2 || !is_string($match[1]) || strlen($match[1]) == 0) {
                 continue;
             }
             $this->template_vars[] = $match[1];
         }
         $this->template_vars = array_unique($this->template_vars);
     }
     $this->content = $this->stdConfig->getAsArray('content');
     $forms = array();
     foreach ($this->ids as $id) {
         if (!is_string($id)) {
             continue;
         }
         $fs = $this->rel->getFormsSatisfyingRelationship($id);
         if (!is_array($fs) || count($fs) == 0) {
             continue;
         }
         $forms[$id] = $fs;
     }
     if (count($forms) == 0) {
         I2CE::raiseError("No valid forms");
         return false;
     }
     $this->forms = $forms;
     $textProps = array();
     I2CE::longExecution();
     $success = $this->_render($textProps);
     return $success;
 }
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have 
* received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
* @version 2.1
* @access public
*/
$translations_dir = "translations" . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR;
$usage[] = "Looks for .pot files in {$translations_dir}\n";
$set_categories = false;
$set_configs = false;
require_once "translate_base.php";
@(require_once "Archive/Tar.php");
if (!class_exists('Archive_Tar')) {
    usage('Please install the PEAR Archive_Tar package');
}
I2CE::setupFileSearch(array('MODULES' => getcwd()));
$fileSearch = I2CE::getFileSearch();
$module = $configurator->findAvailableConfigs($fileSearch, false);
if (count($module) != 1) {
    usage("No Modules Specified");
}
$module = $module[0];
$out_dir = 'translations' . DIRECTORY_SEPARATOR . 'launchpad';
$archive_file = $out_dir . DIRECTORY_SEPARATOR . 'templates-' . $module . '.tgz';
if ($translations_dir[strlen($translations_dir) - 1] == DIRECTORY_SEPARATOR) {
    $translations_dir = substr($translations_dir, 0, -1);
}
if (!is_dir($translations_dir) || !is_readable($translations_dir)) {
    usage("Could not find/read {$translations_dir} directory");
}
if (!is_dir($out_dir)) {
    if (!mkdir($out_dir, 0775, true)) {
 public function getFileData($form, $as_array = false)
 {
     if (($uri = $this->getFileURIType($form)) === false) {
         if ($as_array) {
             return array();
         } else {
             return false;
         }
     }
     $file = $this->_getFile($form);
     if ($uri == 'mdn') {
         return $this->getFileData_mdn($file, $as_array);
     } else {
         if ($uri == 'file') {
             $abs_file = null;
             if (!I2CE_FileSearch::isAbsolut($file)) {
                 $abs_file = I2CE::getFileSearch()->search($this->getSearchCategory($form), $file);
             } else {
                 $abs_file = $file;
             }
             if (!$abs_file || !is_readable($abs_file)) {
                 I2CE::raiseError("Could not find readable {$file} ({$abs_file})");
                 return false;
             }
         } else {
             $abs_file = $file;
         }
         return $this->getFileData_stream($abs_file, $as_array);
     }
 }
 /**
  * Finds newly available configuration files and stores them in the magic data.
  * @param mixed  $modules a string or array of strings:  
  * the shortnames of modules we wish to look for sub-modules.  If null (default), we check all enabled modules.
  * @return array of string the shortname of any modules we found (old and new)
  */
 public function checkForNewModules($modules = null)
 {
     if ($modules !== null) {
         if (!is_array($modules)) {
             $modules = array($modules);
         }
         $fileSearch = new I2CE_FileSearch();
         $this->loadPaths($modules, array('CLASSES', 'MODULES'), true, $fileSearch);
         //add in the class path and module paths for the new modules
     } else {
         $fileSearch = I2CE::getFileSearch();
     }
     require_once 'I2CE_Configurator.php';
     //need to explicitly put this in here b/c the system may  not be enabled
     $configurator = new I2CE_Configurator(I2CE::getConfig());
     return $configurator->findAvailableConfigs($fileSearch, false, '', true);
 }
 protected static function _updateModules($updates, $removals = array(), $optional_excludes = array(), $disables = array())
 {
     I2CE::raiseError("Updating Modules");
     //make sure everything is nice and fresh
     clearstatcache();
     $mod_factory = I2CE_ModuleFactory::instance();
     $exec = array('max_execution_time' => 20 * 60, 'memory_limit' => 256 * 1048576);
     I2CE::longExecution($exec);
     if (!is_array($updates)) {
         $updates = array($updates);
     }
     if (!is_array($removals)) {
         $removals = array($removals);
     }
     $msg = "Will attempt to update:\n";
     foreach (array('Updates' => $updates, 'Removals' => $removals, 'Disables' => $disables) as $k => $v) {
         if (count($v) > 0) {
             $msg .= "\t{$k}:\n\t\t" . implode(',', $v) . "\n";
         }
     }
     I2CE::raiseError($msg);
     $storage = I2CE::getConfig();
     $tmp_storage = I2CE_MagicData::instance("temp_ModuleFactory");
     $configurator = new I2CE_Configurator($tmp_storage);
     if ($storage->setIfIsSet($sitemodule, "config/site/module")) {
         I2CE::raiseError("Site is set at " . $storage->getPath() . ' to be ' . $sitemodule);
         //make sure the site direcotry is added in to the config path.
         $data = $configurator->checkRequirements($updates, $disables, $removals, $mod_factory->getEnabled(), $sitemodule);
     } else {
         I2CE::raiseError("Site is not set at " . $storage->getPath());
         $data = $configurator->checkRequirements($updates, $disables, $removals, $mod_factory->getEnabled());
     }
     //note that checkRequirements has the result of putting _all_ valid config module metadata under /config/data of $tmp_storage
     if (isset($data['failure'])) {
         $storage->clearCache();
         I2CE::raiseError("Installation failed: " . $data['failure']);
         return false;
     }
     foreach (array_keys($data['removals']) as $shortname) {
         if (!$mod_factory->disable($shortname)) {
             $storage->clearCache();
             I2CE::raiseError("Unable to disable {$shortname}", E_USER_NOTICE);
             return false;
         }
     }
     //now we remove from the requirements list anything that is already enabled and  up-to-date
     if (count($data['moved']) > 0) {
         I2CE::raiseError("Found the following in another location.  Attempting to move:" . implode(',', array_keys($data['moved'])));
         I2CE::setupFileSearch(array(), true);
         //reset the file search and clear its cache
         I2CE::getFileSearch()->addPath('MODULES', dirname(dirname(__FILE__)), 'EVEN_HIGHER');
     }
     $skipped = array();
     $moved = array();
     foreach ($data['requirements'] as $shortname => $file) {
         if (!$mod_factory->isEnabled($shortname)) {
             continue;
         }
         if ($mod_factory->isUpToDate($shortname, $file) && $mod_factory->isUpToDateModule($shortname)) {
             //everything is in the correct place and up to date.
             $skipped[] = $shortname;
             $mod_factory->loadPaths($shortname, null, true);
             //for the loading of all categories for this module
             $storage->config->data->{$shortname}->file = $data['requirements'][$shortname];
             I2CE::raiseError("Updated {$shortname} config file to be " . $data['requirements'][$shortname]);
             unset($data['requirements'][$shortname]);
             //this module is enabled and the config is up-to-date so we dont need to do anything
             continue;
         }
         //let us see if this module has been moved
         if (!$storage->__isset("config/data/{$shortname}")) {
             continue;
         }
         if (!$tmp_storage->__isset("config/data/{$shortname}")) {
             continue;
         }
         $meta = $storage->config->data->{$shortname};
         $tmp_meta = $tmp_storage->config->data->{$shortname};
         foreach (array("hash", "last_access") as $key) {
             if (!isset($meta->{$key}) || !isset($tmp_meta->{$key}) || $tmp_meta->{$key} !== $meta->{$key}) {
                 continue 2;
             }
         }
         $class_file = null;
         $tmp_meta->setIfIsSet($class_file, "class/file");
         if ($class_file && ($class_file = I2CE_FileSearch::realPath($class_file))) {
             if (!$meta->__isset("class/hash")) {
                 continue;
             }
             if (!is_readable($class_file)) {
                 continue;
             }
             $contents = file_get_contents($class_file);
             if (!$contents) {
                 continue;
             }
             if ($meta->class->hash !== md5($contents)) {
                 continue;
             }
         }
         $mtimes = array();
         foreach (array("class/file", "file") as $f) {
             if (!isset($tmp_meta->{$f})) {
                 continue;
             }
             @($mtimes[$f] = filemtime(I2CE_FileSearch::realPath($tmp_meta->{$f})));
             if (!$mtimes[$f]) {
                 continue 2;
             }
         }
         if (false == $mod_factory->checkLocalesUpToDate($shortname, $class_file)) {
             //the locales for this module are not up to date
             continue;
         }
         //we made it here.  we can skip the update.
         I2CE::raiseError("Able to move config file for {$shortname} from:\n  " . $meta->file . "\nto:\n  " . $tmp_meta->file);
         foreach (array("class/file" => "class/last_access", "file" => "last_access") as $f => $a) {
             $val = null;
             $tmp_meta->setIfIsSet($val, $f);
             if ($val === null) {
                 continue;
             }
             $meta->{$f} = $val;
             $meta->{$a} = $mtimes[$f];
             $tmp_meta->{$a} = $mtimes[$f];
         }
         unset($data['requirements'][$shortname]);
         //this module is enabled and the config is up-to-date so we dont need to do anything
         $mod_factory->loadPaths($shortname, null, true);
         //for the loading of all categories for this module
         $moved[] = $shortname;
     }
     if (count($skipped) > 0) {
         I2CE::raiseError("Skipping update on the following up-to-date modules:" . implode(',', $skipped));
     }
     if (count($moved) > 0) {
         I2CE::raiseError("Moved the following  modules:" . implode(',', $moved));
     }
     I2CE::raiseError("Attempting to update/enable the following out of date modules: " . implode(',', array_keys($data['requirements'])));
     //make sure all of our class paths for existing moduels are loaded.
     $good_modules = array_diff($mod_factory->getEnabled(), $data['removals'], array_keys($data['requirements']));
     I2CE::raiseError("The following modules class paths are being added:\n\t" . implode(',', $good_modules));
     $mod_factory->loadPaths($good_modules, 'CLASSES', true);
     if (!array_key_exists('optional', $data) || !is_array($data['optional'])) {
         $data['optional'] = array();
     }
     if (is_string($optional_excludes)) {
         $optional_excludes = array($optional_excludes);
     }
     if (!is_array($optional_excludes)) {
         $optional_excludes = array();
     }
     $to_enable = array_merge($data['requirements'], $data['optional']);
     //while (count ($data['requirements']) > 0) {
     I2CE::raiseError("Trying to enable the following required:\n" . implode(" ", array_keys($data['requirements'])));
     I2CE::raiseError("Trying to enable the following optional:\n" . implode(" ", array_keys($data['optional'])));
     I2CE::raiseError("Trying to enable the following:\n" . implode(" ", array_keys($to_enable)));
     while (count($to_enable) > 0) {
         $shortname = key($to_enable);
         // reset ($data['requirements']);
         // $shortname = key($data['requirements']);
         if (!is_string($shortname) || strlen($shortname) == 0) {
             I2CE::raiseError("Invalid Shortname");
             continue;
         }
         $file = array_shift($to_enable);
         if (array_key_exists($shortname, $data['optional']) && in_array($shortname, $optional_excludes)) {
             continue;
         }
         $old_vers = '0';
         $storage->setIfIsSet($old_vers, "/config/data/{$shortname}/version");
         $new_vers = null;
         $tmp_storage->setIfIsSet($new_vers, "/config/data/{$shortname}/version");
         $mod_config = $tmp_storage->config->data->{$shortname};
         $storage->__unset("/config/data/{$shortname}");
         //set the module's metadata to the new stuff.
         $storage->config->data->{$shortname} = $mod_config;
         //keep the old version set around until we know that the module was upgraded
         $storage->config->data->{$shortname}->version = $old_vers;
         if (!$tmp_storage->__isset("/config/data/{$shortname}/class/name")) {
             //there is no class associated in the new version of  this module.
             if ($storage->__isset("/config/data/{$shortname}/class/name")) {
                 //there was a class previously assoicated to this module -- remove its hooks/fuzzy methods,
                 $mod_factory->removeHooks($shortname);
                 unset($storage->config->data->{$shortname}->class);
             }
         }
         foreach (array('conflict' => 'conflict_external', 'requirement' => 'requirement_external') as $type => $key) {
             if ($mod_config->is_parent($key)) {
                 foreach ($mod_config->{$key} as $ext => $req_data) {
                     if ($req_data instanceof I2CE_MagicDataNode) {
                         $req_data = $req_data->getAsArray();
                     } else {
                         $req_data = array();
                     }
                     foreach ($req_data as $req_d) {
                         if (!is_array($req_d) || !array_key_exists('eval', $req_d) || !$req_d['eval']) {
                             continue;
                         }
                         $eval = null;
                         @eval('$eval = ' . $req_d['eval'] . ';');
                         if (is_bool($eval) && !$eval) {
                             if (self::failedRequiredUpdate($shortname, $data, "Could not verify external {$type} {$ext} for {$shortname}", $configurator)) {
                                 return false;
                             } else {
                                 continue 4;
                             }
                         }
                     }
                 }
             }
         }
         $mod_storage = I2CE_MagicData::instance("temp_ModuleFactory_" . $shortname);
         I2CE::getFileSearch()->addPath('MODULES', dirname(dirname(__FILE__)), 'EVEN_HIGHER');
         $r_file = I2CE_FileSearch::realPath($file);
         $mod_configurator = new I2CE_Configurator($mod_storage);
         $s = $mod_configurator->processConfigFile($r_file, false, true, true, false);
         if (!is_string($s)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could load configuration file", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         if ($s != $shortname) {
             //be super safe
             if (self::failedRequiredUpdate($shortname, $data, "Configuration shortname mismatch ({$s}/{$shortname})", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         self::processErasers($mod_config, $old_vers);
         $loaded = self::loadModuleMagicData($shortname, $r_file, $old_vers, $new_vers, $mod_configurator);
         if ($loaded === false) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not load magic data", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         $loaded_mod_config = $mod_storage->config->data->{$shortname};
         self::processErasers($loaded_mod_config, $old_vers);
         if (!self::preUpgradeModule($shortname, $old_vers, $new_vers, $mod_storage)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not pre-update module", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         //if $loaded === true, then there was no magic data to update, so we can skip the store.
         if (is_array($loaded) && !self::storeModuleMagicData($shortname, $old_vers, $new_vers, $mod_configurator, $loaded)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not store magic data", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         if (!self::upgradeModule($shortname, $old_vers, $new_vers)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not upgrade module", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         if (!self::postUpdateModule($shortname, $old_vers, $new_vers)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not post update module", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         $mod_factory->setModuleHash($shortname);
         $mod_factory->setModuleClassHash($shortname, false);
         $mod_configurator->__destruct();
         $mod_configurator = null;
         $mod_storage->erase();
         $mod_storage = null;
         $storage = I2CE::getConfig();
         //just to make sure that any upgrades did not change the storage.  this happens with i2ce install for example
         $storage->config->data->{$shortname}->version = $new_vers;
         //we updated this module.  update the permanent modules config data with the temporary
         $mod_factory->loadPaths($shortname, null, true);
         //for the loading of all categories for this module
     }
     I2CE::raiseError("Enabled Modules: " . implode(',', $mod_factory->getEnabled()));
     return true;
 }
 /**
  * Produces  a .dot file for the given forms as a string
  * @param array $forms of string the forms
  */
 public function dot($forms)
 {
     $nodes = array();
     $paths = array();
     $config = I2CE::getConfig();
     $scheme_details = $this->getSchemeDetails('dot');
     if (array_key_exists('colors', $scheme_details) && is_array($scheme_details['colors'])) {
         $form_groups = $scheme_details['colors'];
     } else {
         $form_groups = array();
     }
     $node_groups = array();
     sort($forms);
     foreach ($forms as $form) {
         if (!($formObj = $this->form_factory->createContainer($form)) instanceof I2CE_Form) {
             continue;
         }
         $color = 'ivory3';
         foreach ($form_groups as $m_form => $m_color) {
             if (strpos($form, $m_form) !== false) {
                 $color = $m_color;
                 break;
             }
         }
         $fields = array();
         foreach ($formObj as $field => $fieldObj) {
             if (!($field_def = $this->reverseFieldDef(get_class($fieldObj)))) {
                 continue;
             }
             if (!$fieldObj->isInDB()) {
                 continue;
             }
             $header = trim($fieldObj->getHeader());
             $req = '';
             if ($fieldObj->getOption('required')) {
                 $req = ' *';
             }
             $unique = '';
             if ($fieldObj->hasOption('unique') && $fieldObj->getOption('unique')) {
                 if ($fieldObj->hasOption('unique_field') && ($unique_field = $fieldObj->getOption('unique_field'))) {
                     $unique = '!∈ \\{' . trim($unique_field) . '\\} ';
                 } else {
                     $unique = '! ';
                 }
                 if ($req) {
                     $unique = ',' . $unique;
                 } else {
                     $unique = ' ' . $unique;
                 }
             }
             $header = $header . $req . $unique;
             if ($header) {
                 $fields[] = '<tr><td ALIGN=\'LEFT\'>' . $field . ' (' . $field_def . ')' . '</td></tr><tr><td ALIGN=\'LEFT\'>  <font color=\'grey30\'>' . $header . '</font></td></tr>';
             } else {
                 $fields[] = '<tr><td ALIGN=\'LEFT\'>' . $field . ' (' . $field_def . ')' . '</td></tr>';
             }
             if (!$this->check_map) {
                 continue;
             }
             if (!$fieldObj instanceof I2CE_FormField_MAPPED) {
                 continue;
             }
             $map_forms = array_intersect($fieldObj->getSelectableForms(), $forms);
             sort($map_forms);
             if (count($map_forms) > 1) {
                 if (!array_key_exists('splitter+', $node_groups)) {
                     $node_groups['splitter+'] = array();
                 }
                 $node_groups['splitter+'][] = "\"splitter+{$form}+{$field}\" [shape=point size = 1 label = \"\"  ] ;";
                 $paths[] = "\"{$form}\" -> \"splitter+{$form}+{$field}\" [arrowhead = none label = \"{$field}\" ];";
                 foreach ($map_forms as $map_form) {
                     if (!in_array($map_form, $forms)) {
                         continue;
                     }
                     $paths[] = "\"splitter+{$form}+{$field}\" -> \"{$map_form}\"  ;";
                 }
             } else {
                 if (count($map_forms) == 1) {
                     reset($map_forms);
                     $map_form = current($map_forms);
                     if (in_array($map_form, $forms)) {
                         if ($field !== $map_form) {
                             $paths[] = "\"{$form}\" -> \"{$map_form}\" [ label = \"{$field}\" ]  ;";
                         } else {
                             $paths[] = "\"{$form}\" -> \"{$map_form}\"  ;";
                         }
                     }
                 }
             }
         }
         $label = '<table border=\'0\' cellborder=\'0\'><tr><td BGCOLOR=\'white\' BORDER=\'1\'>' . $form . ' (' . get_class($formObj) . ') </td></tr>' . implode('', $fields) . '</table>';
         if (!array_key_exists($color, $node_groups) || !is_array($node_groups[$color])) {
             $node_groups[$color] = array();
         }
         $node_groups[$color][$form] = "\"{$form}\" [style=filled fillcolor = {$color}   label =<{$label}> shape = \"Mrecord\"   ];";
         $child_forms = array_intersect($formObj->getChildForms(), $forms);
         sort($child_forms);
         if (count($child_forms) > 0) {
             foreach ($child_forms as $child_form) {
                 $paths[] = "\"{$form}\" -> \"{$child_form}\" [color=firebrick];";
             }
         }
     }
     if (array_key_exists('graph_options', $scheme_details) && is_array($scheme_details['graph_options'])) {
         $graph_options = $scheme_details['graph_options'];
     } else {
         $graph_options = array();
     }
     if (!array_key_exists('label', $graph_options) || !$graph_options['label'] || $graph_options['label'] == "''" || $graph_options['label'] == '""') {
         $module = $this->getModule();
         $title = $this->getDisplayName($module);
         $version = $this->getVersion($module);
         if ($version) {
             $title .= ' - ' . $version;
         }
         $graph_options['label'] = '"' . $title . '"';
     }
     $bgcolor = 'white';
     if (array_key_exists('bgcolor', $graph_options)) {
         $bgcolor = $graph_options['bgcolor'];
     }
     $graph_details = "graph [";
     foreach ($graph_options as $key => $val) {
         $graph_details .= "\n\t\t" . $key . '=' . $val;
     }
     $graph_details .= "\n\t];\n\tratio = auto;\n";
     foreach ($node_groups as $colors => $ns) {
         foreach ($ns as $n) {
             $nodes[] = $n;
         }
     }
     $graph = "digraph g {\n\t{$graph_details}\n\t" . implode("\n\t", $nodes) . implode("\n\t", $paths) . "\n}\n";
     $dot_file = $this->getOutputFile('dot');
     if (file_put_contents($dot_file, $graph) === false) {
         I2CE::raiseError("Could not write to {$dot_file}");
     } else {
         I2CE::raiseError(".dot graph file saved to {$dot_file}");
     }
     $dot = trim(`which dot`);
     $unflatten = trim(`which unflatten`);
     if (!$dot || !$unflatten) {
         I2CE::raiseError("the dot utility was not found on your system.  cannot create the imate. try sudo apt-get install dot");
         return;
     }
     $output_file = $this->getOutputFile('gif');
     $dot = "{$unflatten} -f -l 2 -c 2 | {$dot} -T gif ";
     $composite = trim(`which composite`);
     $convert = trim(`which convert`);
     if ($composite) {
         $watermark_file = I2CE::getFileSearch()->search('IMAGES', 'form_documentor_legend.gif');
         $watermark = '';
         if ($watermark_file) {
             if ($convert) {
                 $watermark = "  |{$convert} gif:-   -bordercolor white  -border 0x100 - |{$composite} -gravity SouthEast  {$watermark_file} gif:- ";
             } else {
                 $watermark = "  |{$composite} -gravity SouthEast  {$watermark_file} -splice 0x20 gif:-   ";
             }
         }
         $exec = $dot . $watermark . $output_file;
     } else {
         I2CE::raiseError("Imagemagick utitilies were not found on your system.  cannot watermark the file. try sudo apt-get isntall imagemagick");
         $exec = $dot . '-o ' . $output_file;
     }
     I2CE::raiseError("Attempting to execute:\n\t" . $exec);
     $proc = popen($exec, "w");
     if (!is_resource($proc)) {
         I2CE::raiseError("Could not start execute");
     } else {
         fwrite($proc, $graph);
         fclose($proc);
         I2CE::raiseError("You should now have a graph at {$output_file}");
     }
     return;
 }
 protected function action()
 {
     parent::action();
     if (!array_key_exists('maps', $this->args) || !is_array($this->args['maps']) || count($this->args['maps']) == 0) {
         $this->template->setDisplayDataImmediate('map_error', 'No map data in page arguments.');
         return true;
     }
     if (array_key_exists('title', $this->args)) {
         $this->template->setDisplayDataImmediate('openlayers_title', $this->args['title']);
     }
     $maps = $this->args['maps'];
     $ol_mod = I2CE_ModuleFactory::instance()->getClass('OpenLayers');
     $ol_mod->addMapDefaults($maps);
     $default_height = null;
     $default_width = null;
     if (array_key_exists('_height', $maps)) {
         $default_height = $maps['_height'];
     }
     if (array_key_exists('_width', $maps)) {
         $default_width = $maps['_width'];
     }
     //$maps['map']['layers']['facilities']['gradient'] = array( '#000', '#00f', '#0f0', '#ff0', '#f00' );
     $map_data = $ol_mod->processOptions('maps', $maps);
     if (count($map_data) != 2 || !is_array($map_data[1])) {
         $this->template->setDisplayDataImmediate('map_error', 'Invalid map data in page arguments.');
         return true;
     }
     foreach ($maps as $map_name => $map) {
         if ($map_name[0] == '_') {
             continue;
         }
         $map_node = $this->template->appendFileById("openlayers_map.html", "div", "maps");
         $this->template->setAttribute('id', "{$map_name}_map", 'map', null, $map_node);
         $this->template->setAttribute('id', "{$map_name}_feature_details", 'feature_details', null, $map_node);
         $height = $default_height;
         if (array_key_exists('_height', $map)) {
             $height = $map['_height'];
         }
         $width = $default_width;
         if (array_key_exists('_width', $map)) {
             $width = $map['_width'];
         }
         if ($width) {
             $this->template->setAttribute('style', "width: {$width};", "{$map_name}_feature_details", null, $map_node);
         }
         if ($height || $width) {
             $this->template->setAttribute('style', ($height ? "height: {$height};" : '') . ($width ? "width: {$width};" : ''), "{$map_name}_map", null, $map_node);
         }
         if (!array_key_exists('layers', $map)) {
             $this->template->setDisplayDataImmediate('map_error', "No layer data in page arguments for {$map_name}.");
             return true;
         }
     }
     $js = "window.addEvent('domready', function() { \n";
     foreach ($map_data[1] as $prepend) {
         $js .= "{$prepend}\n";
     }
     $js .= $map_data[0] . "\n";
     $page_js = I2CE::getFileSearch()->search('SCRIPTS', 'openlayers_post_inline_' . $this->page . '.js');
     if ($page_js) {
         //$this->template->addHeaderLink( 'openlayers_' . $this->page . '.js' );
         $js .= file_get_contents($page_js);
     }
     $js .= "});\n";
     $this->template->addHeaderText($js, "script", 'openlayers_maps');
 }
function getTranslatableDocuments($show_bad = true)
{
    global $categories;
    global $found_modules;
    I2CE::raiseError("Getting Translate-able Documents");
    getAvailableModules();
    I2CE::raiseError("Will attempt to  template files for the following modules:\n\t" . implode(",", array_keys($found_modules)));
    $factory = I2CE_ModuleFactory::instance();
    $templates = array();
    foreach ($found_modules as $module => $top_module) {
        I2CE::setupFileSearch();
        //reset the file search.
        $fileSearch = I2CE::getFileSearch();
        $good_paths = array();
        $bad_paths = array();
        foreach ($categories as $cat) {
            $fileSearch->setPreferredLocales($cat, I2CE_Locales::DEFAULT_LOCALE);
            //only search the en_US locale
            $factory->loadPaths($module, $cat, true, $fileSearch);
            //load all template paths
            $ordered_paths = $fileSearch->getSearchPath($cat, true);
            //get the paths found with their localization;
            if (count($ordered_paths) == 0) {
                //echo "\tNo $cat directories for $module. -- Skipping\n";
                continue;
            }
            foreach ($ordered_paths as $paths) {
                foreach ($paths as $path => $locale) {
                    if ($locale !== I2CE_Locales::DEFAULT_LOCALE) {
                        //should not happen.
                        var_dump($locale);
                        die("Yell at Carl -- you have locale {$locale} instead of " . I2CE_Locales::DEFAULT_LOCALE . "\n");
                    }
                    $dir = basename($path);
                    if ($dir != I2CE_Locales::DEFAULT_LOCALE) {
                        $bad_paths[] = $path;
                    } else {
                        $good_paths[$path] = I2CE_Locales::DEFAULT_LOCALE;
                    }
                }
            }
        }
        if ($show_bad && count($bad_paths) > 0) {
            I2CE::raiseError("The following template paths for {$module} were not localized:\n\t" . implode("\n\t", $bad_paths));
        }
        if (count($good_paths) == 0) {
            //echo "\tNo localized template files for $module -- Skipping\n";
            continue;
        }
        foreach ($good_paths as $path => $locale) {
            $rec_path = $path . DIRECTORY_SEPARATOR . '**';
            //do a recursive search
            $files = $fileSearch->resolve(array('/^.*\\.html?$/'), array($rec_path => I2CE_Locales::DEFAULT_LOCALE), true);
            if (is_array($files) && count($files) > 0) {
                $templates[$module][$path] = $files;
            }
        }
    }
    if (count($templates) == 0) {
        I2CE::raiseError("None of the modules available are setup with localized tempaltes.  Nothing to do.");
    } else {
        I2CE::raiseError("The following modules has translatable templates:\n\t" . implode(",", array_keys($templates)));
    }
    return $templates;
}
 public function generate($id, $stream = true)
 {
     I2CE::longExecution(array("max_execution_time" => 1800));
     if (!($doc = $this->get_doc_for_id($id)) instanceof DOMDocument) {
         I2CE::raiseError("Could not get document for " . $this->formRelationship->getPrimaryForm() . "|{$id}");
         return false;
     }
     $contents = $doc->saveXML($doc->documentElement);
     $transform_src = false;
     $transform_file = false;
     $trans_is_temp = false;
     if (!($this->request_exists('transform') && $this->request('transform') == 0)) {
         //allow request varible to turn of transform to check underlying data source easily
         if (array_key_exists('transform', $this->args) && is_string($this->args['transform'])) {
             $transform_src = $this->args['transform'];
         }
         if (is_string($transform_src) && strlen($transform_src)) {
             if ($transform_src[0] == '@') {
                 //it's a file.  search for it.
                 $file = substr($transform_src, 1);
                 if (!($transform_file = I2CE::getFileSearch()->search('XSLTS', $file))) {
                     I2CE::raiseError("Invalid transform file at {$file} => {$transform_file}\n" . print_r(I2CE::getFileSearch()->getSearchPath('XSLTS'), true));
                     return false;
                 }
             } else {
                 if (substr($transform_src, 0, 7) == 'file://') {
                     $transform_file = substr($transform_src, 7);
                 } else {
                     $trans_is_temp = true;
                     $transform_file = tempnam(sys_get_temp_dir(), 'XSL_REL_');
                     file_put_contents($transform_file, $transform_src);
                 }
             }
         }
     }
     if ($stream) {
         if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
             I2CE::raiseError("Got errors:\n{$errors}");
         }
         header('Content-Type: text/xml');
         flush();
         if ($transform_file) {
             $temp_file = tempnam(sys_get_temp_dir(), 'XML_REL_SINGLE_');
             file_put_contents($temp_file, $contents);
             $cmd = $this->get_transform_cmd($contents, $temp_file, $transform_file);
             passthru($cmd);
             unlink($temp_file);
             if ($trans_is_temp) {
                 unlink($transform_file);
             }
         } else {
             echo $contents;
         }
         exit(0);
     } else {
         if ($transform_file) {
             $temp_file = tempnam(sys_get_temp_dir(), 'XML_REL_SINGLE_');
             file_put_contents($temp_file, $contents);
             $cmd = $this->get_transform_cmd($contents, $temp_file, $transform_file);
             $trans = shell_exec($cmd);
             unlink($temp_file);
             if ($trans_is_temp) {
                 unlink($transform_file);
             }
             return $trans;
         } else {
             return $contents;
         }
     }
 }
Exemple #23
0
 /**
  * Executes a script
  * @param string $file.  The SQL file to execute -- it must lie in the fileSearch's SQL category
  * (this is ensured by addinging it to a <path name='sql'> node in the configuration XML
  * @param string $database.  If non-null it will connect to the named database.  
  * @param mixed $transact defaults to true meaning that the whole script is executed in a transaction.  If a string, it is the name of
  * a save point to use (assumes you are already in a transaction)
  * @param string $dsn.  An option DSN to connect on.  If set $database is ignored.
  * it will use whatever database is refered to by the MDB2::singleton()
  * @param string $delimiter.  Defaults to ';' Needs to be exactly one character
  * @return boolean  -- true on sucess, false on failure
  */
 public static function runSQLScript($file, $database = null, $transact = true, $dsn = null, $delimiter = ';')
 {
     $t_file = I2CE::getFileSearch()->search('SQL', $file);
     if (!$t_file) {
         I2CE::raiseError("Couldn't find SQL script: {$file}.\nSearch Path is:\n" . print_r(I2CE::getFileSearch()->getSearchPath('SQL'), true), E_USER_NOTICE);
         return false;
     }
     $file = $t_file;
     if ($dsn !== null) {
         $database = null;
         $db = MDB2::connect($dsn);
         if (I2CE::pearError($db, "Cannot connect to database {$database}")) {
             return false;
         }
         $db->loadModule('Extended');
         $db->setFetchMode(MDB2_FETCHMODE_OBJECT, 'MDB2_row');
         $db->query("SET NAMES 'utf8'");
     } else {
         if ($database !== null) {
             $db = MDB2::singleton();
             $oldDB = $db->database_name;
         } else {
             $db = MDB2::singleton();
         }
     }
     if ($database !== null) {
         if (I2CE::pearError($db->query('USE ' . $db->quoteIdentifier($database)), "Cannot use database {$database}")) {
             return false;
         }
     }
     $transact_msg = '';
     $savepoint = null;
     if ($transact === true) {
         if (!$db->supports('transactions')) {
             $transact = false;
             $transact_msg = 'No Transactions used (Not supported)';
         } else {
             if ($db->in_transaction) {
                 $transact = 'SCRIPT_EXECUTE_' . rand(1000, 9999);
                 $transact_msg = "Using savepoint {$transact} (Already in transaction)";
             } else {
                 $transact_msg = "Transaction on";
             }
         }
     } else {
         if (is_string($transact)) {
             if ($db->in_transaction) {
                 $transact_msg = "Using savepoint {$transact}";
             } else {
                 $transact_msg = "Transaction on (Savepoint {$transact} ignored because not in transaction)";
                 $transact = true;
             }
         } else {
             $transact = false;
             $transact_msg = 'No Transactions used (None specified)';
         }
     }
     I2CE::raiseError("Running SQL Script at {$file}: " . $transact_msg);
     $result = self::explodeAndExecuteSQLQueries(file_get_contents($file), $db, $transact, $delimiter);
     if ($database !== null) {
         if (I2CE::pearError($db->query('USE ' . $db->quoteIdentifier($oldDB)), "Cannot use database {$oldDB}")) {
             return false;
         }
     }
     if (!$result) {
         I2CE::raiseError("Script excution failed for {$file}");
         return false;
     }
     return true;
 }
 /**
  * Process results
  * @param array $results_data an array of results.  indices are 'results' and MDB2 Buffered result and 'num_results' the
  * number of results.  (these values may be false on failure)
  * @param DOMNode $contentNode.  Default to null a node to append the results onto
  */
 protected function processResults($results_data, $contentNode = null)
 {
     if ($this->page->request_exists('flash_data')) {
         require_once I2CE::getFileSearch()->search('MAANI_CHART_FILES', 'charts.php');
         if (substr($this->defaultOptions['displayFieldsType'], 0, 7) == 'one_row') {
             $this->preProcessResultsOneRow();
         } else {
             $this->preProcessResultsMultiRow();
         }
         parent::processResults($results_data, $contentNode);
         if (!array_key_exists('num_results', $results_data) || $results_data['num_results'] == 0) {
             // Nothing was found so just show a message instead of
             // the confusing default report.
             unset($this->chart['chart_data']);
             unset($this->chart['draw']['print']);
             $this->chart['chart_rect']['x'] = 1000;
             $this->chart['chart_rect']['y'] = 1000;
             $this->chart['legend_rect']['x'] = 1000;
             $this->chart['legend_rect']['y'] = 1000;
             $message = "Error!";
             I2CE::getConfig()->setIfIsSet($message, "/modules/CustomReports/displays/PieChart/error_message");
             $msg_arr = explode("\n", wordwrap($message, 40));
             $start_y = 25;
             foreach ($msg_arr as $num => $msg_line) {
                 $this->chart['draw']['error' . $num] = array('color' => '000000', 'size' => 25, 'type' => 'text', 'text' => $msg_line, 'height' => 100, 'width' => 500, 'x' => 25, 'y' => $start_y);
                 $start_y += 25;
             }
             $this->SendChartData();
         }
         if (substr($this->defaultOptions['displayFieldsType'], 0, 7) == 'one_row') {
             $this->postProcessResultsOneRow();
         } else {
             $this->postProcessResultsMultiRow();
         }
         $this->setupHeightWidth();
         $this->SendChartData();
     } else {
         // I don't think this ever gets called anymore?  Can it just be removed?
         I2CE::raiseError("I don't think this should be called this way anymore.  It's being added to display() instead.");
         //just make a reference to the chart
         $i2ce_config = I2CE::getConfig();
         $license = '';
         $license = $i2ce_config->setIfIsSet($license, 'modules/maani-charts/license');
         //$results_data will be false b/c we called parent::display($contentNode,false) in display() above
         if (!$contentNode instanceof DOMNode) {
             return false;
         }
         $this->template->addHeaderLink('swfobject.js');
         $flashDataURL = 'index.php/file/charts.swf?library_path=index.php/file/charts_library';
         if ($license) {
             $flashDataURL .= '&license=' . $license;
         }
         $save_req = "flash_data&" . file_get_contents("php://input") . "&" . $_SERVER['QUERY_STRING'];
         $req_key = md5($save_req);
         $_SESSION['req_query'][$req_key] = $save_req;
         $flashDataURL .= '&php_source=' . urlencode("index.php/CustomReports/show/{$this->view}/{$this->display}?req_query=" . $req_key);
         $js = "\tif(window.addEvent) { window.addEvent('domready', function() { swfobject.embedSWF('{$flashDataURL}', \n\t\t'{$report_results}', '{$this->defaultOptions['flash_width']}', " . " '{$this->defaultOptions['flash_height']}', '9.0.0' ,'expressInstall.swf',  \n\t\t" . " {}, \n\t\t{quality: 'high', bgcolor:'{$this->defaultOptions['flash_bgcolor']}',wmode:'opaque'}\n\t); } ); } ";
         $this->template->addHeaderLink('mootools-core.js');
         $this->template->addHeaderText($js, 'script', true);
         //add this to a new script node.
         return true;
     }
 }
 /**
  * Produces  a .dot file for the given modules as a string
  * @param array $modules of string the modules
  */
 public function dot($modules)
 {
     $mod_factory = I2CE_ModuleFactory::instance();
     $nodes = array();
     $paths = array();
     $scheme_details = $this->getSchemeDetails('dot');
     $config = I2CE::getConfig();
     if (array_key_exists('colors', $scheme_details) && is_array($scheme_details['colors'])) {
         $mod_groups = $scheme_details['colors'];
     } else {
         $mod_groups = array();
     }
     $node_groups = array();
     $config = I2Ce::getConfig();
     $mod_config = $config->config->data;
     foreach ($modules as $module) {
         if (!$mod_config->is_parent($module)) {
             continue;
         }
         $color = 'ivory3';
         foreach ($mod_groups as $m_module => $m_color) {
             if (strpos($module, $m_module) !== false) {
                 $color = $m_color;
                 break;
             }
         }
         $className = $mod_factory->getClassName($module);
         if ($className) {
             $className = ' (' . $className . ')';
         }
         $mod_data = array();
         foreach (array('displayName') as $key) {
             if (!$mod_config->is_scalar("{$module}/{$key}")) {
                 continue;
             }
             $mod_data[] = $mod_config->{$module}->{$key};
         }
         foreach ($mod_data as &$d) {
             $d = '<tr><td ALIGN=\'LEFT\'>' . $d . '</td></tr>';
         }
         $label = '<table border=\'0\' cellborder=\'0\'><tr><td BGCOLOR=\'white\' BORDER=\'1\'>' . $module . $className . '</td></tr>' . implode('', $mod_data) . '</table>';
         if (!array_key_exists($color, $node_groups) || !is_array($node_groups[$color])) {
             $node_groups[$color] = array();
         }
         $node_groups[$color][$module] = "\"{$module}\" [style=filled fillcolor = {$color}   label =<{$label}> shape = \"Mrecord\"   ];";
         if ($mod_config->is_parent("{$module}/requirement")) {
             $requirements = array_intersect($modules, $mod_config->getKeys("{$module}/requirement"));
         } else {
             $requirements = array();
         }
         if ($mod_config->is_parent("{$module}/conflict")) {
             $conflicts = array_intersect($modules, $mod_config->getKeys("{$module}/conflict"));
         } else {
             $conflicts = array();
         }
         if ($mod_config->is_parent("{$module}/enable")) {
             $enabled = array_intersect($modules, $mod_config->getKeys("{$module}/enable"));
         } else {
             $enabled = array();
         }
         foreach ($requirements as $req) {
             $paths[] = "\"{$module}\" -> \"{$req}\";";
         }
         foreach ($enabled as $end) {
             $paths[] = "\"{$module}\" -> \"{$end}\" [color=forestgreen];";
         }
         foreach ($conflicts as $con) {
             $paths[] = "\"{$module}\" -> \"{$con}\" [color=yellow];";
         }
     }
     $config = I2CE::getConfig();
     $module = $config->config->site->module;
     if (!$module) {
         I2CE::raiseError("No site module");
         return $graph;
     }
     if (array_key_exists('graph_options', $scheme_details) && is_array($scheme_details['graph_options'])) {
         $graph_options = $scheme_details['graph_options'];
     } else {
         $graph_options = array();
     }
     if (!array_key_exists('label', $graph_options) || !$graph_options['label'] || $graph_options['label'] == "''" || $graph_options['label'] == '""') {
         $title = 'Module Documentor';
         $version = '';
         $u_version = '';
         if ($config->setIfIsSet($title, "/config/data/{$module}/displayName")) {
             $title = str_ireplace('Demonstration', '', $title);
             $title = str_ireplace('Demo', '', $title);
             $title = trim($title);
             if ($config->setIfIsSet($version, "/config/data/{$module}/version")) {
                 $title .= ' - ' . $version;
                 $u_version = '_' . strtr($version, '.', '_');
             }
         }
         $graph_options['label'] = '"' . $title . '"';
     }
     $bgcolor = 'white';
     if (array_key_exists('bgcolor', $graph_options)) {
         $bgcolor = $graph_options['bgcolor'];
     }
     $graph_details = "graph [";
     foreach ($graph_options as $key => $val) {
         $graph_details .= "\n\t\t" . $key . '=' . $val;
     }
     $graph_details .= "\n\t];\n\tratio = auto;\n";
     foreach ($node_groups as $colors => $ns) {
         foreach ($ns as $n) {
             $nodes[] = $n;
         }
     }
     $graph = "digraph g {\n\t{$graph_details}\n\t" . implode("\n\t", $nodes) . implode("\n\t", $paths) . "\n}\n";
     $dot = trim(`which dot`);
     $unflatten = trim(`which unflatten`);
     if (!$dot || !$unflatten) {
         I2CE::raiseError("the dot utility was not found on your system.  cannot create the imate. try sudo apt-get install dot");
         return $graph;
     }
     $output_file = '/tmp/modules_' . $module . $u_version . '.gif';
     $dot = "{$unflatten} -f -l 2 -c 2 | {$dot} -T gif ";
     $composite = trim(`which composite`);
     $composite = false;
     if ($composite) {
         $watermark_file = I2CE::getFileSearch()->search('IMAGES', 'module_documentor_legend.gif');
         $watermark = '';
         if ($watermark_file) {
             $bgcolor_change = '';
             if (strtolower($bgcolor) != 'white') {
                 $bgcolor_change = "-fuzz 5% -fill {$bgcolor} -opaque white";
             }
             $watermark = "  |{$composite} gif:-  -gravity SouthEast  {$bgcolor_change} {$watermark_file} ";
         }
         $exec = $dot . $watermark . $output_file;
     } else {
         I2CE::raiseError("Imagemagick utitilies were not found on your system.  cannot watermark the file. try sudo apt-get isntall imagemagick");
         $exec = $dot . '-o ' . $output_file;
     }
     I2CE::raiseError("Attempting to execute:\n\t" . $exec);
     $proc = popen($exec, "w");
     if (!is_resource($proc)) {
         I2CE::raiseError("Could not start execute");
     } else {
         fwrite($proc, $graph);
         fclose($proc);
     }
     return $graph;
 }
 protected function action()
 {
     parent::action();
     if (!$this->config instanceof I2CE_MagicDataNode) {
         $this->reshow(true);
         //show the parent node.
         return;
     }
     $reshow = false;
     switch ($this->page()) {
         case 'upload':
             I2CE::raiseError("Upload on " . $this->config->getPath(false) . "\n" . print_r($_FILES, true));
             if (!array_key_exists('upload', $_FILES) || array_key_exists('error', $_FILES['upload']) && $_FILES['upload']['error'] > 0 || ($upload = file_get_contents($_FILES['upload']['tmp_name'])) === false) {
                 $this->userMessage("Could not upload " . $_FILES['upload']['name']);
                 break;
             }
             if (strlen($upload) != $_FILES['upload']['size']) {
                 I2CE::raiseError("Upload size mismatch " . strlen($upload) . ' != ' . $_FILES['upload']['size']);
                 $this->userMessage("Could not upload " . $_FILES['upload']['name']);
                 break;
             }
             if ($this->config->is_parent()) {
                 $this->userMessage("Cannot set value on parent node");
                 break;
             }
             $content = $this->config;
             if ($content->is_parent()) {
                 $this->userMessage("Cannot overwrite content node");
                 break;
             }
             if ($content->hasAttribute('binary') && $content->getAttribute('binary')) {
                 $upload = base64_encode($upload);
                 $content->setValue($upload);
                 $content->setAttribute('encoding', 'base64');
                 $content->setAttribute('binary', '1');
             } else {
                 $content->setValue($upload);
             }
             break;
         case 'upload_binary':
             I2CE::raiseError("Upload Binary on " . $this->config->getPath(false) . "\n" . print_r($_FILES, true));
             if (!array_key_exists('upload', $_FILES) || array_key_exists('error', $_FILES['upload']) && $_FILES['upload']['error'] > 0 || ($upload = file_get_contents($_FILES['upload']['tmp_name'])) === false) {
                 $this->userMessage("Could not upload " . $_FILES['upload']['name']);
                 break;
             }
             if (strlen($upload) != $_FILES['upload']['size']) {
                 I2CE::raiseError("Upload size mismatch " . strlen($upload) . ' != ' . $_FILES['upload']['size']);
                 $this->userMessage("Could not upload " . $_FILES['upload']['name']);
                 break;
             }
             if ($this->config->is_scalar()) {
                 $this->userMessage("Cannot set value on parent node");
                 break;
             }
             $content = $this->config->traverse('content', true, false);
             $name = $this->config->traverse('name', true, false);
             $type = $this->config->traverse('type', true, false);
             if ($content->is_parent()) {
                 $this->userMessage("Cannot overwrite content node");
                 break;
             }
             if ($name->is_parent()) {
                 $this->userMessage("Cannot overwrite content node");
                 break;
             }
             if ($type->is_parent()) {
                 $this->userMessage("Cannot overwrite type node");
                 break;
             }
             //I2CE::raiseError("Setting " . $this->config->getPath() );
             $upload = base64_encode($upload);
             $content->setValue($upload);
             $name->setValue($_FILES['upload']['name']);
             $type->setValue($_FILES['upload']['type']);
             $content->setAttribute('binary', 1);
             $content->setAttribute('encoding', 'base64');
             break;
         case 'load':
             I2CE::raiseError("Begin load:" . print_r($this->request(), true));
             $transform = false;
             if (($transform_key = $this->request('transform_key')) && I2CE_MagicDataNode::checkKey($transform_key) && I2CE::getConfig()->setIfIsSet($transform, "/modules/magicDataBrowser/transforms/" . $this->request('transform_key')) && $transform) {
                 if (substr($transform, 0, 7) == 'file://' && (!($transform_file = I2CE::getFileSearch()->search('XSL', $file_name = substr($transform, 7))) || !($transform = file_get_contents($transform_file)))) {
                     I2CE::raiseError("Could not load {$file_name} for transform");
                     $this->userMessage("Invalid registered transform");
                     return false;
                 }
             } else {
                 if (array_key_exists('transform', $_FILES) && !(array_key_exists('error', $_FILES['transform']) && $_FILES['transform']['error'] > 0)) {
                     $transform = file_get_contents($_FILES['transform']['tmp_name']);
                 }
             }
             I2CE::raiseError("Loading with transform:{$transform}");
             if ($this->actionLoad($transform)) {
                 $this->userMessage("Data successuly loaded");
             } else {
                 $this->userMessage("There was a problem loading the data");
             }
             break;
         case 'erase':
             $name = $this->config->getName();
             $parent = $this->config->traverse('../');
             if ($this->isPost() && $this->config->getPath() != $this->config->traverse('/')->getPath()) {
                 //don't allow an erase of the top level node
                 unset($parent->{$name});
             }
             $reshow = true;
             break;
         case 'parent':
             if ($this->isPost() && $this->config->is_indeterminate()) {
                 $this->config->set_parent();
             }
             break;
         case 'scalar':
             if ($this->isPost() && $this->config->is_indeterminate()) {
                 $this->config->set_scalar();
             }
             break;
         case 'add':
             if ($this->post_exists('browser_magic_data_add_key')) {
                 $key = $this->post('browser_magic_data_add_key');
                 if (I2CE_MagicDataNode::checkKey($key) && !$this->config->pathExists($key)) {
                     $this->config->traverse($key, true, false);
                 }
             }
             break;
         case 'add_parent':
             if ($this->post_exists('browser_magic_data_add_key')) {
                 $key = $this->post('browser_magic_data_add_key');
                 if (I2CE_MagicDataNode::checkKey($key) && !$this->config->pathExists($key) && ($newNode = $this->config->traverse($key, true, false)) instanceof I2CE_MagicDataNode) {
                     $newNode->set_parent();
                 }
             }
             break;
         case 'add_scalar':
             if ($this->post_exists('browser_magic_data_add_key')) {
                 $key = $this->post('browser_magic_data_add_key');
                 if (I2CE_MagicDataNode::checkKey($key) && !$this->config->pathExists($key) && ($newNode = $this->config->traverse($key, true, false)) instanceof I2CE_MagicDataNode) {
                     $newNode->set_scalar();
                 }
             }
             break;
         case 'set':
             I2CE::raiseError("Try to set:0");
             if ($this->post_exists('browser_magic_data_value') && $this->post_exists('browser_magic_data_key')) {
                 I2CE::raiseError("Try to set:1");
                 $key = $this->post('browser_magic_data_key');
                 $value = $this->post('browser_magic_data_value');
                 if ($this->config->offsetExists($key) && is_scalar($value)) {
                     I2CE::raiseError("Try to set:2");
                     if ($this->config->is_translatable($key)) {
                         $locales = I2CE_Locales::getPreferredLocales();
                         reset($locales);
                         $locale = current($locales);
                         $this->config->setTranslation($locale, $value, $key);
                         if ($locale == I2CE_Locales::DEFAULT_LOCALE) {
                             $this->config->__set($key, $value);
                         }
                     } else {
                         $this->config[$key] = $value;
                     }
                 }
             }
             //we redirect so a reload does not post and so that if the page's display depends on the value that is being
             //set, we redisplay it.
             break;
         case 'download':
             if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
                 I2CE::raiseError("Errors:\n" . $errors);
             }
             $value = $this->config->getValue();
             header("Cache-Control: max-age=1, s-maxage=1, no-store, no-cache, must-revalidate");
             header('Cache-Control: post-check=0, pre-check=0', false);
             header('Pragma: no-cache');
             header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10) . " GMT");
             header("ETag: PUB" . time());
             header("Pragma: no-cache");
             header("Content-length: " . strlen($value));
             header('Content-Disposition: attachment; filename="' . $this->config->getName() . '"');
             $mime_type = I2CE_MimeTypes::magicMimeType($value);
             I2CE::raiseError($mime_type);
             header('Content-type:' . $mime_type);
             session_cache_limiter("nocache");
             echo $value;
             die;
         case 'trans':
             $this->config->setTranslatable(null, !$this->config->is_translatable());
             break;
         case 'show':
         case 'mini':
             $this->actionDisplayConfig();
             $reshow = null;
             break;
         default:
             break;
     }
     if ($reshow !== null) {
         $this->reshow($reshow);
     }
 }
 protected function getODTTemplate()
 {
     //print_r($this->args);
     if (array_key_exists('template_upload', $this->args) && is_array($template_upload = $this->args['template_upload']) && array_key_exists('content', $template_upload) && $template_upload['content'] && array_key_exists('name', $template_upload) && $template_upload['name']) {
         $name = $template_upload['name'];
         $pos = strrpos($name, '.');
         $ext = '';
         if ($pos !== false) {
             $ext = substr($name, $pos);
             $name = substr($name, 0, $pos);
         }
         $this->template_file = tempnam(sys_get_temp_dir(), basename($name . '_')) . $ext;
         file_put_contents($this->template_file, $template_upload['content']);
     } else {
         if (array_key_exists('template_file', $this->args) && ($template = $this->args['template_file'])) {
             $this->template_file = I2CE::getFileSearch()->search('ODT_TEMPLATES', $template);
             if (!$this->template_file) {
                 I2CE::raiseError("No template file found from {$template}");
                 return false;
             }
         }
     }
 }
 /**
  * This method finds the location of a template file.If the file is not an absolute file path, it searches the class path 'XML'
  * 
  * This method searches the template directory path from the global configuration array
  * for the given template.  If it exists it returns the full path to the file and if not
  * it returns false.  It seaches the path backwards so that later directories
  * can override package versions of files.
  * @param string $template The name of the template file.
  * @param boolean $raise_error Defaults to true.  Raise error if template is not found
  * @return mixed
  */
 public function findTemplate($template, $raise_error = true)
 {
     if (I2CE_FileSearch::isAbsolut($template)) {
         return $template;
     }
     $template_file = I2CE::getFileSearch()->search('XML', $template);
     if ($template_file) {
         return $template_file;
     } else {
         if ($raise_error) {
             $this->raiseError("Couldn't find template file: {$template}.\nSearch Path is:\n" . print_r(I2CE::getFileSearch()->getSearchPath('TEMPLATES'), true), E_USER_NOTICE);
         }
         return false;
     }
 }
/**
 * The autoload function is used to load class files when needed
 * 
 * This function will be used to load any class files when they
 * are required instead of in every file.
 * 
 * It searchs the configuration array for the common class directory
 * as well as the class directory specifically for this project.
 * @global array
 * @param string $class_name The name of the class being loaded
 */
function i2ce_class_autoload($class_name)
{
    $class_file = I2CE::getfileSearch()->search('CLASSES', $class_name . '.php');
    $class_found = false;
    if ($class_file) {
        require_once $class_file;
        if (class_exists($class_name, false) || interface_exists($class_name, false)) {
            $class_found = true;
        } else {
            I2CE::raiseError("Defintion for class {$class_name} is not contained in {$class_file}", E_USER_WARNING);
        }
    }
    if (!$class_found) {
        $classes = I2CE_ModuleFactory::callHooks('autoload_search_for_class', $class_name);
        $count = count($classes);
        foreach ($classes as $class) {
            if (!is_string($class) || strlen($class) == 0) {
                continue;
            }
            if (false === eval($class)) {
                I2CE::raiseError("While looking for {$class_name}, could not parse: {$class}");
            }
            if (class_exists($class_name, false)) {
                $class_found = true;
                break;
            }
        }
    }
    if (!$class_found) {
        $debug = debug_backtrace();
        $msg = "Cannot find the defintion for class ({$class_name})";
        if (array_key_exists(1, $debug) && array_key_exists('line', $debug[1])) {
            $msg .= "called from  line " . $debug[1]['line'] . ' of file ' . $debug[1]['file'];
        }
        $msg .= "\nSearch Path is:\n" . print_r(I2CE::getFileSearch()->getSearchPath('CLASSES'), true);
        //        I2CE::raiseError( $msg, E_USER_NOTICE);
    }
}
 /**
  *  Load the font metrics from an afm  file
  *  (Some of this code was stolen from makefont.php)
  *  @param I2CE_Encoding $encoding -- the character encoding  used in the file
  *  @param string $afmfile
  *  Caution:  Units for these files are 1/1000 of a point where a point is 1/72 of an inch
  */
 protected function loadFontMetricFromAFM($encoding, $afmfile)
 {
     $prev_dir = $this->getDirection();
     $sub = mb_substitute_character();
     mb_substitute_character("none");
     //Read a font metric file
     $found_afmfile = I2CE::getFileSearch()->search('AFM_PATH', $afmfile);
     if (!$found_afmfile) {
         die('Error: AFM file not found: ' . $afmfile);
     } else {
         $afmfile = $found_afmfile;
     }
     $a = file($found_afmfile);
     if (empty($a)) {
         die('File empty' . $afmfile);
     }
     $this->setGlobal();
     //global information is the default
     $this->setLinegap(0);
     //no line gap information is present in a AFM file
     $mode = 0;
     /**
      * Modes are 0: header or wirting direction
      * 10: Character metrics
      * 20: Kerning
      * 21: Kerning Tracking
      * 21: Kerning Pairs 
      * 30: Composites
      */
     foreach ($a as $l) {
         $e = explode(' ', rtrim($l));
         $code = $e[0];
         switch ($mode) {
             case 10:
                 //character metrics
                 $vals = array();
                 unset($cc);
                 unset($gn);
                 switch ($code) {
                     case 'EndCharacterMetrics':
                     case 'EndCharMetrics':
                         $mode = 0;
                         continue 2;
                         //break out of the switch($mode)
                     //break out of the switch($mode)
                     case 'C':
                         $cc = (int) $e[1];
                         break;
                     case 'CH':
                         $cc = hexdec($e[1]);
                         break;
                 }
                 if (!isset($cc)) {
                     break;
                 }
                 $i = 3;
                 while ($i < count($e)) {
                     $subcode = $e[$i];
                     switch ($subcode) {
                         case 'WX':
                         case 'W0X':
                         case 'W1X':
                         case 'WY':
                         case 'W0Y':
                         case 'W1Y':
                             //widths and heights
                             $vals[$subcode] = (double) $e[$i + 1];
                             $i = $i + 2;
                             break;
                         case 'W':
                         case 'W0':
                         case 'W1':
                         case 'VV':
                             //widths and heights
                             $vals[$subcode] = array((double) $e[$i + 1], (double) $e[$i + 2]);
                             $i = $i + 3;
                             break;
                         case 'N':
                             //postscript glyph name
                             $gn = $e[$i + 1];
                             $i = $i + 2;
                             break;
                         case 'B':
                             //bounding box
                             $vals[$subcode] = array((double) $e[$i + 1], (double) $e[$i + 2], (double) $e[$i + 3], (double) $e[$i + 4]);
                             $i = $i + 5;
                             break;
                         case 'L':
                             //Ligature sequence -- may have more than one
                             if (!isset($vals['L'])) {
                                 $vals['L'] = array();
                             }
                             $vals['L'][] = array($e[$i + 1], $e[$i + 2]);
                             $i = $i + 3;
                             $i++;
                             break;
                         default:
                             $i++;
                             break;
                     }
                 }
                 unset($uc);
                 if ($cc < 0) {
                     //not a valid character code
                     if ($gn !== null) {
                         //try to get the unicode code point of the glyphname based on our encoding
                         $uc = $encoding->UnicodeFromGlyphname($gn);
                         if ($uc === null) {
                             //we failed
                             //try to get a unicode code point from the glyphname
                             if (preg_match('/^uni([0-9A-F]{4})$/', $gn, $ucs)) {
                                 //we have a unicode codepoint
                                 $uc = $ucs[1];
                             }
                         }
                     }
                 } else {
                     //we have a valid character code
                     $uc = $encoding->UnicodeFromCharactercode($cc);
                     if ($gn !== null) {
                         $this->gn2cc[$gn] = $cc;
                     }
                 }
                 if ($uc !== null && $uc <= 0xffff && $uc >= 0 && $uc !== 0xfffd) {
                     //replacement character
                     $uc = I2CE_UTF8::cp_to_code($uc);
                     //convert to UTF8
                     $cc = mb_convert_encoding($uc, $this->getEncoding()->getEncodingType(), 'UTF-8');
                     if ($this->getEncoding()->useMB()) {
                         if (mb_strlen($cc, $this->getEncoding()->getEncodingType()) === 0) {
                             $cc = -1;
                         }
                     } else {
                         if (strlen($cc) === 0) {
                             $cc = -1;
                         }
                     }
                 } else {
                     $cc = -1;
                 }
                 foreach (array('WX', 'W0X') as $key) {
                     if (array_key_exists($key, $vals) && $vals[$key] !== null) {
                         $this->setDirection('H');
                         if ($cc !== -1) {
                             $this->setCharacterWidth($cc, $vals[$key]);
                         }
                         if ($gn !== null) {
                             $this->setCharacterWidth($gn, $vals[$key]);
                         }
                     }
                 }
                 if (array_key_exists('W1X', $vals) && $vals['W1X'] !== null) {
                     $this->setDirection('V');
                     if ($cc !== -1) {
                         $this->setCharacterWidth($cc, $vals['W1X']);
                     }
                     if (null !== $gn) {
                         $this->setCharacterWidth($gn, $vals['W1X']);
                     }
                 }
                 foreach (array('WY', 'W0Y') as $key) {
                     if (array_key_exists($key, $vals) && null !== $vals[$key]) {
                         $this->setDirection('H');
                         if ($cc !== -1) {
                             $this->setCharacterHeight($cc, $vals[$key]);
                         }
                         if (null !== $gn) {
                             $this->setCharacterHeight($gn, $vals[$key]);
                         }
                     }
                 }
                 if (array_key_exists('W1Y', $vals) && null !== $vals['W1Y']) {
                     $this->setDirection('V');
                     if ($cc !== -1) {
                         $this->setCharacterHeight($cc, $vals['W1Y']);
                     }
                     if (null !== $gn) {
                         $this->setCharacterHeight($gn, $vals['W1Y']);
                     }
                 }
                 foreach (array('W', 'W0') as $key) {
                     $this->setDirection('H');
                     if (array_key_exists($key, $vals) && null !== $vals[$key]) {
                         if ($cc !== -1) {
                             $this->setCharacterWidth($cc, $vals[$key]);
                             $this->setCharacterHeight($cc, $vals[$key]);
                         }
                         if (null !== $gn) {
                             $this->setCharacterWidth($gn, $vals[$key]);
                             $this->setCharacterHeight($gn, $vals[$key]);
                         }
                     }
                 }
                 if (array_key_exists('W1', $vals) && null !== $vals['W1']) {
                     $this->setDirection('V');
                     if ($cc !== -1) {
                         $this->setCharacterWidth($cc, $vals[$key]);
                         $this->setCharacterHeight($cc, $vals[$key]);
                     }
                     if (null !== $gn) {
                         $this->setCharacterWidth($gn, $vals[$key]);
                         $this->setCharacterHeight($gn, $vals[$key]);
                     }
                 }
                 foreach (array('VVector' => 'VV', 'BoundingBox' => 'B', 'Ligature' => 'L') as $name => $key) {
                     $this->setGlobal();
                     if (array_key_exists($key, $vals) && null !== $vals[$key]) {
                         if ($cc !== -1) {
                             $this->setCharacterInfo($cc, $name, $vals[$key]);
                         }
                         if (null !== $gn) {
                             $this->setCharacterInfo($gn, $name, $vals[$key]);
                         }
                     }
                 }
                 break;
             case 20:
                 //kerning
                 switch ($code) {
                     case 'EndKernData':
                         $mode = 0;
                         break;
                     case 'StartTrackKern':
                         $mode = 21;
                         break;
                     case 'StartKernPairs':
                     case 'StartKernPairs0':
                         $this->setDirection('H');
                         $mode = 22;
                         break;
                     case 'StartKernPairs1':
                         $this->setDirection('V');
                         $mode = 22;
                         break;
                 }
                 break;
             case 21:
                 //kerning tracking
                 switch ($code) {
                     case 'EndTrackKern':
                         $mode = 20;
                         break;
                     case '':
                         break;
                 }
                 break;
             case 22:
                 //kerning pairs
                 switch ($code) {
                     case 'EndKernPairs':
                         $mode = 21;
                         break;
                     case 'KP':
                         //kerning pairs are given by glyph name
                         $this->setDirection('H');
                         $this->setKerningByPair($e[1], $e[2], (double) $e[3]);
                         $this->setDirection('V');
                         $this->setKerningByPair($e[1], $e[2], (double) $e[4]);
                         //get the corresponding character codes and insert into the table
                         $this->setGlobal();
                         $cc1 = $this->getEncoding()->getCodeFromGlyphname($e[1]);
                         $cc2 = $this->getEncoding()->getCodeFromGlyphname($e[2]);
                         if ($cc1 !== -1 && $cc2 !== -1) {
                             $this->setDirection('H');
                             $this->setKerningByPair($cc1, $cc2, (double) $e[3]);
                             $this->setDirection('V');
                             $this->setKerningByPair($cc1, $cc2, (double) $e[4]);
                         }
                         break;
                     case 'KPH':
                         //not sure what is best to do here.
                         $ch1 = ltrim(rtrim($e[1], '>'), '<');
                         $ch2 = ltrim(rtrim($e[1], '>'), '<');
                         $this->setDirection('H');
                         $this->setKerningByPair($ch1, $ch2, (double) $e[3]);
                         $this->setDirection('V');
                         $this->setKerningByPair($ch1, $ch2, (double) $e[4]);
                         break;
                     case 'KPX':
                         $this->setDirection('H');
                         $this->setKerningByPair($e[1], $e[2], (double) $e[3]);
                         if (!array_key_exists($e[1], $this->gn2cc) || !array_key_exists($e[2], $this->gn2cc)) {
                             break;
                         }
                         $cc1 = $this->gn2cc[$e[1]];
                         $cc2 = $this->gn2cc[$e[2]];
                         if ($cc1 !== -1 && $cc2 !== -1) {
                             $this->setKerningByPair($cc1, $cc2, (double) $e[3]);
                         }
                         break;
                     case 'KPY':
                         $this->setDirection('V');
                         $this->setKerningByPair($e[1], $e[2], (double) $e[3]);
                         if (!array_key_exists($e[1], $this->gn2cc) || !array_key_exists($e[2], $this->gn2cc)) {
                             break;
                         }
                         $cc1 = $this->gn2cc[$e[1]];
                         $cc2 = $this->gn2cc[$e[2]];
                         if ($cc1 !== -1 && $cc2 !== -1) {
                             $this->setKerningByPair($cc1, $cc2, (double) $e[3]);
                         }
                         break;
                 }
                 break;
             case 30:
                 //composites
                 switch ($code) {
                     case 'EndComposites':
                         $mode = 0;
                         break;
                 }
                 break;
             default:
                 //header/global information or writing direction
                 switch ($code) {
                     case 'BeginCharacterMetrics':
                     case 'StartCharMetrics':
                         $mode = 10;
                         break;
                     case 'BeginKernData':
                     case 'StartKernData':
                         $mode = 20;
                         break;
                     case 'BeginComposites':
                     case 'StartComposites':
                         $mode = 03;
                         break;
                     case 'StartDirection':
                         //does not have to exist in which case we are in direction 0
                         if ($e[1] == '1') {
                             $this->setDirection('V');
                         } else {
                             $this->setDirection('H');
                         }
                         break;
                     case 'EndDirection':
                         $this->setGlobal();
                         break;
                     case 'CharWidth':
                         $dir = $this->getDirection();
                         //this is not global information
                         if ($dir === -1) {
                             // however the keyword StartDirection is optional
                             $this->setDirection('H');
                         }
                         $this->setFixedWidth(true);
                         $this->setFixedWidthSize((double) $e[1]);
                         $this->setFixedHeightSize((double) $e[2]);
                         $this->setDirection($dir);
                         break;
                     case 'UnderlinePosition':
                     case 'UnderlineThickness':
                     case 'ItalicAngle':
                         $dir = $this->getDirection();
                         //this is not global information
                         if ($dir === -1) {
                             // however the keyword StartDirection is optional
                             $this->setDirection('H');
                         }
                         $this->setFontCharacteristic($code, $e[1]);
                         $this->setDirection($dir);
                         break;
                     case 'IsFixedPitch':
                         $isfixed = strpos(strtolower($e[1]), 'true') === 0;
                         $dir = $this->getDirection();
                         //this is not global information
                         if ($dir === -1) {
                             // however the keyword StartDirection is optional
                             $this->setDirection('H');
                         }
                         $this->setFixedWidth($isfixed);
                         $this->setDirection($dir);
                         break;
                     case 'isFixedV':
                     case 'isBaseFont':
                         $this->setGlobal();
                         $this->setFontCharacteristic($code, strpos(strtolower($e[1]), 'true'));
                         break;
                     case 'MappingScheme':
                     case 'EscCar':
                     case 'Characters':
                         $this->setGlobal();
                         $this->setFontCharacteristic($code, (int) $e[1]);
                         break;
                     case 'Notice':
                     case 'Comment':
                         $this->setGlobal();
                         $val = $this->getFontCharacteristic($code);
                         if ($val === null) {
                             $val = "";
                         }
                         $this->setFontCharacteristic($code, $val . substr($l, strlen($code) + 1));
                         break;
                     case 'CapHeight':
                     case 'XHeight':
                         $this->setGlobal();
                         $this->setFontCharacteristic($code, (double) $e[1]);
                         break;
                     case 'Ascender':
                         $this->setGlobal();
                         $this->setAscender((double) $e[1]);
                         break;
                     case 'Descender':
                         $this->setGlobal();
                         $this->setDescender((double) $e[1]);
                         break;
                     case 'VVector':
                         $this->setGlobal();
                         $this->setFontCharacteristic($code, array((double) $e[1], (double) $e[2]));
                     case 'FontBBox':
                         $this->setGlobal();
                         $this->setBoundingBox(array((double) $e[1], (double) $e[2], (double) $e[3], (double) $e[4]));
                         break;
                     default:
                         //the rest are strings for global font information
                         $this->setGlobal();
                         $this->setFontCharacteristic($code, $e[1]);
                         break;
                 }
                 break;
         }
     }
     //normalize a few values.
     $this->setGlobal();
     $asc = $this->getAscender();
     if ($asc == 0) {
         $d = mb_convert_encoding('d', $this->getEncoding()->getEncodingType(), 'ASCII');
         $ht = $this->getCharacterHeight($d);
         if ($ht != 0) {
             $this->setAscender($ht);
         } else {
             $this->setDirection('H');
             $ht = $this->getCharacterHeight($d);
             if ($ht != 0) {
                 $this->setAscender($ht);
             } else {
                 $this->setGlobal();
                 $bbox = $this->getBoundingBox();
                 $this->setAscender($bbox[3]);
             }
         }
     }
     $this->setGlobal();
     $dsc = $this->getAscender();
     if ($dsc == 0) {
         $p = mb_convert_encoding('p', $this->getEncoding()->getEncodingType(), 'ASCII');
         $bbox = $this->getCharacterInfo($p, 'BoundingBox');
         if (!$bbox == null) {
             $this->setDescender($bbox[1]);
         } else {
             $this->setDirection('H');
             $bbox = $this->getCharacterInfo($p, 'BoundingBox');
             if (!$bbox == null) {
                 $this->setDescender($bbox[1]);
             } else {
                 $this->setGlobal();
                 $bbox = $this->getBoundingBox();
                 $this->setDescender($bbox[1]);
             }
         }
     }
     $this->setDirection($prev_dir);
     mb_substitute_character($sub);
 }